
//****************************************
//* Initalize Variables                  *
//****************************************


// Commandbar
// var DSExplorer=new Object();
// top.DSExplorer='test';
// if (top.DSExplorer.GUIPlaces==undefined)
//	top.stylebase=new Array();
DSExplorer = new Object()
DSExplorer.GUIPlace=new Object();
DSExplorer.Workflow=new Object();
//DSExplorer.GUIPlace.CommandBar='';
//DSExplorer.GUIPlace.ContextMenu='';
//DSExplorer.GUIPlace.Paging='';
// alert(Object.keys(DSExplorer.GUIPlace));
//alert(top.DSExplorer.GUIPlaces.CommandBar);

// Set GUI Object
var dsnavname='undefined';
DSGUIObject_Active=new Object();

// 2008-09-27 [Ap]
var DS= {};

// Set Language Variables
function DSLang(variable) {
	var thisvariable=DSJS.LCase(variable);
	var returnvariable=DSLangArray['lang_'+thisvariable];
	if (returnvariable==undefined)
		returnvariable='undefined: '+thisvariable;

	return returnvariable;
}

//****************************************
//* END Initalize Variables              *
//****************************************

var dcbe = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body? document.body : null;
var naviuser = navigator.userAgent.toLowerCase();
var opera = !!(window.opera && document.getElementById);
var opera6 = opera && !document.defaultView;
var opera7 = opera && !opera6;
var ie = (navigator.appName == "Microsoft Internet Explorer");
var ns6 = !opera && !document.all && document.documentElement;
//ns6 = (!opera && document.defaultView && typeof document.defaultView.getComputedStyle != 'undefined');
var w3c = !ie && !ns6 && !opera && document.getElementById;


function DSInit(){
	dcbe = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body? document.body : null;
	naviuser = navigator.userAgent.toLowerCase();
	opera = !!(window.opera && document.getElementById);
	opera6 = opera && !document.defaultView;
	opera7 = opera && !opera6;
	ie = naviuser.indexOf("msie") != -1 && document.all && dcbe && !opera;
	ns6 = !opera && !document.all && document.documentElement;
	//ns6 = (!opera && document.defaultView && typeof document.defaultView.getComputedStyle != 'undefined');
	w3c = !ie && !ns6 && !opera && document.getElementById;	
}


if(window.name==null || window.name=='')
	window.name='ds';

var Engine = {
  detect: function() {
    var UA = navigator.userAgent;
    this.isKHTML = /Konqueror|Safari|KHTML/.test(UA);
    this.isGecko = (/Gecko/.test(UA) && !this.isKHTML);
    this.isOpera = /Opera/.test(UA);
    this.isMSIE  = (/MSIE/.test(UA) && !this.isOpera);
		this.isMSIE7 = this.isMSIE && (UA.indexOf('MSIE 7') != -1);
  }
}

Engine.detect();



Position.getPageSize = function() {
  var xScroll, yScroll;

  if (window.innerHeight && window.scrollMaxY) {  
    xScroll = document.body.scrollWidth;
    yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = document.body.offsetWidth;
    yScroll = document.body.offsetHeight;
  }

  var windowWidth, windowHeight;
  if (self.innerHeight) { // all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  } 

  // for small pages with total height less then height of the viewport
  pageHeight = Math.max(windowHeight, yScroll);

  // for small pages with total width less then width of the viewport
  pageWidth = Math.max(windowWidth, xScroll);

  return { page: { width: pageWidth, height: pageHeight }, window: { width: windowWidth, height: windowHeight } };
}


function NiftyCheck(){
	if(!document.getElementById || !document.createElement)
		return(false);
	var b=navigator.userAgent.toLowerCase();
	if(b.indexOf("msie 5")>0 && b.indexOf("opera")==-1)
		return(false);
	return(true);
}



/* DSJS - ColdFusion Functions for JavaScript
	Methods: 	
		Abs(number)
		ArrayAppend(array, value)
		ArrayLen(array)
		ArraySort(array, sort_type [, sort_order ])
		ArrayToList(array [, delimiter ])
		Ceiling(number)
		Compare(string1, string2)
		CompareNoCase(string1, string2)		
		DateDiff(datepart, date1, date2)
		DecimalFormat(number)
		DollarFormat(number)
		Find(substring, string)
		FindNoCase(substring, string)
		Insert(substring, string, position)
		IsDate(date)
		IsNumeric(string)
		LCase(string)
		Left(string, count)
		Len(sting)
		ListAppend(list, value, [, delimiters])
		ListDeleteAt(list, position [, delimiters ])
		ListFind(list, value [, delimiters ]))
		ListFindNoCase(list, value [, delimiters ]))
		ListGetAt(list, position [, delimiters ]))
		ListLen(list [, delimiters])
		ListSetAt
		ListToArray(list [, delimiters])
		LTrim(string)
		Mid(string, start, count)
		Replace(string, substring1, substring2 [, scope ])
		ReplaceNoCase(string, substring1, substring2 [, scope ])
		Reverse(string)
		Right(string, count)
		Round(number [, number of decimal places])
		RTrim(string)
		Trim(string)
		UCase(string)
		URLDecode(string)
		URLEncodedFormat(string)		
		
	Usage:
		
		DSJS.Len("returns the length of a sting");
		DSJS.ListGetAt('andy,tim,katrin',3);
		
	Code Variable Abbreviations:
		a 		= array
		c 		= count
		d 		= delimiters
		d1,d2 	= date one, date two
		dp 		= date part
		i 		= index
		l 		= list
		n 		= number
		p 		= position
		r 		= return value/string/etc 
		s 		= string
		s1,s2 	= string one, string two
		sb 		= substring
		sb1,sb2	= substring one, substring two
		so 		= sort order
		st 		= sort type
		sc 		= scope
		v 		= value
*/
var DSJS = {
	_CommaForThousands: function(n){
			var r = n.slice(0, n.indexOf('.'));
			for (var i = 0; i < Math.floor((r.length-(1+i))/3); i++){
				r = n.substring(0,n.length-(4*i+3)) + ',' + n.substring(n.length-(4*i+3));
			}
			return r;
	},
	Abs: function(n){
		return Math.abs(n);
	},	
	ArrayAppend: function(a, v){
		a[a.length] = v;
		return a;
	},
	ArraySort: function(a,st,so){
		var _so;
		if (st.toUpperCase() == 'TEXTNOCASE'){ 
			if(!so || so.toUpperCase() != "DESC"){
				_so = function(a, b) {a = a.toUpperCase(); b = b.toUpperCase(); if (a < b){return -1;} else if(a > b){return 1;} else {return 0;}};
			} else {
				_so = function(a, b) {a = a.toUpperCase(); b = b.toUpperCase(); if (a > b){return -1;} else if(a < b){return 1;} else {return 0;}};
			}		
		} else if (st.toUpperCase() == 'TEXT'){ 
			if(!so || so.toUpperCase() != "DESC"){
				_so = function(a, b) {if (a < b){return -1;} else if(a > b){return 1;} else {return 0;}};
			} else {
				_so = function(a, b) {if (a > b){return -1;} else if(a < b){return 1;} else {return 0;}};
			}		
		} else if (st.toUpperCase() == 'NUMERIC'){
			if(!so || so.toUpperCase() != "DESC"){
				_so = function(a,b) {return a - b;};
			} else {
				_so = function(a,b) {return b - a;};
			}			
		}
		return a.sort(_so);
	},
	ArrayToList: function(a,d){
		if(!d){d = ",";}
		var re = /[,]/gi;
		return a.toString().replace(re, d);
	},
	ArrayLen: function(a){		
		return a.length;		
	},	
	Ceiling: function(n){
		return Math.ceil(n);
	},
	Compare: function(s1,s2){
		if (s1 == s2) {return 0;}
		if (s1 > s2) {return 1;}	
		else {return -1;}
	},
	CompareNoCase: function(s1,s2){
		return this.Compare(s1.toUpperCase(),s2.toUpperCase());
	},
	DateDiff: function(dp,d1,d2){
		var dt1 = new Date(d1);
		var dt2 = new Date(d2);
		var iDiffMS = dt2.valueOf() - dt1.valueOf();
		var dtDiff = new Date(iDiffMS);
		var nYears  = dt2.getUTCFullYear() - dt1.getUTCFullYear();
		var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears!==0 ? nYears*12 : 0);
		var nQuarters = nMonths / 3;		
		var nMilliseconds = iDiffMS;
		var nSeconds = iDiffMS / 1000;
		var nMinutes = nSeconds / 60;
		var nHours = nMinutes / 60;
		var nDays  = nHours / 24;
		var nWeeks = nDays / 7;
		var iDiff = 0;		
		switch(dp.toLowerCase()){
			case "yyyy": return nYears;
			case "q": return nQuarters;
			case "m": return nMonths;
			case "y": return nDays;
			case "d": return nDays;
			case "w": return nDays;
			case "ww":return nWeeks;		
			case "h": return nHours;
			case "n": return nMinutes;
			case "s": return nSeconds;
			case "ms":return nMilliseconds;
			default: return "invalid interval: '" + dp + "'";
		}
	},
	DecimalFormat: function(n){ 
		var r = n.toFixed(2);
		var bp = this._CommaForThousands(r.slice(0, r.indexOf('.') + 1));
		var ap = this.Right(r,2);
		r = bp + '.' + ap;
		return r;
	},
	DollarFormat: function(n) {
		var _n = n.toString().replace(/\$|\,/g,'');
		_n = _n.toString().replace('(','-');
		_n = _n.toString().replace(')','');
		if(isNaN(_n)){
			_n = 0;
		}
		var	sign = (_n == (_n = Math.abs(n)));
			_n = Math.floor(_n*100+0.50000000001);
		var	cents = _n%100;
			_n = Math.floor(_n/100).toString();		
		if(cents < 10){
			cents = "0" + cents;
		}
		_n = this._CommaForThousands(_n);
		return (((sign)?'':'(') + '$' + _n + '.' + cents + ((sign)?'':')'));
	},
	Find: function(sb,s){
		 return s.toString().indexOf(sb) + 1;
	},
	FindNoCase: function(sb,s){		
		return this.Find(sb.toUpperCase(),s.toUpperCase());
	},
	Insert: function(sb,s,p){
		return s.slice(0, p) + sb + s.slice(p, s.length);
	},
	IsDate: function(d){
		var datePat 	= /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
		var matchArray 	= d.toString().match(datePat);	
		if (matchArray === null) {
			return false;
		}	
		var month 	= matchArray[1];
		var day 	= matchArray[3];
		var year 	= matchArray[5];	
		if (month < 1 || month > 12) { 
			return false;
		}	
		if (day < 1 || day > 31) {
			return false;
		}	
		if ((month==4 || month==6 || month==9 || month==11) && day==31) {
			return false;
		}	
		if (month == 2) { 
			var isleap = (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0));
				if (day > 29 || (day==29 && !isleap)) {
					return false;
				}
		}
		return true; 
	},
	IsNumeric: function(s){
		if (isNaN(s)){
			return false;
		} else {
			return true;
		}
	},
	LCase: function(s){		
		return s.toLowerCase();			
	},
	Left: function(s,c){
		return s.slice(0, c);
	},	
	Len: function(s){		
		return s.length;
	},
	ListAppend: function(l, v, d){
		if(!d){d = ",";}
		var r = ""; 
		if (this.ListLen(l)){
			r = l + d + v;
		} else {
			r = v;
		}
		return r;
	},
	ListDeleteAt: function(l, p, d){
		if(!d){d = ",";}
		var i,posInList;
		var posInArray = p - 1;
		var thisD 	= "";
		var r = ""; 
		for(i = 0; i < l.split(d).length; i++){
			if (i != posInArray){
				posInList = i + 1;
				if (r.length){
					thisD 	= d;
				}
				r += thisD + this.ListGetAt(l, posInList, d);
			}
		}
		return r;
	},
	ListFind: function (l,v,d){
		if(!d){d = ",";}
		var r = 0;
		var listToArray = l.split(d);
		for (var i=0; i < listToArray.length; i++){		
			if (listToArray[i] == v){
				r = i + 1;
				break;
			}
		}
		return r;
	},
	ListFindNoCase: function(l,v,d){
		if(!d){d = ",";}
		return this.ListFind(l.toUpperCase(), v.toUpperCase(), d);
	},
	ListFirst: function(l,d) {
		if(!d){var d=','}
		_TempListFirstSplitArray = l.split(d)
		return _TempListFirstSplitArray[0]
	},
	ListGetAt: function (l, p, d){
		if(!d){d = ",";}
		return l.split(d)[p - 1];
	},	


	ListLast: function(l,d) {
		if(!d){var d=','}
		_TempListFirstSplitArray = l.split(d)
		return _TempListFirstSplitArray[_TempListFirstSplitArray.length-1]
	},
	ListLen: function(l,d){	
		if(!d){d = ",";}		
		return l.split(d).length;
	},	
	ListSetAt: function(l,p,v,d) {
		if(!d){d = ",";}
		_TempListFirstSplitArray = l.split(d);
		_TempListFirstSplitArray[p-1]=v;
		_TempStringToReturn = _TempListFirstSplitArray.join(d);
		return _TempStringToReturn;
	},
	ListToArray: function(l,d){		
		var r,a,i;			
		if(!d){d = ",";}		
		r = [];

		a = l.split(d);			
		for(i=1; i <= a.length; i++){
			r[i] = a[i - 1];
		}			
		return r;	
	},
	LTrim: function(s){
		return s.toString().replace(/^\s*/, '');
	},	
	Mid: function(s, start, c){
		start -= 1;
		return s.slice(start,start + c);
	},
	Replace: function(s,sb1,sb2,sc){
		if(!sc || sc.toUpperCase() != "ALL"){
			sc = "";
		} else {
			sc ="g";
		} 	
		var re = new RegExp(sb1,sc);
		return s.replace(re,sb2);
	},

	ReplaceNoCase: function(s,sb1,sb2,sc){
		if(!sc || sc.toUpperCase() != "ALL"){
			sc = "i";
		} else {
			sc ="gi";
		} 	
		var re = new RegExp(sb1,sc);
		return s.replace(re,sb2);
	},
	Reverse: function(s){
		var i = s.length;
		var r = "";	
		for (i; 0 <= i; i--){	
			r += s.charAt(i);	
		}	
		return r;
	},
	Right: function(s,c){
		return s.slice(s.length - c, s.length);
	},
	Round: function(n,p) {
		if (!isNaN(n.toFixed(p))){
			return n.toFixed(p);
		} else {
			return n;
		}
	},
	RTrim: function(s){
		return s.toString().replace(/\s*$/, '');
	},
	Trim: function(s){
		return s.replace(/^\s*|\s*$/g,'');
	},
	UCase: function(s){		
		return s.toUpperCase();			
	},
	URLDecode: function(s){
		return unescape(s);
	},	
	URLEncodedFormat: function(s){
		return encodeURI(s);
	},
	Year: function (mydate) {
		_newDate = new Date(mydate)
		return _newDate.getYear();
	},
	// 2008-07-16 [AP] Added LSCurrencyFormat	
	LSCurrencyFormat: function (num) {
		currency=''; // € oder $
		num = num.toString().replace(/\$|\,/g,'');		
		if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10)
		cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'+
		num.substring(num.length-(4*i+3));
		return (((sign)?'':'-') + currency + num + ',' + cents);
	}		
	

};


/* END DSJS - ColdFusion Functions for JavaScript */


function DSIsDefined( variable){
    return (typeof(window[variable]) == "undefined")?  false: true;
}
function isdefined( variable){
    return (typeof(window[variable]) == "undefined")?  false: true;
}



function DSGetVarFromURL(url,variable) {
	variable = variable.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+variable+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec(url);
	if(results==null)
		return "";
	else
		return results[1];
}

// Start
function DSSnippetSelect (e,type,field,optionlist) {
	this.contentdiv='fff';	
	DSOptionList(optionlist);	
	
	top.DSSnippetSelect_type=type;
	top.DSSnippetSelect_field=field;
	DSContextShow(e,contentdiv);
}


function DSSnippetInsert(theSelect) {
	if(theSelect.selectedIndex>=0) {
		theContentObject=theSelect.options[theSelect.selectedIndex].value;
		content=$(theContentObject).innerHTML;
		if($(theSelect.options[theSelect.selectedIndex].value+'_replacelist')) {
			thelist=$(theSelect.options[theSelect.selectedIndex].value+'_replacelist').value;
			for(replacevar=0;replacevar < DSJS.ListLen(thelist,',');replacevar++) {
				Item=DSJS.ListGetAt(thelist,replacevar+1,',');
				if(DSJS.ListLen(Item,':')==2) {
					content=DSJS.ReplaceNoCase(content,DSJS.ListGetAt(Item,1,':'),DSJS.ListGetAt(Item,2,':'));
				}
			}
		}
	}
	if(top.DSSnippetSelect_type=='field')
		$(top.DSSnippetSelect_field).value=$(top.DSSnippetSelect_field).value+content;
	else if(top.DSSnippetSelect_type=='dseditor'){
		tinyMCE.get(top.DSSnippetSelect_field).selection.setContent(content);
		if(top.DSSnippetSelect_field=='messagebody')
			tinyMCE.get(top.DSSnippetSelect_field).dom.setHTML('dssenderemail', $('email_from').options[$('email_from').selectedIndex].value);		
	}
	//tinyMCE.setContent(tinyMCE.getContent(top.DSSnippetSelect_field)+content);

	theSelect.selectedIndex=0;
}

ds_selected_obj_to_insert='';
function ds_selected_obj_insert(tvs,tve){
	if (ds_selected_obj_to_insert=='')
		return;
	ds_selected_obj_to_insert.focus();
	if(typeof document.selection != 'undefined'){
		thisSelection=document.selection.createRange();
		range_text_length = thisSelection.text.length;
		thisSelection.text = tvs+thisSelection.text+tve;
		if (range_text_length==0)
			thisSelection.move('character', -tve.length);
		thisSelection.select();
	}
	else if(typeof ds_selected_obj_to_insert.selectionStart != 'undefined'){
		sec_start = ds_selected_obj_to_insert.selectionStart;
		sec_end = ds_selected_obj_to_insert.selectionEnd;
		sec_insText = ds_selected_obj_to_insert.value.substring(sec_start,sec_end);
		ds_selected_obj_to_insert.value = ds_selected_obj_to_insert.value.substr(0, sec_start) + tvs + sec_insText + tve + ds_selected_obj_to_insert.value.substr(sec_end);
		new_pos=0;
		if (sec_insText.length==0)
			new_pos = sec_start + tvs.length;
		else
			new_pos = sec_start+tvs.length+sec_insText.length+tve.length;
		ds_selected_obj_to_insert.selectionStart=new_pos;
		ds_selected_obj_to_insert.selectionEnd=new_pos;
	}
	else{
		ds_selected_obj_to_insert.value+=tvs + tve;
	}
}
// End


// readAttribute('active'));
// ***************************
// * START DSLoader          *
// ***************************

var dsloaderid=0;
function dsgetloaderid() {
	dsloaderid++;
	if (dsloaderid>5)
		dsloaderid=1;
}

function DSLoader_getWindowObject(theCommand) {
	pos=top.DSFindLoader_Loaded(theCommand);
	if (pos>-1)
		return top.DSLoader_Loaded[pos][0];
	else
		return this.window
} 

xhrcounter=0;

function dsloader(url,target,element,optionlist) {
	//alert('window.name:'+window.name+'url:'+url+' target:'+target);
		
	type='load';
	popupwarning=1;
	postform='';
	theelement=url;
	cancelalert=0;
	xhr=0;
	dspopup1_loader_width=20;
	dspopup2_loader_width=30;
	dspopup3_loader_width=40;	
	dspopup1_width=20;
	dspopup2_width=30;
	dspopup3_width=40;	
	DSOptionList(optionlist);
	if(target==null)
		target='dspopup1';
	url=url+'&dscaller='+window.name+'&dsreceiver='+target;
	if(typeof top.DSLoader_URLAdd != 'undefined' && top.DSLoader_URLAdd!='')
		url=url+top.DSLoader_URLAdd;

	// 2009-02-07 [AP] Multiple Sorting
	// Das Attributre mulitplesorting wird in der DSMultipleSort() Funktion gesetzt
	if ($(element) && $(element).readAttribute('multiplesorting')) {
		url+='&dssorting='+$(element).readAttribute('multiplesorting');	
	}
	if(cancelalert==1)
		url=url+'&cancelalert=1';
	//if (DSCAID==2260) {
	//	alert('url:'+url+'\ndselement:'+DSJS.FindNoCase('&dselement=',url)+'\nelement:'+DSJS.FindNoCase('='+element,url));
	//}
	if (DSJS.FindNoCase('&dselement=',url)==0 && DSJS.FindNoCase('='+element,url)==0 && element)
		url+='&dselement='+element;
	//2008-07-01 [AP]
	//if (DSCAID=2260)
	//	alert('each:'+s+'\nurl:'+url+'\ncommand:'+DSJS.FindNoCase('cmd='+s,url)+'\nCommandbarElement:'+DSJS.FindNoCase('DSCommandBarElement',url))
	if (typeof DSExplorer.GUIPlace.CommandBar=='object' && DSJS.FindNoCase('DSCommandBarElement',url)==0) {
		DSExplorer.GUIPlace.CommandBar.Element.each(function(s) { 
			//if (DSJS.FindNoCase('cmd='+s,url)){
			if (s==element) {	
				url=url+'&dscommandbarelement='+DSExplorer.GUIPlace.CommandBar.Name;
				$break;
			}
		}); 
	}		
	if (element!=null)
		theelement=element;
	//if (DSCAID==2260)
	//	alert(url);
	if(DSLeft(target,7)=='dspopup') {
		if(DSIsBackEnd==1) {
			MAINWIndow='top.MAIN.';
			if(dsviewcheck()=='dsmanager')
				MAINWIndow='top.dsmanager.';
		}
		else
			MAINWIndow='top.';
		
		TargetWindowObject=eval(MAINWIndow+target+'_loader');
		if(type=='load') {
			if(eval(MAINWIndow+'$(\''+target+'\').style.display')=='block' && TargetWindowObject.DSPopUp_RefreshAlert && TargetWindowObject.DSPopUp_RefreshAlert==1) {
				editor_warning=confirm(DSLang('alertdicardpopupcontent'));
				if(editor_warning==false)
					return
			}
			if(xhr==0)
				TargetWindowObject.location.href=url;
			else
				new Ajax.Updater(theelement, url+'&dsxhr=1',{parameters: { text: $(theelement) }}); 
				
		}
		if (dcbe==null)
			DSInit();
		if((parent.document.getElementById(target) || $(target)) && type=='load'){
			if($(target)){
				$(target).style.left = 20+eval(target+'_width') + "px";
				$(target).style.top = DSInt(dcbe.scrollTop+20+eval(target+'_width')) + "px";
			}
			else{
				parent.$(target).style.left = 20+eval(target+'_width') + "px";
				parent.$(target).style.top = DSInt(parent.dcbe.scrollTop+20+eval(target+'_width')) + "px";
			}
		}
	}
	else if(target=='dsmanager') {
		TargetWindowObject=eval(top.dsmanager);
	}
	else if(target=='dssidebar') {
		TargetWindowObject=eval(top.dssidebar);
	}	
	else if(target=='MAIN' || target=='ds' || target=='dsfront') {
		if(DSIsBackEnd==1)
			TargetWindowObject=eval(top.MAIN);
		else
			TargetWindowObject=eval(top);
	}
	else if(target=='dsloader') {
		if($('dsformwaitcode') && url.indexOf('unlock') == -1)
			$('dsformwaitcode').style.display='block';
		dsgetloaderid();
		// 2006-07-27 [AP] Postform
		if(postform!='' && $(postform)) {	
			$(postform).action=url;
			$(postform).target='dsloader'+dsloaderid;		
			$(postform).submit();
		}
		else {			
			if(DSIsBackEnd==1)
				TargetWindowObject=eval('top.dsloader_action.'+target+dsloaderid);
			else
				TargetWindowObject=eval('top.'+target+dsloaderid);
			if(xhr==0){
				TargetWindowObject.location.href=url;
			}
			else{
				/*this.transport=new Ajax.Request(url+'&dsxhr=1', {method:'post',onComplete:function(transport) {
						$(theelement).innerHTML = transport.responseText.stripScripts();
					    setTimeout(function() {transport.responseText.evalScripts()}, 10);
					}
				});*/
				new Ajax.Updater(theelement, url+'&dsxhr=1',{evalScripts:true}); 
			}
		}
	}
	else if(target=='_self')
		self.location.href=url;
	else if(target=='this.window'){
		TargetWindowObject=this.window;
	}
	else {
		// 2007-03-24 [AP]
		if (type!='add')
			dsnav_open_win(url,target);
	}

	// LoaderArray Settings
	if(target=='dsloader')
		thetarget='dsloader'+dsloaderid;
	else
		thetarget=target;
	help_array=[];
	if(type=='load')
		help_array[0]=this.window;
	else if (type=='add') {
		if(DSLeft(target,7)=='dspopup')
			TargetWindowObject=eval(MAINWIndow+target);
		help_array[0]=TargetWindowObject;
	}
	help_array[1]=theelement;
	if(typeof TargetWindowObject!='undefined')
		help_array[2]=TargetWindowObject;
	else
		help_array[2]=this.window;
	help_array[3]=type;
	help_array[4]=url;
	top.DSLoader_Loaded[top.DSLoader_Loaded.length]=help_array;
}

// Clear top.DSLoader_Loaded Commands for this.window
DSLoader_Loaded=new Array();
if(top.DSLoader_Loaded!=null) {
	for(i=0;i<top.DSLoader_Loaded.length;i++)
		if(top.DSLoader_Loaded[i][0]==this.window) {
			top.DSLoader_Loaded[i][0]=-1;
			top.DSLoader_Loaded[i][1]=-1;
			top.DSLoader_Loaded[i][2]=-1;
			top.DSLoader_Loaded[i][3]=-1;
			top.DSLoader_Loaded[i][4]=-1;
			top.DSLoader_Loaded[i]=-1;
		}
}


function DSLoader_ShowLoaded() {
	msg='';
	theloaderaction='';
		for (i=top.DSLoader_Loaded.length-1;i>=0;i--) {
			if(top.DSLoader_Loaded[i][0]!=null) {
				if(top.DSLoader_Loaded[i][3]=='load')
					theloaderaction='<a href="javascript:dynasite();" onclick="window.open(\''+top.DSLoader_Loaded[i][4]+'\',\'dsloadertop\');">'+top.DSLoader_Loaded[i][1]+'</a>';
				else
					theloaderaction=top.DSLoader_Loaded[i][1];
				msg+='<tr style="background-color:#eeeeee"><td>'+i+'</td><td>'+top.DSLoader_Loaded[i][3]+'</td><td>'+theloaderaction+'</td><td>'+top.DSLoader_Loaded[i][0].name+'</td><td>'+top.DSLoader_Loaded[i][2].name+'</td><td nowrap="nowrap">'+top.DSLoader_Loaded[i][4]+'</td></tr>';
			}
		}
		if(msg.length==0)
			msg='<table><tr><td>Nothing loaded</td></tr></table>';
		else
			msg='<table cellspacing="1" style="padding:2px;width:100%"><tr><td class="dshead">ID</td><td class="dshead">Type</td><td class="dshead">Command/Element</td><td class="dshead">Caller</td><td class="dshead">Receiver</td><td class="dshead">URL</td></tr>'+msg+'<tr><td colspan="6">&nbsp;</td></tr></table>';
		if(top.DSManagerLoaded==1) 
			top.dsmanager.$('loaderloadeddiv').innerHTML=msg+'&nbsp;';
		else
			$('loaderloadeddiv').innerHTML=msg+'&nbsp;';
// alert(msg);

}

function DSFindLoader_Loaded(cmd,thewindow){
	//top.DSLoader_Loaded[i][0]=window (frame oder iframe)
	//top.DSLoader_Loaded[i][1]=command
	var i=0;
	var cmdcode='';
	if (top.DSLoader_Loaded.length > 0){
		for (i=top.DSLoader_Loaded.length-1;i>=0;i--){
			if(cmd=='lastcmd' && top.DSLoader_Loaded[i][3]=='load' && DSJS.Find('unlock',top.DSLoader_Loaded[i][1])==0 && DSJS.Find('command_edit',top.DSLoader_Loaded[i][1])==0) {
				return i;
				break;					
			}
			cmdcode=top.DSLoader_Loaded[i][1];
			if(typeof cmdcode != 'undefined') {
				// alert('Index:'+i+'CMDCode:'+cmdcode+' CMD:'+cmd);
				if(thewindow!=null) {
					// if(cmd.indexOf(cmdcode) != -1 &&  top.DSLoader_Loaded[i][0]==thewindow) {
					if(cmd==cmdcode &&  top.DSLoader_Loaded[i][0]==thewindow) {
						return i;
						break;
					}
				}
				else if(cmd==cmdcode) {
					 //alert('i:'+i+' len:'+top.DSLoader_Loaded.length+'code'+cmdcode+'cmd:'+cmd);
					return i;
					break;					
				}
			}
		}
	}
	return -1;
}

function dsdisable(thisvalue,disablevalue,operator,fieldlist,additional) {
	// 2006-10-24 [AP] new option, Operator != 
	var i=0;
	thisdisabled=0;
	additionaldisable='';
	if (additional!=null) {
		additional =additional.split(",");	
		for (i=0; i < additional.length; ++i) {
			//Element[0] = Formfield, Element[1] = Disable Value 
			element=additional[i].split(":");				
			selecttype=$(element[0]).type;							
			if (selecttype=="select-one" && $(element[0]).options[$(element[0]).selectedIndex].value==element[1]) 		
				additionaldisable=1;
			else if (selecttype=='radio' && $(element[0]).checked==true && $(element[0]).value==element[1])
				additionaldisable=1;
			else
				additionaldisable=0;		
		}
		if (thisvalue==disablevalue && additionaldisable==1)
			thisdisabled=1;	
	}
	else {
		if (operator=="!=") {
			if (thisvalue!=disablevalue)
				thisdisabled=1;
		}
		else {
			if (thisvalue==disablevalue || thisvalue=='')
				thisdisabled=1;
		}
	}	
	fieldlist=fieldlist.split(",");	
	for(i=0; i<fieldlist.length; i++){		
		if ($(fieldlist[i])) {
			if ($(fieldlist[i]).type!=undefined)// Ungleich Form-Felder
				$(fieldlist[i]).disabled=thisdisabled;
			else {
				if (thisdisabled==1) {
					$(fieldlist[i]).style.display='none';
					if ($(fieldlist[i]).nodeName=="TD")
						$(fieldlist[i]).setAttribute("style","display:none")
				}
				else {
					$(fieldlist[i]).style.display='block';	
					if ($(fieldlist[i]).nodeName=="TD")
						$(fieldlist[i]).setAttribute("style","display:table-cell !important;display:block")				
				}
			}
		}
	}
	DSPopUpResize();
}

function dsnav_open_win(url, target, scroll){
	if (url.length==0)
		return false;
	Ausdruck=/&target=(\w.+)&.+&/;
	if (Ausdruck.test(url)){
		Ausdruck.exec(url);
		target=RegExp.$1;
		Ausdruck=/&width=(\d.+)&/;
		Ausdruck.exec(url);
		width=RegExp.$1;
		Ausdruck=/&height=(\d.+)/;
		Ausdruck.exec(url);
		height=RegExp.$1;
		Ausdruck=/(\w.+)&target=/;
		Ausdruck.exec(url);
		url=RegExp.$1;

eval(target+"=window.open('"+url+"','"+target+"','width="+width+",height="+height+",left="+Math.ceil(screen.width/2-width/2)+", top="+Math.ceil((screen.height-height)/2)+",screenx=0,scrollbars="+scroll+",screeny=0,dependent=yes,resizable=yes')");
		eval(target+".focus()");
	}
	else
		window.open(url, target);
}

// ***************************
// * END DSLoader            *
// ***************************


function dsnonselect(event,thisElement){
	if(event.altKey){
		thisElement.onselectstart='return false';
		thisElement.unselectable='on';
		thisElement.style.cssText=thisElement.style.cssText+';-moz-user-select:none !important';
	}
	else{
		thisElement.onselectstart='';
		thisElement.unselectable='off';
		thisElement.style.cssText=thisElement.style.cssText.replace(';-moz-user-select:none !important','');
	}
}

function DSFindParnetNodeByName(element,nodename){
	parentnode=element.parentNode;
	returnnode='';
	nodename=nodename.toLowerCase();
	while (returnnode=='') {
		parnetnodename=parentnode.nodeName.toLowerCase();
		if (parnetnodename==nodename || parnetnodename=='html')
			returnnode=parentnode;
		parentnode=parentnode.parentNode;
	}
	return returnnode;
}


// ***************************
// * START Global functions  *
// ***************************

function DSAddBodyOnLoad(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
		window.onload = func;
	else {
		window.onload = function() {
			oldonload();
			isfullfunction=func.search(/\(/gi);0
			if (isfullfunction!=-1)
				eval(func);
			else
				func();
		}
	}
}

function DSBlank(){
	return;
}

function DSSetFocus(element) {
	$(element).activate();
}

function DSArrayFind(array,value) {
	found=false;
	for(afi=0;afi<array.length;afi++) {
		if(array[afi]==value) {
			found=true;
			break
		}
	}
	return found;
}
function DSArrayFindPos(array,value) {
	found=-1;
	for(afi=0;afi<array.length;afi++) {
		if(array[afi]==value) {
			found=afi;
			break
		}
	}
	return found;
}

function DSArrayDeleteElement(this_array,this_pos){
	var help_array=new Array();
	var i=0;
	for(i=0;i<this_array.length;i++){

		if (this_pos!=i){
			help_array[help_array.length]=this_array[i];
		}
	}
	return help_array;
}

function DSArrayToList(array,delimitter){
	var i=0;
	var list='';
	for (i=0;i<array.length;i++){
		if (list=='')
			list+=array[i];
		else
			list+=delimitter+array[i];
	}
	return list;
}

function DSTrim(this_value){
	return this_value.replace(/^\s+/g,'').replace(/\s+$/g,'');
}

function DSLeft(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function DSRight(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function DSInt(to_integer){
	to_integer=parseInt(to_integer);
	if (isNaN(to_integer))
		to_integer=0;
	return to_integer;
}

function DSNumChk(this_number){
	this_number=DSTrim(this_number)
	punkt=this_number.indexOf(".");
	komma=this_number.indexOf(",");
	if (komma > -1){
		if (punkt==-1)
			this_number=this_number.replace(',','.');
		else if(komma<punkt)
			this_number=this_number.replace(',','');
		else if(punkt<komma){
			this_number=this_number.replace('.','');
			this_number=this_number.replace(',','.');
		}
	}
	return this_number;
}

function DSIsNum(this_number){
	this_number=DSNumChk(this_number);
	if (this_number=='' || isNaN(this_number))
		return false;
	else
		return true;
}

function dswinopen(url,width,height,rzb,sb,target){
	eval(target+"=window.open('"+url+"','"+target+"','width="+width+", height="+height+", left="+Math.ceil(screen.width/2-width/2)+", top="+Math.ceil((screen.height-height)/2)+", dependent=1, resizable="+rzb+", scrollbars="+sb+"')");
	eval(target+".focus()");
}

function DSOptionList(OptionList,Delimiter) {
	var i=0;
	if(OptionList!=null) {	
		theDelimiter=':';
		if(Delimiter!=null)
			theDelimiter=Delimiter;
		function_list= OptionList.split(",");
		for (i=0; i<function_list.length; i++) {
			//alert(function_list[i]);
			this_function=function_list[i].split(theDelimiter);
			this[this_function[0]]=this_function[1];
			//eval(this_function[0]+"='"+this_function[1]+"'");
		}
	}
}


var listclass='';
function DSonMouseOverOut(OverOut,thiselement,optionlist) {
	classname='dslist1';
	hoverclass='dslist_hover';
	if (optionlist!=null)
		DSOptionList(optionlist);
	if(OverOut=='over' && thiselement.className!='dslist_selected' && thiselement.className!='trprintno') {
		listclass=thiselement.className;
		thiselement.className=hoverclass;
	}
	if(OverOut=='out' && thiselement.className!='dslist_selected' && thiselement.className!='trprintno') {
		thiselement.className=classname;
	}
}




// ***************************
// * END Global functions    *
// ***************************


// ***************************
// * START Layout - Colors   *
// ***************************
function DSColorSchemeBar(height,type) {
	colorschemebar='<table cellpadding="0" cellspacing="0" width="100%"><tr><td style="height:'+height+'px;width:20%;background:#d70026;"></td><td style="width:20%;background:#3399cc;"></td><td style="width:20%;background:#99cc33;"></td><td style="width:20%;background:#ff6600;"></td><td style="width:20%;background:#FFCC33;"></td></tr></table>'
	if(type=='document.write')
		document.write(colorschemebar);
	else
		return colorschemebar;
}

var colors=new Array('#D70026','#3399CC','#99CC33','#FF6600','#FFCC33');
var trcolors=new Array('#FFFFFF','#f1f5fa');

function DSChildLoop(theElement,theTagName,theAction) {
	var i=0;
	var index=0;
	var theElement = $(theElement);
	for (var i = 0; i < theElement.childNodes.length; ++i) {
		if (theElement.childNodes.item(i).nodeName == theTagName) {
			if(theAction=='dscoloring') {
				theElement.childNodes.item(i).style.color=colors[index];
				index=index+1;
				if(index==colors.length)
					index=0;
			}
			else if(theAction=='trcoloring') {
				theElement.childNodes.item(i).style.backgroundColor=trcolors[index];
				index=index+1;
				if(index==trcolors.length)
					index=0;					
			}
		}
	}
}


function DSSetTRColor (table) { 
    $$('table#'+table+' tbody > tr:nth-child(odd)').each(function(s) {
        s.setStyle('background-color:#ffffff');
    });
    $$('table#'+table+' tbody > tr:nth-child(even)').each(function(s) {
        s.setStyle('background-color:#f1f5fa');
   });
}
function dsulloop(theElement) {
	var index=0; 
	var ul = $(theElement);
	for (var i = 0; i < ul.childNodes.length; ++i) {

		if (ul.childNodes.item(i).nodeName == "LI") {
			ul.childNodes.item(i).style.color=colors[index];
			index=index+1;
			if(index==colors.length)
				index=0;
		}
	}
}

function dswrite_bgcolor(formular,feld) {
	$(feld+'color').style.backgroundColor=$(feld).value;
}

// ***************************
// * END Layout - Colors     *
// ***************************

// Start
function DSPageRowSelect(theElement,theCMD,option) {
	//2008-07-01 [AP] URL.Variable DSPageRowAction hinzugefügt
	var page=theElement.options[theElement.selectedIndex].value;
	postform='';
	element='';
	if(option!=null){
		DSOptionList(option);
	}
	if(postform!='' && $(postform)!=null)
		dsloader(dsxpath+'dynasite.cfm?'+theCMD+'&dspagerows='+page+'&dspagerowsaction='+page,'dsloader',element,'postform:'+postform);
	else
		dsloader(dsxpath+'dynasite.cfm?'+theCMD+'&dspagerows='+page+'&dspagerowsaction='+page,'dsloader',element);
}
// End

//Start
function dscheckticketmessage(dsctid){
	checkmessageconfirm=true;
	if($('messagebody_'+dsctid) && $('messagebody_'+dsctid).value.length>0 && $('messagebody_'+dsctid).value.length<20){
		checkmessageconfirm=false;
		alert('Es wird keine Email verschickt weil die Nachricht zu kurz ist!\nSie benötigt mindestens 20 Zeichen.');
	}
	else if($('messagebody_'+dsctid) && $('messagebody_'+dsctid).value.length>20)
		checkmessageconfirm=confirm('Achtung es wird eine eMail an den Kunden verschickt!');
	if(checkmessageconfirm==true)
		dsform_submit('form:form_'+dsctid)
	else
		$('dsbutton_submit').disabled=false;
}

//End

//Start
function dsWidgetSetAction(action,widgetset,defaultset,dselement){
	if(action=='new' || action=='edit')
		$(dselement+'_widgetsetform').setStyle({display:'block'});
	else
		$(dselement+'_widgetsetform').setStyle({display:'none'});
		
	if(action=='new'){
		dswsid=0;		
		dsaction='insert';
		$(dselement+'_widgetsetname').value='';
		$(dselement+'_widgetsetdefault').checked=false;
	}
	else if(action=='edit'){
		dswsid=widgetset;
		dsaction='update';
		$(dselement+'_widgetsetname').value=$('widgset_'+widgetset).innerHTML;
		if(defaultset){
			$(dselement+'_widgetsetdefault').disabled=true;			
			$(dselement+'_widgetsetdefault').checked=true;
		}
		else
			$(dselement+'_widgetsetdefault').checked=false;
	}
	else if(action=='delete'){
		widgetdelete=confirm('Sind Sie sich sicher?');
		if(widgetdelete==false)
			return;
		dswsid=widgetset;
		action='submit';
		dsaction='delete';
	}
	else if(action=='cancel'){
		dswsid=0;
		$(dselement+'_widgetsetname').value='';
		$(dselement+'_widgetsetdefault').disabled=false;
		$(dselement+'_widgetsetdefault').checked=false;
	}
	else if(action=='set'){
		dswsid=widgetset;		
		action='submit';
		dsaction='set';
	}
	else if(action=='reset'){
		dswsid=0;		
		action='submit';
		dsaction='reset';
	}
	if(action=='submit'){
		var postbodycontent='';
		var sortables = $(dselement).select('.dswidget_column');
		var counter=1;
		var isdef=$(dselement+'_widgetsetdefault').checked ? 1: 0;		
		sortables.each(function (sortable) {
			if(counter==1)		
				postbodycontent+='columnvalue='+sortable.id+'='+$(sortable.id).select('.dswidget').pluck('id').join(',');
			else
				postbodycontent+='|'+sortable.id+'='+$(sortable.id).select('.dswidget').pluck('id').join(',');
			counter+=1;
		});
		
		postbodycontent+='&name='+encodeURIComponent($(dselement+'_widgetsetname').value)+'&isDefault='+isdef;
		
		new Ajax.Updater(dselement+'_widgetsets',dsxpath+'dynasite.cfm?dscmd=widget_widget_sort_'+dsaction+'&dselement='+dselement+'&dswsid='+dswsid+'&dsxhr=1',{
			method: 'post', 
			postBody: postbodycontent,
			onSuccess:function(request){
				request.responseText.evalScripts();
			}
		});
		
		$(dselement+'_widgetsetname').value='';
		$(dselement+'_widgetsetdefault').disabled=false;
		$(dselement+'_widgetsetdefault').checked=false;
	}
}
function BuildCommandSelect(thiselement,thisid) {
	$(thisid).disabled=true;
	if ($(thiselement).readAttribute('element')=='dscid' && $(thisid+'_application'))
		$(thisid+'_application').disabled=true;
			
	var url=dsxpath+'dynasite.cfm?dsmid='+DSMID+'&dscmd=command_command_command_select';
	var dscid=DSCID;
	var multiple=0;
	var name=$(thisid).name;
	var firstoption=$(thisid).readAttribute('firstoption');
	var type=$(thisid).readAttribute('type');
	var preselect=$(thisid).readAttribute('preselect');
	var application=$(thisid).readAttribute('application');
	var global=$(thisid).readAttribute('global');
	
	if ($(thisid+'_dscid'))
		dscid=$(thisid+'_dscid').value;
	if ($(thisid+'_application'))
		application=$(thisid+'_application').value;
	
	//alert(application+' dscid:'+dscid)
	if ($(thisid).multiple==true)
		multiple=1;
	new Ajax.Updater(thisid+'_container', url+'&dsxhr=1',{
		postBody:'command_dscid='+dscid+'&command_multiple='+multiple+'&command_name='+name+'&command_id='+thisid+'&command_firstoption='+firstoption+'&command_type='+type+'&command_preselect='+preselect+'&command_application='+application+'&command_global='+global,
		evalScripts:true
	}); 

}
//2009-01-15 [AP] Die Funktion wird im DS Framework app/_layout.cfm verwendet 
function DSLoadContextMenu() {
	new Proto.Menu({selector: '#DSTree_dsmenutree_'+DSSID+' a',className: 'menu desktop',menuItems: 'treeMenuItems'})
}
var treeMenuItems = [
	{check:'menu==1',name: DSLang('Edit'),className: 'edit',callback: function(e,element) {tempdsmid=element.id.split('_');dsloader(dsxpath+'dynasite.cfm?dscmd=content_menu_menu_edit&dsmid='+tempdsmid[4]+'&dssid='+tempdsmid[2],'dspopup1','content_menu_menu_edit');}},
	{check:'menu==1',name: DSLang('Delete'),className: 'delete',callback: function(e,element) {tempdsmid=element.id.split('_');dsloader(dsxpath+'dynasite.cfm?dscmd=content_delete_menu_delconf&dsmid='+tempdsmid[4]+'&dssid='+tempdsmid[2],'dspopup1','content_delete_menu_delconf');}},
	{check:'menu==1',separator: true},	
	{check:'menu==1',name: DSLang('New'),className: 'new',callback: function(e,element) {tempdsmid=element.id.split('_');dsloader(dsxpath+'dynasite.cfm?dscmd=content_menu_menu_new&dsmid=0&dssid='+tempdsmid[2],'dspopup1','content_menu_menu_new');}},	
	{check:'menu==1',name: 'Menu []',disabled:'1'},
	{check:'menu==0',className: 'delete',name: 'System Menu',disabled:'1'}	
];

//End
if(window.name=='MAIN')
	var slide=0;

function DSDistributor (OptionList) {	
	this.element=DSCommand;
	this.commandbarelement='none';
	this.pagingelement=DSCommand;	
	this.classelement=DSCommand;
	this.guielement='';
	this.page=0;
	this.lastpage=1;
	this.pagerows=25;
	this.isoutput=DSIsOutput;
	this.startend=0;
	this.distribute=0;
	this.scrollto='0';
	this.resetresult=0;
	this.xhr=0;
	this.evalScript=0;
	this.innerdistribution=0;
	this.commandbardistributioncode='';
	this.type='distribute';
	this.display=0;
	this.assignedcommandbar='';
	if (DSIsDefined('this_window')==false){
		this_window=self;
	}
		
	DSOptionList(OptionList);
	
	if (this.type=='distribute') {	
		if (this_window.$(this.classelement) && this_window.$(this.classelement).readAttribute('guielement')!=null)
			this.guielement=this_window.$(this.classelement).readAttribute('guielement');
		
		// Wenn ein Command im POPUP mit DSDistributor geladen und angezeigt wird
		//if (DSCaller=='dynasite' && DSReceiver!='dsloader' && DSReceiver!='' && DSJS.ListFindNoCase('dspopup1_loader,dspopup2_loader,dspopup3_loader',this_window.name))
		if (window.name==this_window.name)
			this.isoutput=1;

		// isOutput ist immer 0, wenn es im DSLoader IFRAME geladen wird, damit es zum Ziel zurückgeschrieben wird
		if (DSReceiver=='dsloader')
			this.isoutput=0;			
		
		if (this.xhr==0)
			DSContext();			
		DSPageRows();

		if (this.page!=0) {
			DSSetPage();
			DSDisplayNavigator();
			DSClearPagingElements();
		}		
		
		DSGuiPlace();
		
		DSContent();		
		DSPaging();
	}
	else if (this.type=='DisplayPage') {
		DSSetPage();
		DSDisplayNavigator();	
	}
	else if (this.type=='ClearPage') {
		DSClearPagingElements();
	}
	else if (this.type=='DisplayGuiPlace') {
		DSGuiPlace();
	}		
		
	DSOnEnd();
	/************************
	// Functions	
	************************/
	function DSOptionList(OptionList) {
		var i=0;
		var function_list='';
		var this_function='';
		
		if(OptionList!=null) {	
			theDelimiter=':';
			function_list= OptionList.split(",");
			for (i=0; i<function_list.length; i++) {
				this_function=function_list[i].split(theDelimiter);
				this[this_function[0]]=this_function[1];
			}
				
		}
		this.classelement=this.element;	
		if (DSJS.FindNoCase('pagingelement:',OptionList)==0)		
			this.pagingelement=this.element;
		if (this_window.$(this.classelement) && this_window.$(this.classelement).readAttribute('commandbar')!=null)
			this.commandbar=this_window.$(this.classelement).readAttribute('commandbar');
		
		if (this_window.$(this.element) && this_window.$(this.element).readAttribute('classelement')!=null)
			this.classelement=this_window.$(this.element).readAttribute('classelement');		
			
		if (DSJS.ListFindNoCase(OptionList,'commandbarelement')==false && $(this.element+'_dscommandbarcontent') && $(this.element+'_dscommandbarcontent').readAttribute('commandbarelement')!=null)
			this.commandbarelement=$(this.element+'_dscommandbarcontent').readAttribute('commandbarelement');	
	}	
	
	function DSContext(){
		if (this_window.$(this.element+'_context') && $(this.element+'_context')){
			//this_window.$(this.element+'_context').innerHTML=$(this.element+'_context').innerHTML;			
			this_window.$(this.element+'_context').innerHTML='';			
			this_window.$(this.element+'_context').insert({bottom:$(this.element+'_context').innerHTML});
		}
	}
	
	function DSPageRows() {
		if (DSIsDefined('runPageRowsDistributor')==false) {			
			if ($('dscommandbar_pagerows') && $(this.commandbarelement+'_dscommandbar_pagerows')) {
				$(this.commandbarelement+'_dscommandbar_pagerows').innerHTML=$('dscommandbar_pagerows').innerHTML;	
				$('dscommandbar_pagerows').innerHTML='';
				runPageRowsDistributor=1;
			}
			// 2008-01-14 [AP] Wenn ein Command im Artikel (Explorer) aufgerufen wird und das dscommandbar_pagerow element im content steht
			else if ($('dscommandbar_pagerows') && this_window.$(this.commandbarelement+'_dscommandbar_pagerows')) {
				this_window.$(this.commandbarelement+'_dscommandbar_pagerows').innerHTML=$('dscommandbar_pagerows').innerHTML;	
				$('dscommandbar_pagerows').innerHTML='';
				runPageRowsDistributor=1;
			}
		}		
	}
	
	function DSContent () {
		// Commandbar 

		if (this.commandbar==1 && $(this.element+'_dscommandbarcontent') && (this.page==0 || this.page==1 || this.resetresult==1 || this_window.$(this.commandbarelement+'_commandbar')==null)){
			this.commandbardistributioncode=$(this.element+'_dscommandbarcontent').innerHTML;
			$(this.element+'_dscommandbarcontent').remove();
			this_window.$(this.classelement).setAttribute('commandbar',1);				
		}		

		//if (DSCAID==2260)
		//	alert('window.name:'+window.name+'\nthis.window:'+this_window.name+'\nelement:'+this.element+'\npage:'+this.page+'\nlastpage:'+this.lastpage+'\noutput:'+this.isoutput+'\nresetresult:'+this.resetresult);

		if (this_window.$(this.element) && $(this.element) && this.isoutput==0) {
			if (this.page==0) {					
				// this_window.$(this.element).innerHTML=this.commandbardistributioncode+'<div id="'+this.element+'_outer" style="display:none">'+$(this.element).innerHTML+'</div>';
				// this_window.$(this.element+'_outer').setStyle({display:'block'}); 
				AddHTML=this.commandbardistributioncode+'<div id="'+this.element+'_outer" style="display:none">'+$(this.element).innerHTML+'</div>';
				if (this.evalScript==0)
					AddHTML=AddHTML.stripScripts();
				this_window.$(this.element).innerHTML='';
				this_window.$(this.element).insert({bottom:AddHTML});
				
				this_window.$(this.element+'_outer').setStyle({display:'block'});
			}
			// Content Distribution with Paging
			else {				
				// Clear Receiver-Element
				if ((this.resetresult==1 || this.page==1) && this_window.$(this.element)) 		
					this_window.$(this.element).innerHTML='';					
				
				// Set lastpage to display="none"
				if (this_window.$(this.element+'_'+this.lastpage))
					this_window.$(this.element+'_'+this.lastpage).style.display='none';					
				
				// Remove _header Element
				if ($(this.element+'_header') && this_window.$(this.element+'_header')) 
					$(this.element+'_header').remove();	
					
				AddHTML=this.commandbardistributioncode+'<div id="'+this.element+'_outer_'+this.page+'" style="display:none">'+$(this.element).innerHTML+'</div>';				
				if (this.evalScript==0)
					AddHTML=AddHTML.stripScripts();
			
				// Insert Paging Content
				//new this_window.Insertion.Bottom(this.element, AddHTML);
				this_window.$(this.element).insert({bottom:AddHTML});
				
				//this_window.Effect.Appear(element+'_outer_'+page,{afterUpdate:this_window.DSPopupHelper,afterFinish:this_window.DSPopupHelper});
				this_window.$(this.element+'_outer_'+this.page).setStyle({display:'block'}); 							
			}
			
		}
		else if (this.commandbardistributioncode!='') {
			// Setzt nur die CommandBar über den Content. Z.B. wenn der Command im Artikel geladen wird (erster Aufruf)
			this_window.$(this.element).innerHTML=this.commandbardistributioncode+$(this.element).innerHTML;
		}
		if (this_window.$(this.classelement))
			this_window.$(this.classelement).setAttribute('pagerows',this.pagerows);	
	}
	
	function DSGuiPlace () {				
		
		if (this.guielement=='' || (this.page>1 && this.resetresult==0))
			return false;

		if (this.display==1) {
			if (this.assignedcommandbar!='')
				this.commandbarelement=this.assignedcommandbar;
			else {
				if ($(this.classelement).readAttribute('commandbarelement'))					
					this.commandbarelement=DSJS.ReplaceNoCase($(this.classelement).readAttribute('commandbarelement'),'_commandbar','','All');
				else
					this.commandbarelement='none';
			}			
		}
		//if (DSCAID==2260)
		//	alert('commandbar:'+this.commandbarelement+'\nguielement:'+this.guielement+'\nactive:'+this_window.$(this.guielement).readAttribute('active'));
		// active:'+this_window.$(this.guielement).readAttribute('active')+'
		
		if (this_window.$(this.guielement) && this_window.$(this.guielement).readAttribute('active') && this_window.$(this_window.$(this.guielement).readAttribute('active')))			
			this_window.$(this_window.$(this.guielement).readAttribute('active')).style.display='none';
		
		this_window.$(this.guielement).setAttribute('active',this.commandbarelement+'_commandbar');
		
		//if (DSCAID==2260)
		//	alert(' window:'+this_window.name+'\n active:'+this.guielement+'\nclasselement:'+this.classelement+'\nelement:'+this.element+'\n commandbarelement:'+this.commandbarelement+'\n display:'+display);
			
		if (this.display==0 && $(this.element+'_dscommandbarcontent')) {			
			// Remove commandbar element falls schon vorhanden
			if (this.xhr==0 && this_window.$(this.commandbarelement+'_commandbar'))
				this_window.$(this.commandbarelement+'_commandbar').remove();
			
			//if ($(this.commandbarelement+'_commandbar'))
			//	alert($(this.commandbarelement+'_commandbar').innerHTML);
			
			AddHTML=$(this.element+'_dscommandbarcontent').innerHTML;		
			
			//if (this.xhr==1 && $(this.guielement).select('[id="'+this.commandbarelement+'_commandbar"]')!='')
			//	$(this.commandbarelement+'_commandbar').remove();
			
			if (this.evalScript==0)
				AddHTML=AddHTML.stripScripts();
			//new this_window.Insertion.Bottom(this.guielement, AddHTML);				
			this_window.$(this.guielement).insert({bottom:AddHTML});
			
			$(this.element+'_dscommandbarcontent').remove();		
		
			if (this_window.$(this.classelement)) {
				this_window.$(this.classelement).setAttribute('commandbar',1);
				this_window.$(this.classelement).setAttribute('commandbarelement',this.commandbarelement+'_commandbar');
				this_window.$(this.classelement).setAttribute('guielement',this.guielement);
			}			
			
			if (this_window.$(this.commandbarelement+'_commandbar'))
				this_window.$(this.commandbarelement+'_commandbar').setAttribute('classelement',this.classelement);			
		}			
		
		if (this_window.$(this_window.$(this.guielement).readAttribute('active'))!=null)
			this_window.$(this_window.$(this.guielement).readAttribute('active')).style.display='block';
		
	}
	// Set Last and current Page Number
	function DSSetPage () {	
		if (this_window.$(this.classelement)) {		
			if (this_window.$(this.classelement).readAttribute('page')!=null)
				this.lastpage=this_window.$(this.classelement).readAttribute('page');				
			this_window.$(this.classelement).setAttribute('page',this.page);			
			
			if ($(this.commandbarelement))
				$(this.commandbarelement).setAttribute('classelement',this.classelement);				
		}
		else {
			// Wenn alle Paging-Element im Dokument stehen und nur ein- und ausgeblendet werden (z.B. Manager-Übersicht)
			if (this.lastpage!=this.page)
				this.lastpage=this.page;
			top.DSGUIObject_Active["DSPaging_"+element]=this.page;
			//this.page=page;
		}
	}
	// Display Paging Navigator
	function DSDisplayNavigator () {
		var pagingcounter=2;		
		//if (DSCAID==2260)
		//	alert('element:'+this.element+' - Page:'+this.page+' - LastPage:'+this.lastpage+' - Counter:'+pagingcounter+' window name:'+this_window.name);
		if (this.page!=this.lastpage) {
			for (i=1;i<pagingcounter+1;i++) {
				if (this_window.$(this.element+'_dspage_void_'+i+'_'+this.lastpage)) {				
					this_window.$(this.element+'_dspage_void_'+i+'_'+this.lastpage).hide();
					this_window.$(this.element+'_dspage_'+i+'_'+this.lastpage).hide();
					
					if (this_window.$(this.element+'_dspage_void_'+i+'_'+this.page))
						this_window.$(this.element+'_dspage_void_'+i+'_'+this.page).hide();	

					if (this_window.$(this.element+'_dspage_'+i+'_'+this.page)){		
						this_window.$(this.element+'_dspage_'+i+'_'+this.page).show();	
					}
				}
			}	
		}
	}
	
	function DSClearPagingElements () {
		if(this.resetresult==1 || this.page==1) {
			if (this_window.$(this.commandbarelement+'_dscommandbar_paging')){				
				this_window.$(this.commandbarelement+'_dscommandbar_paging').innerHTML='';	
			}
			if (this_window.$(this.pagingelement+'_element_paging')) {
				this_window.$(this.pagingelement+'_element_paging').innerHTML='';	
				if ($(this.element+'_dsnavigatorbox_1_'+this.page)) {
					$(this.element+'_dsnavigatorbox_1_'+this.page).style.display='none';				
				}				
			}		
			if (this.removeelement!='' && this_window.$(this.removeelement)) {					
				this_window.$(this.removeelement).remove();
			}
		}
	}
	
	
	function DSPaging() {
		this_paging_window=this_window;
			
		if (this_paging_window.$(this.pagingelement+'_element_paging') || $(this.pagingelement+'_element_paging')) {
			if (this.innerdistribution==1)
				this_paging_window=self;		
			this_class='element_paging';
			dsnavigator_element=this.element;
			receiving_element=this.pagingelement+'_element_paging';
			//if (DSCAID==2260)
			//	alert('element:'+receiving_element+'\nwindow:'+this_paging_window.name);
		}
		//else if ((DSJS.ListFindNoCase('dsmanager,dspopup3_loader,dspopup1_loader',this_window.name) || DSCommandBar==1 || this_window.DSCommandBar==1) && (this.commandbardistributioncode!='' || (this_window.$(this.commandbarelement+'_dscommandbar_paging')!=null) && $(this.commandbarelement+'_dsnavigatorbox_1_'+this.page)!=null)) {
		else if (this_window.$(this.classelement) && this_window.$(this.classelement).readAttribute('commandbar')==1){
			this_class='dscommandbar_paging';
			dsnavigator_element=this.commandbarelement;
			receiving_element=this.commandbarelement+'_dscommandbar_paging';
			this.pagingelement=this.commandbarelement;			
		}
		else 			
			return false;
		
		if (this.xhr==1 && this_paging_window.$(receiving_element))
			this_paging_window.$(receiving_element).innerHTML='';
		
		//if (DSCAID==2260)
		//	alert('this_class:'+this_class+'\nreceiving_element:'+receiving_element+'\ndsnavigator_element:'+dsnavigator_element+'\nwindow:'+this_paging_window.name)
				
		if ($(dsnavigator_element+'_dsnavigatorbox_1_'+this.page) && this_paging_window.$(receiving_element)) {
			AddHTML=$(dsnavigator_element+'_dsnavigatorbox_1_'+this.page).innerHTML;
			
			if (this.evalScript==0)
				AddHTML=AddHTML.stripScripts();			
			this_paging_window.$(receiving_element).insert({top:AddHTML});
		
			//AddHTML=this_paging_window.$(receiving_element).innerHTML;
			//AddHTML=DSJS.Replace(AddHTML,"<","<span><</span>","All");
			//AddHTML+='<br /><br />';
			//top.MAIN.$('testing').innerHTML=AddHTML;
		}			
		
		if (this_paging_window.$(dsnavigator_element+'_dsnavigatorbox_1_'+this.page)) {
			//this_paging_window.$(dsnavigator_element+'_dsnavigatorbox_1_'+this.page).innerHTML='';			
			this_paging_window.$(dsnavigator_element+'_dsnavigatorbox_1_'+this.page).remove();			
			// Die Outer-Box muss auf display:none gesetzt werden, da ansonsten ein Abstand zwischen Content und DSCommandbar steht
			//this_paging_window.$(dsnavigator_element+'_dsnavigatorbox_1_'+this.page).style.display='none';
			this_paging_window.$(dsnavigator_element+'_dspage_1_'+this.page).className=this_class;
			this_paging_window.$(dsnavigator_element+'_dspage_void_1_'+this.page).className=this_class;
		}
	}
	
	function DSOnEnd() {
		if(this_window.$('dsformwaitcode'))
			this_window.$('dsformwaitcode').style.display='none';
			
		//if(this_window.name!='MAIN')
		this_window.DSPopUpResize();	
	
		if (this.scrollto!=0)
			this_window.scrollTo(0,0);
	}
};

//		if (DSCAID==2260)
//			alert('element:'+this.element+' page:'+this.page+' lastpage:'+this.lastpage+' window:'+this_window.name);

function dspaging(element,querystring,option) {
	page=1;
	lastpage=1;
	startend=0;
	scrollto='0';
	loadtype='dsloader';
	postform='';
	resetresult=0;
	pagingcounter=2;
	display='';
	// Option Loop
	DSOptionList(option);	
	
	this_window=DSLoader_getWindowObject(element);
	
	var ClassElement=element;
	if ($(element) && $(element).readAttribute('classelement')!=null) 
		ClassElement=$(element).readAttribute('classelement');
	
	if(startend==0 && resetresult==1) {
		$(ClassElement).setAttribute('page','');		
		DSDistributor('element:'+element+',page:'+page+',lastpage:'+lastpage+',resetresult:1,type:ClearPage');
	}		
		
	// Set LastPage
	if (this_window.$(ClassElement))
		lastpage=this_window.$(ClassElement).readAttribute('page');		
	else
		lastpage=top.DSGUIObject_Active["DSPaging_"+element];
	

	// Load new page if not exist in document
	if ($(element+'_'+page)==null || resetresult==1) {		
		if(lastpage!=''){				
			for (i=1;i<pagingcounter+1;i++) {	
				if($(element+'_dspage_void_'+i+'_'+lastpage)!=null) {						
					$(element+'_dspage_void_'+i+'_'+lastpage).style.display='block';
					$(element+'_dspage_'+i+'_'+lastpage).style.display='none';						
				}
			}
			if ($('dsformwaitcode')!=null) 
				$('dsformwaitcode').style.display='block';					
		}		
		if (top.DSLoader_URLAdd!=null && DSJS.ListFirst(top.DSLoader_URLAdd,"=")=='dssorting')
			top.DSLoader_URLAdd='';
		if ($(ClassElement) && $(ClassElement).readAttribute('pagerows')){
			if (DSJS.FindNoCase('dspagerows',querystring)==0)
				querystring+='&dspagerows='+$(ClassElement).readAttribute('pagerows');
			querystring+='&DSPageRowsAction='+$(ClassElement).readAttribute('pagerows');
		}
		if(postform!='' && $(postform)!=null)
			dsloader(querystring+'&dspage='+page+'&dsslide='+slide,'dsloader',element,'postform:'+postform);			
		else if(loadtype=='dsloader')
			dsloader(querystring+'&dspage='+page+'&dsslide='+slide,'dsloader',element);
		else if (loadtype=='selflocation')					
			self.location.href=querystring+'&dspage='+page;			
	}
	// Display next/prev. page
	else {			
		// Current Page Block - Old Page None
		$(element+'_'+lastpage).hide();
		$(element+'_'+page).show();
		// wenn alle Paging-Elemente im Dokument stehen und NICHT über den dsloader geladen werden
		if ($(element+'_dsnavigatorbox_1_'+page) && $(element+'_dsnavigatorbox_1_'+page).style.display=='none' && display!='' ) {
			$(element+'_dsnavigatorbox_1_'+page).show();
			$(element+'_dsnavigatorbox_1_'+lastpage).hide();
		}
		// Page Container	
		DSDistributor('element:'+element+',page:'+page+',lastpage:'+lastpage+',scrollto:'+scrollto+',type:DisplayPage');
	}	
}

function dstinymcecustomfilebrowser(element_id, url, type, win) {
	parent.TinyMCEInstance='tinymce';
	parent.TinyMCEWindow=win;			
	parent.dsfield=element_id;
	if(type=='image' || type=='flash')
		dslgs_open('f1',element_id,'asset_asset_asset_view');
	else if(type=='file')
		dslgs_open('f1',element_id,'site_site_site_view');
	else
		dslgs_open('f1',element_id,'site_site_site_view');				
}
function dstinymcstogglehtmlmode(action,textarea,height,font) {
	fieldtemp='';
	fonttemp='';
	if(font!=null){
		font=font.split('|')
		for(i=0;i<font.length;i++){
			if(font[i]=='size')
				fonttemp+='fontsizeselect,';
			if(font[i]=='family')
				fonttemp+='fontselect,';
		}
	}
	if(textarea=='ssubject')
		fieldtemp='fieldtype_title';
	else if (textarea=='teaser')
		fieldtemp='fieldtype_teaser';	
	else if (textarea=='shortbody')
		fieldtemp='fieldtype_body';	
	if(tinyMCE!=null)
		tinyMCE.execCommand('mceRemoveControl',false,textarea);
	if(action=='simple') {
		if($(fieldtemp)!='' && $(fieldtemp)!=null){
			if($('editor_warning_'+textarea).value==0 && $(fieldtemp).value!='editor'){				
				editor_warning=DSLang('alertswitcheditormodus');							
				if(editor_warning==false)
					return
				else{
					$('editor_warning_'+textarea).value=1;
					$(fieldtemp).value='editor';
				}
			}
		}
		if(fonttemp!=''){
			tempbutton1='"paste,pastetext,pasteword,separator,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,separator,outdent,indent,separator,undo,redo,separator,link,unlink,anchor,image"';
			tempbutton2='"'+fonttemp+'separator,bold,italic,underline,strikethrough,forecolor,backcolor"';
		}
		else{
			tempbutton1='"paste,pastetext,pasteword,separator,bold,italic,underline,strikethrough,forecolor,backcolor,separator,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,separator,outdent,indent,separator,undo,redo,separator,link,unlink,anchor,image"';
			tempbutton2='""';
		}		
		tinyMCE.init({
			mode : "exact",
			theme : "advanced",
			skin : "o2k7",
		    elements  : "+textarea+",
			plugins : "safari,table,media,searchreplace,contextmenu,inlinepopups,paste",
			theme_advanced_disable:"",
			theme_advanced_buttons1:eval(tempbutton1),
			theme_advanced_buttons2:eval(tempbutton2),
			theme_advanced_buttons3 : "",
			theme_advanced_statusbar_location : "none",

			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_link_targets : eval('"'+DSLang('mainwindow')+'=main;Reload=_top"'),
			extended_valid_elements : "+textarea[accesskey|class|cols|dir<ltr?rtl|disabled<disabled|id|lang|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onselect|readonly<readonly|rows|style|tabindex|title],input[accept|accesskey|align<bottom?left?middle?right?top|alt|checked<checked|class|dir<ltr?rtl|disabled<disabled|id|ismap<ismap|lang|maxlength|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onselect|readonly<readonly|size|src|style|tabindex|title|type<button?checkbox?file?hidden?image?password?radio?reset?submit?text|usemap|value],+iframe[align<bottom?left?middle?right?top|class|frameborder|height|id|longdesc|marginheight|marginwidth|name|scrolling<auto?no?yes|src|style|title|width],+fieldset[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+form[accept|accept-charset|action|class|dir<ltr?rtl|enctype|id|lang|method<get?post|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onreset|onsubmit|style|title|target],+noscript[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+object[align<bottom?left?middle?right?top|archive|border|class|classid|codebase|codetype|data|declare|dir<ltr?rtl|height|hspace|id|lang|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|standby|style|tabindex|title|type|usemap|vspace|width],+optgroup[class|dir<ltr?rtl|disabled<disabled|id|label|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+option[class|dir<ltr?rtl|disabled<disabled|id|label|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|selected<selected|style|title|value],+script[charset|defer|language|src|type],+select[class|dir<ltr?rtl|disabled<disabled|id|lang|multiple<multiple|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|size|style|tabindex|title],param[id|name|type|value|valuetype<DATA?OBJECT?REF],+label[accesskey|class|dir<ltr?rtl|for|id|lang|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],link[charset|class|dir<ltr?rtl|href|hreflang|id|lang|media|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|rel|rev|style|title|target|type],+legend[align<bottom?left?right?top|accesskey|class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+map[class|dir<ltr?rtl|id|lang|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+area[accesskey|alt|class|coords|dir<ltr?rtl|href|id|lang|nohref<nohref|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|shape<circle?default?poly?rect|style|tabindex|title|target],+a[accesskey|charset|class|coords|dir<ltr?rtl|href|hreflang|id|lang|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|rel|rev|shape<circle?default?poly?rect|style|tabindex|title|target|type],+dd[class|id|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex],+dl[class|id|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex],+dt[class|id|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex]",
			table_styles : "DSTable_Table=dstable_table",
			table_cell_styles : "DSTable_Cell=dstable_cell",
			table_row_styles : "DSTable_Row=dstable_row",			
			document_base_url:eval('"'+DSFrontURL+'/"'),				
			language: eval('"'+dslang+'"'),
			docs_language:eval('"'+dslang+'"'),
			debug: false,
			width:"100%",
			height:eval('"'+height+'"'),
			force_hex_style_colors : true,
			force_br_newlines : DSEditorForceBR,
			force_p_newlines : DSEditorForceP,
			forced_root_block : false,
			inline_styles : false,
			relative_urls: true,
			convert_urls : false,
			apply_source_formatting: true,
			button_tile_map: true,
			convert_fonts_to_spans : false,
			cleanup : true,
			verify_html:true,
			remove_linebreaks : false,
//			cleanup_callback : "mceTagWrap",
			entity_encoding:eval('"'+entity_encoding+'"'),
			paste_use_dialog : false,
			file_browser_callback : "dstinymcecustomfilebrowser",
			init_instance_callback: "dsEditorCustomInitInstance",
			paste_postprocess : function(pl, o) {
				if(o.wordContent==true && DSEditorForceBR==true){
					var test = o.node.innerHTML;
					test = test.replace(/<p>/g,'');
					test = test.replace(/<\/p>/g,'</br>');					
					test = test.replace(/\&nbsp\;/g, ' ');
					test = test.replace(/\s{2,}/g, ' ');				
					o.node.innerHTML=test;
				}
			}
		});
		tinyMCE.execCommand('mceAddControl',false,textarea);
		if($('dirshow_'+textarea)!=null)
			$('dirshow_'+textarea).style.display='none';
		$('editorname_'+textarea).innerHTML='['+DSLang('contenteditor')+']';		
	}
	else if(action=='advanced') {
		if($(fieldtemp)!='' && $(fieldtemp)!=null){
			if($('editor_warning_'+textarea).value==0 && $(fieldtemp).value!='editor'){				
				editor_warning=confirm(DSLang('alertswitchtoeditor'));
				if(editor_warning==false)
					return
				else{
					$(fieldtemp).value='editor';					
					$('editor_warning_'+textarea).value=1;
				}
			}
		}
		if(fonttemp!=''){
			tempbutton1='"paste,pastetext,pasteword,separator,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,separator,outdent,indent,separator,undo,redo,separator,link,unlink,anchor,image"';
			tempbutton2='"'+fonttemp+'separator,bold,italic,underline,strikethrough,forecolor,backcolor"';
			tempbutton3='"cut,copy,separator,search,replace,separator,cleanup,removeformat,separator,sub,sup,charmap,separator,media,separator,tablecontrols,visualaid"';			
		}
		else{
			tempbutton1='"paste,pastetext,pasteword,separator,bold,italic,underline,strikethrough,forecolor,backcolor,separator,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,separator,outdent,indent,separator,undo,redo,separator,link,unlink,anchor,image"';
			tempbutton2='"cut,copy,separator,search,replace,separator,cleanup,removeformat,separator,sub,sup,charmap,separator,media,separator,tablecontrols,visualaid"';
			tempbutton3='""';
		}				
		tinyMCE.init({
			mode : "exact",
			theme : "advanced",
			skin : "o2k7",			
		    elements  : "+textarea+",
			plugins : "safari,table,media,searchreplace,contextmenu,inlinepopups,paste",
			theme_advanced_disable:"",			
			theme_advanced_buttons1:eval(tempbutton1),
			theme_advanced_buttons2:eval(tempbutton2),
			theme_advanced_buttons3:eval(tempbutton3),
			theme_advanced_statusbar_location : "none",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_link_targets : eval('"'+DSLang('mainwindow')+'=main;Reload=_top"'),
			extended_valid_elements : "+textarea[accesskey|class|cols|dir<ltr?rtl|disabled<disabled|id|lang|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onselect|readonly<readonly|rows|style|tabindex|title],input[accept|accesskey|align<bottom?left?middle?right?top|alt|checked<checked|class|dir<ltr?rtl|disabled<disabled|id|ismap<ismap|lang|maxlength|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onselect|readonly<readonly|size|src|style|tabindex|title|type<button?checkbox?file?hidden?image?password?radio?reset?submit?text|usemap|value],+iframe[align<bottom?left?middle?right?top|class|frameborder|height|id|longdesc|marginheight|marginwidth|name|scrolling<auto?no?yes|src|style|title|width],+fieldset[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+form[accept|accept-charset|action|class|dir<ltr?rtl|enctype|id|lang|method<get?post|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onreset|onsubmit|style|title|target],+noscript[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+object[align<bottom?left?middle?right?top|archive|border|class|classid|codebase|codetype|data|declare|dir<ltr?rtl|height|hspace|id|lang|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|standby|style|tabindex|title|type|usemap|vspace|width],+optgroup[class|dir<ltr?rtl|disabled<disabled|id|label|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+option[class|dir<ltr?rtl|disabled<disabled|id|label|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|selected<selected|style|title|value],+script[charset|defer|language|src|type],+select[class|dir<ltr?rtl|disabled<disabled|id|lang|multiple<multiple|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|size|style|tabindex|title],param[id|name|type|value|valuetype<DATA?OBJECT?REF],+label[accesskey|class|dir<ltr?rtl|for|id|lang|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],link[charset|class|dir<ltr?rtl|href|hreflang|id|lang|media|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|rel|rev|style|title|target|type],+legend[align<bottom?left?right?top|accesskey|class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+map[class|dir<ltr?rtl|id|lang|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+area[accesskey|alt|class|coords|dir<ltr?rtl|href|id|lang|nohref<nohref|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|shape<circle?default?poly?rect|style|tabindex|title|target],+a[accesskey|charset|class|coords|dir<ltr?rtl|href|hreflang|id|lang|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|rel|rev|shape<circle?default?poly?rect|style|tabindex|title|target|type],+dd[class|id|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex],+dl[class|id|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex],+dt[class|id|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex]",
			table_styles : "DSTable_Table=dstable_table",
			table_cell_styles : "DSTable_Cell=dstable_cell",
			table_row_styles : "DSTable_Row=dstable_row",			
			document_base_url:eval('"'+DSFrontURL+'/"'),				
			language:eval('"'+dslang+'"'),
			docs_language:eval('"'+dslang+'"'),
			debug: false,
			width:"100%",
			height:eval('"'+height+'"'),
			force_hex_style_colors : true,
			force_br_newlines : DSEditorForceBR,
			force_p_newlines : DSEditorForceP,
			forced_root_block : false,			
			inline_styles : false,
			relative_urls: true,
			convert_urls : false,			
			apply_source_formatting: true,
			button_tile_map: true,
			dialog_type: "window",
			convert_fonts_to_spans : false,
			cleanup : true,
			verify_html:true,
			remove_linebreaks : false,
//			cleanup_callback : "mceTagWrap",
			entity_encoding:eval('"'+entity_encoding+'"'),
			paste_use_dialog : false,
			file_browser_callback : "dstinymcecustomfilebrowser",
			init_instance_callback: "dsEditorCustomInitInstance",
			paste_postprocess : function(pl, o) {
				if(o.wordContent==true && DSEditorForceBR==true){
					var test = o.node.innerHTML;
					test = test.replace(/<p>/g,'');
					test = test.replace(/<\/p>/g,'</br>');					
					test = test.replace(/\&nbsp\;/g, ' ');
					test = test.replace(/\s{2,}/g, ' ');				
					o.node.innerHTML=test;
				}
			}
		});
		tinyMCE.execCommand('mceAddControl',false,textarea);
		$('editorname_'+textarea).innerHTML='['+DSLang('contenteditor')+']';		
		if($('dirshow_'+textarea)!=null)		
			$('dirshow_'+textarea).style.display='none';
	}
	else if(action=='frontend') {
		if(fonttemp!=''){
			tempbutton1='"paste,pastetext,pasteword,separator,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,separator,outdent,indent,separator,undo,redo"';
			tempbutton2='"'+fonttemp+'separator,bold,italic,underline,strikethrough,forecolor,backcolor"';
		}
		else{
			tempbutton1='"paste,pastetext,pasteword,separator,bold,italic,underline,strikethrough,forecolor,backcolor,separator,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,separator,outdent,indent,separator,undo,redo"';
			tempbutton2='""';
		}
		tinyMCE.init({
			mode : "exact",
			theme : "advanced",
			skin : "o2k7",			
		    elements  : "+textarea+",
			plugins : "safari,table,media,searchreplace,contextmenu,inlinepopups,paste",
			theme_advanced_disable:"",			
			theme_advanced_buttons1:eval(tempbutton1),
			theme_advanced_buttons2:eval(tempbutton2),
			theme_advanced_buttons3 : "",
			theme_advanced_statusbar_location : "none",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_link_targets :  eval('"'+DSLang('mainwindow')+'=main;Reload=_top"'),
			extended_valid_elements : "+textarea[accesskey|class|cols|dir<ltr?rtl|disabled<disabled|id|lang|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onselect|readonly<readonly|rows|style|tabindex|title],input[accept|accesskey|align<bottom?left?middle?right?top|alt|checked<checked|class|dir<ltr?rtl|disabled<disabled|id|ismap<ismap|lang|maxlength|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onselect|readonly<readonly|size|src|style|tabindex|title|type<button?checkbox?file?hidden?image?password?radio?reset?submit?text|usemap|value],+iframe[align<bottom?left?middle?right?top|class|frameborder|height|id|longdesc|marginheight|marginwidth|name|scrolling<auto?no?yes|src|style|title|width],+fieldset[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+form[accept|accept-charset|action|class|dir<ltr?rtl|enctype|id|lang|method<get?post|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onreset|onsubmit|style|title|target],+noscript[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+object[align<bottom?left?middle?right?top|archive|border|class|classid|codebase|codetype|data|declare|dir<ltr?rtl|height|hspace|id|lang|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|standby|style|tabindex|title|type|usemap|vspace|width],+optgroup[class|dir<ltr?rtl|disabled<disabled|id|label|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+option[class|dir<ltr?rtl|disabled<disabled|id|label|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|selected<selected|style|title|value],+script[charset|defer|language|src|type],+select[class|dir<ltr?rtl|disabled<disabled|id|lang|multiple<multiple|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|size|style|tabindex|title],param[id|name|type|value|valuetype<DATA?OBJECT?REF],+label[accesskey|class|dir<ltr?rtl|for|id|lang|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],link[charset|class|dir<ltr?rtl|href|hreflang|id|lang|media|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|rel|rev|style|title|target|type],+legend[align<bottom?left?right?top|accesskey|class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+map[class|dir<ltr?rtl|id|lang|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+area[accesskey|alt|class|coords|dir<ltr?rtl|href|id|lang|nohref<nohref|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|shape<circle?default?poly?rect|style|tabindex|title|target],+a[accesskey|charset|class|coords|dir<ltr?rtl|href|hreflang|id|lang|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|rel|rev|shape<circle?default?poly?rect|style|tabindex|title|target|type],+dd[class|id|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex],+dl[class|id|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex],+dt[class|id|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex]",
			table_styles : "DSTable_Table=dstable_table",
			table_cell_styles : "DSTable_Cell=dstable_cell",
			table_row_styles : "DSTable_Row=dstable_row",			
			document_base_url:eval('"'+DSFrontURL+'/"'),
			language:eval('"'+dslang+'"'),
			docs_language:eval('"'+dslang+'"'),
			debug: false,
			width:"100%",
			height:eval('"'+height+'"'),
			force_hex_style_colors : true,
			force_br_newlines: DSEditorForceBR,
			force_p_newlines : DSEditorForceP,
			forced_root_block : false,
			inline_styles : false,
			relative_urls: true,
			convert_urls : false,			
			apply_source_formatting: true,
			button_tile_map: true,
			dialog_type: "window",
			convert_fonts_to_spans : false,
			cleanup : true,
			verify_html:true,
			remove_linebreaks : false,
//			cleanup_callback : "mceTagWrap",
			entity_encoding:eval('"'+entity_encoding+'"'),
			paste_use_dialog : false,
			file_browser_callback : "dstinymcecustomfilebrowser",
			init_instance_callback: "dsEditorCustomInitInstance",
			paste_postprocess : function(pl, o) {
				if(o.wordContent==true && DSEditorForceBR==true){
					var test = o.node.innerHTML;
					test = test.replace(/<p>/g,'');
					test = test.replace(/<\/p>/g,'</br>');					
					test = test.replace(/\&nbsp\;/g, ' ');
					test = test.replace(/\s{2,}/g, ' ');				
					o.node.innerHTML=test;
				}
			}
		});
		tinyMCE.execCommand('mceAddControl',false,textarea);
		if($('dirshow_'+textarea)!=null)		
			$('dirshow_'+textarea).style.display='none';
	}
	else if(action=='frontendtable') {
		if(fonttemp!=''){
			tempbutton1='"paste,pastetext,pasteword,separator,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,separator,outdent,indent,separator,undo,redo"';
			tempbutton2='"'+fonttemp+'separator,bold,italic,underline,strikethrough,forecolor,backcolor"';
			tempbutton3='"cut,copy,separator,search,replace,separator,cleanup,removeformat,separator,sub,sup,charmap,separator,flash,separator,tablecontrols,visualaid"';			
		}
		else{
			tempbutton1='"paste,pastetext,pasteword,separator,bold,italic,underline,strikethrough,forecolor,backcolor,separator,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,separator,outdent,indent,separator,undo,redo"';
			tempbutton2='"cut,copy,separator,search,replace,separator,cleanup,removeformat,separator,sub,sup,charmap,separator,flash,separator,tablecontrols,visualaid"';
			tempbutton3='""';
		}						
		tinyMCE.init({
			mode : "exact",
			theme : "advanced",
			skin : "o2k7",			
		    elements  : "+textarea+",
			plugins : "safari,table,media,searchreplace,contextmenu,inlinepopups,paste",
			theme_advanced_disable:"",			
			theme_advanced_buttons1:eval(tempbutton1),
			theme_advanced_buttons2:eval(tempbutton2),
			theme_advanced_buttons3:eval(tempbutton3),
			theme_advanced_statusbar_location : "none",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_link_targets : eval('"'+DSLang('mainwindow')+'=main;Reload=_top"'),
			extended_valid_elements : "+textarea[accesskey|class|cols|dir<ltr?rtl|disabled<disabled|id|lang|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onselect|readonly<readonly|rows|style|tabindex|title],input[accept|accesskey|align<bottom?left?middle?right?top|alt|checked<checked|class|dir<ltr?rtl|disabled<disabled|id|ismap<ismap|lang|maxlength|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onselect|readonly<readonly|size|src|style|tabindex|title|type<button?checkbox?file?hidden?image?password?radio?reset?submit?text|usemap|value],+iframe[align<bottom?left?middle?right?top|class|frameborder|height|id|longdesc|marginheight|marginwidth|name|scrolling<auto?no?yes|src|style|title|width],+fieldset[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+form[accept|accept-charset|action|class|dir<ltr?rtl|enctype|id|lang|method<get?post|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onreset|onsubmit|style|title|target],+noscript[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+object[align<bottom?left?middle?right?top|archive|border|class|classid|codebase|codetype|data|declare|dir<ltr?rtl|height|hspace|id|lang|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|standby|style|tabindex|title|type|usemap|vspace|width],+optgroup[class|dir<ltr?rtl|disabled<disabled|id|label|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+option[class|dir<ltr?rtl|disabled<disabled|id|label|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|selected<selected|style|title|value],+script[charset|defer|language|src|type],+select[class|dir<ltr?rtl|disabled<disabled|id|lang|multiple<multiple|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|size|style|tabindex|title],param[id|name|type|value|valuetype<DATA?OBJECT?REF],+label[accesskey|class|dir<ltr?rtl|for|id|lang|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],link[charset|class|dir<ltr?rtl|href|hreflang|id|lang|media|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|rel|rev|style|title|target|type],+legend[align<bottom?left?right?top|accesskey|class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+map[class|dir<ltr?rtl|id|lang|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],+area[accesskey|alt|class|coords|dir<ltr?rtl|href|id|lang|nohref<nohref|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|shape<circle?default?poly?rect|style|tabindex|title|target],+a[accesskey|charset|class|coords|dir<ltr?rtl|href|hreflang|id|lang|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|rel|rev|shape<circle?default?poly?rect|style|tabindex|title|target|type],+dd[class|id|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex],+dl[class|id|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex],+dt[class|id|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex]",
			table_styles : "DSTable_Table=dstable_table",
			table_cell_styles : "DSTable_Cell=dstable_cell",
			table_row_styles : "DSTable_Row=dstable_row",			
			document_base_url:eval('"'+DSFrontURL+'/"'),				
			language:eval('"'+dslang+'"'),
			docs_language:eval('"'+dslang+'"'),
			debug: false,
			width:"100%",
			height:eval('"'+height+'"'),
			force_hex_style_colors : true,
			force_br_newlines: DSEditorForceBR,
			force_p_newlines : DSEditorForceP,
			forced_root_block : false,		
			inline_styles : false,
			relative_urls: true,
			convert_urls : false,			
			apply_source_formatting: true,
			button_tile_map: true,
			dialog_type: "window",
			convert_fonts_to_spans : false,
			cleanup : true,
			verify_html:true,
			remove_linebreaks : false,
//			cleanup_callback : "mceTagWrap",
			entity_encoding:eval('"'+entity_encoding+'"'),
			paste_use_dialog : false,
			file_browser_callback : "dstinymcecustomfilebrowser",
			init_instance_callback: "dsEditorCustomInitInstance",
			paste_postprocess : function(pl, o) {
				if(o.wordContent==true && DSEditorForceBR==true){
					var test = o.node.innerHTML;
					test = test.replace(/<p>/g,'');
					test = test.replace(/<\/p>/g,'</br>');					
					test = test.replace(/\&nbsp\;/g, ' ');
					test = test.replace(/\s{2,}/g, ' ');				
					o.node.innerHTML=test;
				}
			}
		});
		tinyMCE.execCommand('mceAddControl',false,textarea);
		if($('dirshow_'+textarea)!=null)		
			$('dirshow_'+textarea).style.display='none';
	}	
	else if(action=='text'){
		if($('dirshow_'+textarea)!=null)		
			$('dirshow_'+textarea).style.display='block';
		$('editorname_'+textarea).innerHTML='['+DSLang('text')+']';
		if($(fieldtemp)!='' && $(fieldtemp)!=null)
			$(fieldtemp).value='text';
	}
	else if(action=='html'){
		if($('dirshow_'+textarea)!=null)		
			$('dirshow_'+textarea).style.display='block';
		$('editorname_'+textarea).innerHTML='['+DSLang('html')+']';
		if($(fieldtemp)!='' && $(fieldtemp)!=null)
			$(fieldtemp).value='html';
	}
	if($('dsacc_dseditor_'+textarea+'_option')!=null)
		$('dsacc_dseditor_'+textarea+'_option').innerHTML=$('DSEditorCall_'+textarea).innerHTML;
	
}


function dsEditorCustomInitInstance(ed) {
	if(ed.id=='ssubject'){
		tinymce.dom.Event.add(ed.getWin(), 'blur', function(e) {
			if($('metaname').value==''){
		        string=ed.getContent().replace(/<[^>]*>/g, '');
				$('metaname').value=string;
			}
		});
	}
}


function dseditorchange(e,textarea,height,changetype,font){
	var html_str='';
	if(font==null)
		font='';
	if(changetype==null)
		changetype=1;
	if(changetype>2)
		html_str+='<a class="dsconmenu" href="javascript:dstinymcstogglehtmlmode(\'text\',\''+textarea+'\',\''+height+'\',\''+font+'\');DSContextHide();">'+DSLang('text')+'</a>';
	if(changetype>0)
		html_str+='<a class="dsconmenu" href="javascript:dstinymcstogglehtmlmode(\'html\',\''+textarea+'\',\''+height+'\',\''+font+'\');DSContextHide();">'+DSLang('html')+'</a>';	
	if(changetype<2)
		html_str+='<a class="dsconmenu" href="javascript:dstinymcstogglehtmlmode(\'frontend\',\''+textarea+'\',\''+height+'\',\''+font+'\');DSContextHide();">'+DSLang('contenteditor')+'</a>';
	else
		html_str+='<a class="dsconmenu" href="javascript:dstinymcstogglehtmlmode(\'simple\',\''+textarea+'\',\''+height+'\',\''+font+'\');DSContextHide();">'+DSLang('contenteditor')+'</a>';	
	if(changetype>1)
		html_str+='<a class="dsconmenu" href="javascript:dstinymcstogglehtmlmode(\'advanced\',\''+textarea+'\',\''+height+'\',\''+font+'\');DSContextHide();">'+DSLang('editoradvanced')+'</a>';
	DSContextShow(e,html_str);			
}


// TinyMCE Zusatz Funktionen behebt die P Tag Problematik [TR] 30.07.07

function mceTagWrap(type, value) {
	switch (type) {
		case "get_from_editor":
			value=mceTrim(value);			
			if(value.charAt(0) == "<" && value.toLowerCase().charAt(1) == "p" && value.charAt(value.length - 1) == ">" && value.toLowerCase().charAt(value.length -2) == "p" && value.charAt(value.length -3) == "/" && value.toLowerCase().lastIndexOf("<p>")==0) {
				value = value.replace(/^<P>/i,'');	
				value = value.replace(/<\/P>$/i,'');
			}
			break;
	}
	return value;
}
function mceTrim(sInString) {
	sInString=sInString.replace( /^\s+/g, "" );// strip leading
	return sInString.replace( /\s+$/g, "" );// strip trailing
}


// *************************************
// * BEGIN Direct Edit                 *
// *************************************
var DSDirectEditStatus='inactive';
var DSDirectEditID='';
var DSDirectTempHref='';
var DSDirectTempTarget='';
var DSDirectTempClass='';

function DSDirectEdit(action){
	var new_function="DSDirectEditPosition(this)";
	var browserinfo = navigator.userAgent;	
	if(action=='active'){
		if(browserinfo.indexOf('MSIE 7') == -1 && browserinfo.indexOf('Firefox') == -1){
			alert(DSLang('alertdirectedit'))
			return
		}		
		top.dsnav.DSDirectEditStatus='active';
		top.dsnav.$('dsdireceditbutton').onclick=new Function('', "top.MAIN.DSDirectEdit('inactive')");
		top.dsnav.$('dsdireceditimage').src=dsgifpath+'icon/page.png';
		if(top.MAIN.$('dsdireceditbutton')!=null){		
			top.MAIN.$('dsdireceditbutton').onclick=new Function('', "top.MAIN.DSDirectEdit('inactive')");
			top.MAIN.$('dsdireceditimage').src=dsgifpath+'icon/page.png';
		}
		for(i=0;i<DSArticleTitleID.length;i++){		
			if($('dsarticletitle_'+DSArticleTitleID[i])!=null){
				$('dsarticletitle_'+DSArticleTitleID[i]).onclick= new Function('', new_function);
				if(ie)
					$('dsarticletitle_'+DSArticleTitleID[i]).attachEvent('onclick', stopevent);
				else
					$('dsarticletitle_'+DSArticleTitleID[i]).addEventListener('click',stopevent,true);
			}
		}
		for(i=0;i<DSArticleBodyID.length;i++){
			if($('dsarticlebody_'+DSArticleBodyID[i])!=null){
				$('dsarticlebody_'+DSArticleBodyID[i]).onclick= new Function('', new_function);			
				if(ie)
					$('dsarticlebody_'+DSArticleBodyID[i]).attachEvent('onclick', stopevent);
				else
					$('dsarticlebody_'+DSArticleBodyID[i]).addEventListener('click',stopevent,true);
			}
		}
		for(i=0;i<DSArticleTitleInactiveID.length;i++){
			if($('dsarticletitle_'+DSArticleTitleInactiveID[i])!=null){
				$('dsarticletitle_'+DSArticleTitleInactiveID[i]).style.opacity='.2';
				if(ie){
					$('dsarticletitle_'+DSArticleTitleInactiveID[i]).style.setAttribute("filter", "alpha(opacity=20)", false);
					$('dsarticletitle_'+DSArticleTitleInactiveID[i]).style.width='100%';
				}
			}
		}
		for(i=0;i<DSArticleBodyInactiveID.length;i++){
			if($('dsarticlebody_'+DSArticleBodyInactiveID[i])!=null){
				$('dsarticlebody_'+DSArticleBodyInactiveID[i]).style.opacity='.2';
				if(ie){
					$('dsarticlebody_'+DSArticleBodyInactiveID[i]).style.width='100%';
					$('dsarticlebody_'+DSArticleBodyInactiveID[i]).style.setAttribute("filter", "alpha(opacity=20)", false);
				}
			}
		}
		if($('dssiteheader')!=null){
			$('dssiteheader').style.opacity='.2';
			if(ie)
				$('dssiteheader').style.setAttribute("filter", "alpha(opacity=20)", false);
		}
		if($('dsmenuheader')!=null){
			$('dsmenuheader').style.opacity='.2';
			if(ie){
				$('dsmenuheader').style.width='100%';			
				$('dsmenuheader').style.setAttribute("filter", "alpha(opacity=20)", false);
			}
		}		
		if($('dsmenus')!=null){
			$('dsmenus').style.opacity='.2';
			if(ie){
				$('dsmenus').style.width='100%';
				$('dsmenus').style.setAttribute("filter", "alpha(opacity=20)", false);
			}
		}
		if($('dsmenufooter')!=null){
			$('dsmenufooter').style.opacity='.2';
			if(ie){
				$('dsmenufooter').style.width='100%';
				$('dsmenufooter').style.setAttribute("filter", "alpha(opacity=20)", false);
			}
		}				
		if($('dscontentheader')!=null){
			$('dscontentheader').style.opacity='.2';
			if(ie){						
				$('dscontentheader').style.width='100%';								
				$('dscontentheader').style.setAttribute("filter", "alpha(opacity=20)", false);
			}
		}
		if($('dscontentfooter')!=null){
			$('dscontentfooter').style.opacity='.2';
			if(ie){									
				$('dscontentfooter').style.width='100%';								
				$('dscontentfooter').style.setAttribute("filter", "alpha(opacity=20)", false);
			}
		}
		if($('dssitefooter')!=null){
			$('dssitefooter').style.opacity='.2';
			if(ie)
				$('dssitefooter').style.setAttribute("filter", "alpha(opacity=20)", false);
		}		
	}
	else{
		top.dsnav.DSDirectEditStatus='inactive';		
		top.dsnav.$('dsdireceditbutton').onclick=new Function('', "top.MAIN.DSDirectEdit('active')");		
		top.dsnav.$('dsdireceditimage').src=dsgifpath+'icon/page_edit.png';
		if(top.MAIN.$('dsdireceditbutton')!=null){
			top.MAIN.$('dsdireceditbutton').onclick=new Function('', "top.MAIN.DSDirectEdit('active')");		
			top.MAIN.$('dsdireceditimage').src=dsgifpath+'icon/page_edit.png';
		}
	
		for(i=0;i<DSArticleTitleID.length;i++){
			if($('dsarticletitle_'+DSArticleTitleID[i])!=null){
				$('dsarticletitle_'+DSArticleTitleID[i]).onclick='';
				if(ie)
					$('dsarticletitle_'+DSArticleTitleID[i]).detachEvent('onclick', stopevent);
				else
					$('dsarticletitle_'+DSArticleTitleID[i]).removeEventListener('click',stopevent,true);				
				tinyMCE.execCommand('mceRemoveControl',false,'dsarticletitle_'+DSArticleTitleID[i]);
			}
		}
		for(i=0;i<DSArticleBodyID.length;i++){
			if($('dsarticlebody_'+DSArticleBodyID[i])!=null){
				$('dsarticlebody_'+DSArticleBodyID[i]).onclick='';
				if(ie)
					$('dsarticlebody_'+DSArticleBodyID[i]).detachEvent('onclick', stopevent);
				else
					$('dsarticlebody_'+DSArticleBodyID[i]).removeEventListener('click',stopevent,true);				
				tinyMCE.execCommand('mceRemoveControl',false,'dsarticlebody_'+DSArticleBodyID[i]);
			}
		}
		for(i=0;i<DSArticleTitleInactiveID.length;i++){
			if($('dsarticletitle_'+DSArticleTitleInactiveID[i])!=null){
				$('dsarticletitle_'+DSArticleTitleInactiveID[i]).style.opacity='';
				$('dsarticletitle_'+DSArticleTitleInactiveID[i]).style.filter='';
			}
		}
		for(i=0;i<DSArticleBodyInactiveID.length;i++){
			if($('dsarticlebody_'+DSArticleBodyInactiveID[i])!=null){
				$('dsarticlebody_'+DSArticleBodyInactiveID[i]).style.opacity='';
				$('dsarticlebody_'+DSArticleBodyInactiveID[i]).style.filter='';
			}
		}
		if($('dssiteheader')!=null){
			$('dssiteheader').style.opacity='';
			$('dssiteheader').style.filter='';
		}
		if($('dsmenuheader')!=null){
			$('dsmenuheader').style.opacity='';
			$('dsmenuheader').style.filter='';
		}		
		if($('dsmenus')!=null){
			$('dsmenus').style.opacity='';
			$('dsmenus').style.filter='';
		}
		if($('dsmenufooter')!=null){
			$('dsmenufooter').style.opacity='';
			$('dsmenufooter').style.filter='';
		}		
		if($('dscontentheader')!=null){
			$('dscontentheader').style.opacity='';
			$('dscontentheader').style.filter='';
		}
		if($('dscontentfooter')!=null){
			$('dscontentfooter').style.opacity='';
			$('dscontentfooter').style.filter='';
		}
		if($('dssitefooter')!=null){
			$('dssitefooter').style.opacity='';
			$('dssitefooter').style.filter='';
		}			
		DSDirectEditID='';						
	}
}
function stopevent(event){
	if(ie){
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	else
		event.preventDefault();
}
DSArticleImage='';
function DSDirectEditPosition(this_element){
	this_element_id=this_element.id;
	if(this_element_id.split('_')[0]=='dsarticletitle' || this_element_id.split('_')[0]=='dsarticlebody'){
		if(this_element_id.split('_')[0]=='dsarticletitle' && $(this_element_id).getElementsByTagName('a')[0].innerHTML=='' && $(this_element_id).getElementsByTagName('a')[0].name=='dstitle_'+this_element_id.split('_')[1])
			$(this_element_id).getElementsByTagName('a')[0].parentNode.removeChild($(this_element_id).getElementsByTagName('a')[0]);
		else if (this_element_id.split('_')[0]=='dsarticletitle'){
			DSDirectTempHref=$(this_element_id).getElementsByTagName('a')[0].href;
			DSDirectTempClass=$(this_element_id).getElementsByTagName('a')[0].classname;				
			if(DSDirectTempTarget=$(this_element_id).getElementsByTagName('a')[0].target!=null)
				DSDirectTempTarget=$(this_element_id).getElementsByTagName('a')[0].target;
			$(this_element_id).innerHTML=$(this_element_id).getElementsByTagName('a')[0].innerHTML;
		}
		if(document.getElementsByTagName('base')[0]!=null)
			document.getElementsByTagName('base')[0].parentNode.removeChild(document.getElementsByTagName('base')[0]);
		DSArticleImage=$(this_element_id).getElementsBySelector('[title="dsimage_div"]');
		for(i=0;i<DSArticleImage.length;i++){
			DSArticleImage[i].remove();
		}						
		for(i=0;i<$(this_element_id).getElementsByTagName('img').length;i++){
			if($(this_element_id).getElementsByTagName('img')[i].src.indexOf(DSFrontURL)!=-1)
				$(this_element_id).getElementsByTagName('img')[i].src=$(this_element_id).getElementsByTagName('img')[i].src.replace(DSFrontURL+'/', '');
		}
		for(i=0;i<$(this_element_id).getElementsByTagName('a').length;i++){
			$(this_element_id).getElementsByTagName('a')[i].href=$(this_element_id).getElementsByTagName('a')[i].href.replace(DSAdminURL+'/main.cfm', 'dynasite.cfm');
		}		
		tinyMCE.execCommand('mceAddControl',false,this_element_id);
		window.setTimeout("tinyMCE.execCommand('mceFocus',false,this_element_id);",100);
		DSDirectEditID=this_element_id;
	}
}


function myHandleEvent(e) {
	if(e.type=='blur'){
		tempcontent=tinyMCE.getContent();
		tinyMCE.execCommand('mceRemoveControl',false,DSDirectEditID);
		for(i=0;i<DSArticleImage.length;i++){
			$(this_element_id).insert({top:DSArticleImage[i]});
			//prototype.insert(this_element_id,{before:DSArticleImage[i]});
		}						
		for(i=0;i<$(this_element_id).getElementsByTagName('img').length;i++){
			$(this_element_id).getElementsByTagName('img')[i].src=$(this_element_id).getElementsByTagName('img')[i].src.replace(DSAdminURL+'/', DSFrontURL+'/');
		}
		for(i=0;i<$(this_element_id).getElementsByTagName('a').length;i++){
			$(this_element_id).getElementsByTagName('a')[i].href=$(this_element_id).getElementsByTagName('a')[i].href.replace(DSAdminURL+'dynasite.cfm', DSAdminURL+'/main.cfm').replace(DSFrontURL+'/dynasite.cfm', DSAdminURL+'/main.cfm');
		}
		dsloader(dsxpath+'dynasite.cfm?dscmd=content_article_direct_edit&DSDirectEditID='+DSDirectEditID.split('_')[1]+'&DSDirectEditType='+DSDirectEditID.split('_')[0],'dsloader');
		if(DSDirectEditID.split('_')[0]=='dsarticletitle'){
			if(DSDirectTempTarget!='')
				DSDirectTempTarget='target="'+DSDirectTempTarget+'"';
			if(DSDirectTempHref!='')
				$(this_element_id).innerHTML='<a name="dstitle_'+DSDirectEditID.split('_')[1]+'" class="'+DSDirectTempClass+'" href='+DSDirectTempHref+' '+DSDirectTempTarget+'>'+$(this_element_id).innerHTML+'</a>';			
			else
				$(this_element_id).innerHTML='<a name="dstitle_'+DSDirectEditID.split('_')[1]+'"></a>'+$(this_element_id).innerHTML;
		}
		DSDirectTempHref='';
		DSDirectTempClass='';		
		DSDirectTempTarget='';

	}
	return true;
}


// *************************************
// * END Direct Edit                   *
// *************************************

/* mouseover Prototype JS MEnu used by DL Helicopter */
var Menu = Class.create();
Menu.prototype = {
	
	initialize: function(idOrElement, name, customConfigFunction) {
		this.name = name;
		this.type = "menu";
		this.closeDelayTimer = null;
		this.closingMenuItem = null;
		this.config();
		if (typeof customConfigFunction == "function") {
			this.customConfig = customConfigFunction;
			this.customConfig();
		}
		this.rootContainer = new MenuContainer(idOrElement, this);
	},
	
	config: function() {
		this.collapseBorders = true;
		this.quickCollapse = true;
		this.closeDelayTime = 300;
	}
}





var MenuContainer = Class.create();
MenuContainer.prototype = {
	
	initialize: function(idOrElement, parent) {
		this.type = "menuContainer";
		this.menuItems = [];
		this.init(idOrElement, parent);
	},

	init: function(idOrElement, parent) {
		this.element = $(idOrElement);
		this.parent = parent;
		this.parentMenu = (this.type == "menuContainer") ? ((parent) ? parent.parent : null) : parent;
		this.root = parent instanceof Menu ? parent : parent.root;
		this.id = this.element.id;

		if (this.type == "menuContainer") {
			if (this.element.hasClassName("level1")) 
				this.menuType = "horizontal";
			else if (this.element.hasClassName("dssubmenus_1") || this.element.hasClassName("submenus_1")) 
				this.menuType = "dropdown";
			else 
				this.menuType = "flyout";
	
			if (this.menuType == "flyout" || this.menuType == "dropdown") {
				this.isOpen = false;
				Element.setStyle(this.element, {
					position: "absolute",
					top: "0px",
					left: "0px",
					visibility: "hidden"
				});
			}
			else {
				this.isOpen = true;
			}
		}
		else {
			this.isOpen = this.parentMenu.isOpen;
		}

		var childNodes = this.element.childNodes;
		if (childNodes == null) return;
	
		for (var i = 0; i < childNodes.length; i++) {
			var node = childNodes[i];
			if (node.nodeType == 1) {
				if (this.type == "menuContainer") {
					if (node.tagName.toLowerCase() == "li") {
						this.menuItems.push(new MenuItem(node, this));
					}
				}
				else {
					if (node.tagName.toLowerCase() == "ul")
						this.subMenu = new MenuContainer(node, this);
				}
			}
		}
	},

	getBorders: function(element) {
		var ltrb = ["Left","Top","Right","Bottom"];
		var result = {};
		for (var i = 0; i < ltrb.length; ++i) {
			if (this.element.currentStyle)
				var value = parseInt(this.element.currentStyle["border"+ltrb[i]+"Width"]);
			else if (window.getComputedStyle)
				var value = parseInt(window.getComputedStyle(this.element, "").getPropertyValue("border-"+ltrb[i].toLowerCase()+"-width"));
			else
				var value = parseInt(this.element.style["border"+ltrb[i]]);
			result[ltrb[i].toLowerCase()] = isNaN(value) ? 0 : value;
		}
		return result;
	},

	open: function() {
		if (this.root.closeDelayTimer) window.clearTimeout(this.root.closeDelayTimer);
		this.parentMenu.closeAll(this);
		this.isOpen = true;
		if (this.menuType == "dropdown") {
			Element.setStyle(this.element,{
				left: (Position.positionedOffset(this.parent.element)[0]) + "px",
				top: (Position.positionedOffset(this.parent.element)[1] + Element.getHeight(this.parent.element)) + "px"
			});
	  	}
		else if (this.menuType == "flyout") {
			var parentMenuBorders = this.parentMenu ? this.parentMenu.getBorders() : new Object();
			var thisBorders = this.getBorders();
			if ((Position.positionedOffset(this.parentMenu.element)[0] + this.parentMenu.element.offsetWidth + this.element.offsetWidth + 20) > (window.innerWidth ? window.innerWidth : document.body.offsetWidth)) {
				Element.setStyle(this.element,{
					left: (- this.element.offsetWidth - (this.root.collapseBorders ?  0 : parentMenuBorders["left"])) + "px"
				});
			}
			else {
				Element.setStyle(this.element,{
					left: (this.parentMenu.element.offsetWidth - parentMenuBorders["left"] - (this.root.collapseBorders ?  Math.min(parentMenuBorders["right"], thisBorders["left"]) : 0)) + "px"
				});
			}
			Element.setStyle(this.element,{
				top: (this.parent.element.offsetTop - parentMenuBorders["top"] - this.menuItems[0].element.offsetTop) + "px"
			});
		}
		Element.setStyle(this.element,{visibility: "visible"});
	},

	close: function() {
		Element.setStyle(this.element,{visibility: "hidden"});
		this.isOpen = false;
		this.closeAll();
	},

	closeAll: function(trigger) {
		for (var i = 0; i < this.menuItems.length; ++i) {
			this.menuItems[i].closeItem(trigger);
		}
	}
}


var MenuItem = Class.create();
Object.extend(Object.extend(MenuItem.prototype, MenuContainer.prototype), {
							
	initialize: function(idOrElement, parent) {
		var menuItem = this;
		this.type = "menuItem";
		this.subMenu;
		this.init(idOrElement, parent);
		if (this.subMenu) {
			this.element.onmouseover = function() {
				menuItem.subMenu.open();
			}
		}
		else {
			if (this.root.quickCollapse) {
				this.element.onmouseover = function() {
					menuItem.parentMenu.closeAll();
				}
			}
		}
		var linkTag = this.element.getElementsByTagName("A")[0];
		if (linkTag) {
			linkTag.onfocus = this.element.onmouseover;
			this.link = linkTag;
			this.text = linkTag.text;
		}
		if (this.subMenu) {
			this.element.onmouseout = function() {
				if (menuItem.root.openDelayTimer) window.clearTimeout(menuItem.root.openDelayTimer);


if (menuItem.root.closeDelayTimer) window.clearTimeout(menuItem.root.closeDelayTimer);



eval(menuItem.root.name + ".closingMenuItem = menuItem");
				menuItem.root.closeDelayTimer = window.setTimeout(menuItem.root.name + ".closingMenuItem.subMenu.close()", menuItem.root.closeDelayTime);
			}
		}
	},
	
	openItem: function() {
		this.isOpen = true;
		if (this.subMenu) { this.subMenu.open(); }
	},
	
	closeItem: function(trigger) {
		this.isOpen = false;
		if (this.subMenu) {
			if (this.subMenu != trigger) this.subMenu.close();
		}
	}
});

/* END mouseover Prototype JS MEnu used by DL Helicopter */

 
 /** 
 * @description		prototype.js based context menu
 * @author        Juriy Zaytsev; kangax [at] gmail [dot] com; http://thinkweb2.com/projects/prototype/
 * @version       0.6
 * @date          12/03/07
 * @requires      prototype.js 1.6
*/
//Start
if (Object.isUndefined(Proto)) { var Proto = { } }

Proto.MenuObjects=new Array();

Proto.Menu = Class.create({
	initialize: function() {
		var e = Prototype.emptyFunction;
		this.ie = Prototype.Browser.IE;
		this.options = Object.extend({
			selector: '.contextmenu',
			className: 'protoMenu',
			pageOffset: 25,
			fade: false,
			zIndex: 100,
			beforeShow: e,
			beforeHide: e,
			beforeSelect: e,
			mouseevent: 'contextmenu' //rightclick:contextmenu, leftclick:click, onMouseover:mouseover
		}, arguments[0] || { });
		this.shim = new Element('iframe', {
			style: 'position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);display:none',
			src: 'javascript:false;',
			frameborder: 0
		});
		this.options.fade = this.options.fade && !Object.isUndefined(Effect);
		this.container = new Element('div', {className: this.options.className, style: 'display:none'});

		document.observe('click', function(e) {
			if (this.container.visible() && !e.isRightClick()) {
				this.options.beforeHide(e);
				if (this.ie) this.shim.hide();
				this.container.hide();
			}
		}.bind(this));

		var that=this;
		$$(this.options.selector).each(function(element){
			element.observe(that.options.mouseevent,function(e){
				if (Prototype.Browser.Opera && !e.ctrlKey) {
					return;
				}
				that.show(e,element);
			});
		});
		
		
		
		/*$$(this.options.selector).invoke('observe', Prototype.Browser.Opera ? 'click' : this.options.mouseevent, function(e){
			if (Prototype.Browser.Opera && !e.ctrlKey) {
				return;
			}
			this.show(e);
		}.bind(this));*/
		

		Proto.MenuObjects[Proto.MenuObjects.length]=this;
	},
	show: function(e,element) {
		if(this.options.menuItems.split('_')[0]=='menu')
			alert(1);
		else
			this.options.evalmenuItems=eval(this.options.menuItems);
		var list = new Element('ul');
		var that=this;
		optionlist='';
		if(element.attributes.optionlist)
			var optionlist=eval(element.attributes.optionlist.value);
		this.options.evalmenuItems.each(function(item) {
			if((!item.check) || (eval('optionlist[0].'+item.check))){
				list.insert(
					new Element('li', {className: item.separator ? 'separator' : ''}).insert(
						item.separator 
							? '' 
							: Object.extend(new Element('a', {
								href: 'javascript:dynasite()',
								title: item.name,
								className: (item.className || '') + (item.disabled ? ' disabled' : ' enabled')
							}), { _callback: item.callback })
							.observe('click', 
								function(e){
									that.onClick(e,element)
								}
							)
							.observe(this.options.mouseevent, Event.stop)
							.update(item.name)
					)
				)
			}
		}.bind(this));
		this.container.innerHTML='';
		$(document.body).insert(this.container.insert(list).observe(this.options.mouseevent, Event.stop));
		if (this.ie) { $(document.body).insert(this.shim) }		
		
		Proto.MenuObjects.each(function(thisitem) {
			thisitem.options.beforeHide(e);
			if (thisitem.ie) thisitem.shim.hide();
			thisitem.container.hide();  
		});		
		
		Event.stop(e);
		this.options.beforeShow(e);
		var x = Event.pointer(e).x,
			y = Event.pointer(e).y,
			vpDim = document.viewport.getDimensions(),
			vpOff = document.viewport.getScrollOffsets(),
			elDim = this.container.getDimensions(),
			elOff = {
				left: ((x + elDim.width + this.options.pageOffset) > vpDim.width 
					? (vpDim.width - elDim.width - this.options.pageOffset) : x) + 'px',
				top: ((y - vpOff.top + elDim.height) > vpDim.height && (y - vpOff.top) > elDim.height 
					? (y - elDim.height) : y) + 'px'
			};
		this.container.setStyle(elOff).setStyle({zIndex: this.options.zIndex});
		if (this.ie) { 
			this.shim.setStyle(Object.extend(Object.extend(elDim, elOff), {zIndex: this.options.zIndex - 1})).show();
		}
		this.options.fade ? Effect.Appear(this.container, {duration: 0.25}) : this.container.show();
		this.event = e;
	},
	onClick: function(e,element) {
		e.stop();
		if (e.target._callback && !e.target.hasClassName('disabled')) {
			this.options.beforeSelect(e);
			if (this.ie) this.shim.hide();
			this.container.hide();
			e.target._callback(this.event,element);
		}
	}
})
//End

// ***************************
// * START ContextMenu       *
// ***************************
context_onmouseout_space=25; //spacer which has to close "context" on mouse over
context_mouse_to_closer=10; // space between mouse and onmouseover-space to close the context
context_mouse_to_context=2; // space between mouse and context
context_mouse_space=context_mouse_to_closer+context_mouse_to_context;

function DSContextHide(){
	if ($("context") != null){
		$("context").style.display="none";
		if (ie)
			$("context_ie_help").style.display="none";
	}
}

function DSDoNothing() {
	
}

function dynasite() {}

function DSContextInnerHTML(this_content, onmouseout){
	context_div=$("context");
	context_div.IsMouseOver=0;
	//context_div.innerHTML='<div style="width:320px; height:200px">dasdsad</div>';
	//onmouseout_color='blue';
	//mouse_space_color='red';
	onmouseout_color=mouse_space_color='transparent';
	if (onmouseout==1){
		new_htm_str='<table cellpadding="0" cellspacing="0" border="0" style="background-color: transparent; position:relative; top:0px; left:0px;">';
		new_htm_str+='<tr>';
			new_htm_str+='<td style="background-color: '+onmouseout_color+';" colspan="3" onmouseover="DSContextHide()" height="'+context_onmouseout_space+'"> </td>';
		new_htm_str+='</tr>';
		new_htm_str+='<tr>';
			new_htm_str+='<td style="background-color: '+onmouseout_color+';" onmouseover="DSContextHide()" width="'+context_onmouseout_space+'"></td>';
			new_htm_str+='<td>';
				new_htm_str+='<table cellpadding="0" cellspacing="0" border="0" style="background-color: transparent;">';
				new_htm_str+='<tr>';
					new_htm_str+='<td style="background-color: '+mouse_space_color+';" colspan="3" height="'+context_mouse_space+'"></td>';
				new_htm_str+='</tr>';
				new_htm_str+='<tr>';
					new_htm_str+='<td style="background-color: '+mouse_space_color+';" width="'+context_mouse_space+'"></td>';
					new_htm_str+='<td style="background-color: '+mouse_space_color+';">'+this_content+'</td>';
					new_htm_str+='<td style="background-color: '+mouse_space_color+';" width="'+context_mouse_space+'"></td>';
				new_htm_str+='</tr>';
				new_htm_str+='<tr>';
					new_htm_str+='<td style="background-color: '+mouse_space_color+';" colspan="3" height="'+context_mouse_space+'"></td>';
				new_htm_str+='</tr>';
				new_htm_str+='</table>';
			new_htm_str+='</td>';
			new_htm_str+='<td style="background-color: '+onmouseout_color+';" onmouseover="DSContextHide()" width="'+context_onmouseout_space+'"></td>';
		new_htm_str+='</tr>';
		new_htm_str+='<tr>';
		new_htm_str+='<td colspan="3" style="background-color: '+onmouseout_color+';" onmouseover="DSContextHide()" height="'+context_onmouseout_space+'"> </td>';
		new_htm_str+='</tr>';
		new_htm_str+='</table>';
		//context_div.innerHTML='<textarea cols=30 rows=30>'+new_htm_str+'</textarea>';
		context_div.innerHTML=new_htm_str;
	}
	else{
		new_htm_str='<table cellpadding="0" cellspacing="0"><tr><td style="background-color: '+mouse_space_color+'; padding:'+context_mouse_to_context+'px">';
		new_htm_str+=this_content;
		new_htm_str+='</td></tr></table>';
		context_div.innerHTML=new_htm_str;
	}
}

function DSContextShow(e,this_content,info){
	if (dcbe==null)
		DSInit()
	context_div=$("context");
	x_show="right";//left,middle,right
	y_show="bottom";//top,middle,bottom
	onmouseout=1; // 0: no function, 1: onmouseout context will be closed
	if (typeof info!='undefined' && info!=''){
		this_info=info.split(';');
		for (i=0;i<this_info.length;i++){
			eval(this_info[i])
		}
	}
	if (onmouseout)
		onmouseout_space=context_onmouseout_space;
	else
		onmouseout_space=0;
	if($(this_content)){
		this_content=$(this_content).innerHTML;
	}
	if (typeof this_content != 'undefined' && this_content != ''){
		DSContextInnerHTML(this_content,onmouseout);
	}

	context_div.style.display="block";
	this_left=DSContextPos(e,context_div,'x',x_show,onmouseout);
	this_top=DSContextPos(e,context_div,'y',y_show,onmouseout);
	
	context_div.style.left=this_left+'px';
	context_div.style.top=this_top+'px';
	if (ie){
		context_iframe=$("context_ie_help");
		if (onmouseout){
			this_left= DSInt(this_left+context_mouse_space+context_onmouseout_space);
			this_top= DSInt(this_top+context_mouse_space+context_onmouseout_space);
		}
		else{
			this_left= DSInt(this_left+context_mouse_to_context);
			this_top= DSInt(this_top+context_mouse_to_context);
		}
		context_iframe.style.top = this_top+'px';
	    context_iframe.style.left = this_left+'px';
		context_iframe.style.width = this_width+'px';
		context_iframe.style.height = this_height+'px';
	    context_iframe.style.zIndex = context_div.style.zIndex - 1;
	    context_iframe.style.display = "block";
		//context_iframe.style.border = "1px solid blue";
	}
}

function DSContextPos(e,this_object,xy,show,onmouseout){
	if (onmouseout){
		onmouseout_space=context_onmouseout_space;
		mouse_to_closer=context_mouse_to_closer;
		mouse_to_context=context_mouse_to_context;
		mouse_space=context_mouse_space;
	}
	else{
		onmouseout_space=0;
		mouse_to_closer=0;
		mouse_to_context=context_mouse_to_context;
		mouse_space=context_mouse_to_context;
	}
	if (xy=='x'){
		this_width = DSInt(this_object.offsetWidth-2*onmouseout_space-2*mouse_space);
		xlim = DSInt((dcbe && dcbe.clientWidth)? dcbe.clientWidth : window.innerWidth) + DSInt(window.pageXOffset || (dcbe? dcbe.scrollLeft : 0) || 0) ;
		pos = DSInt(e.pageX || e.clientX || 0) + DSInt(ie? dcbe.scrollLeft : 0);
		this_size=this_width;
		this_lim=xlim;
		//alert(this_size+'...'+this_lim+'...'+pos+'...'+DSInt(e.pageX || e.clientX || 0)+'...'+DSInt(ie? dcbe.scrollLeft : 0)+'...'+ie)
	}
	else{
		this_height = DSInt(this_object.offsetHeight-2*onmouseout_space-2*mouse_space);
		ylim = DSInt((dcbe && dcbe.clientHeight)? dcbe.clientHeight : window.innerHeight) + DSInt(window.pageYOffset || (dcbe? dcbe.scrollTop : 0) || 0) ;
		pos = DSInt(e.pageY || e.clientY || 0) + DSInt(ie? dcbe.scrollTop : 0);
		this_size=this_height;
		this_lim=ylim;
		//alert(this_size+'...'+this_lim+'...'+pos+'...'+DSInt(e.pageY || e.clientY || 0)+'...'+DSInt(ie? dcbe.scrollTop : 0)+'...'+ie)	
	}
	
	if (show=='top' || show=='left'){
		check_pos=pos-this_size-mouse_to_context;
		if (check_pos>=0)
			pos=pos-onmouseout_space-mouse_space-this_size-mouse_to_context;
		else
			pos=pos-onmouseout_space-mouse_to_closer;
	}
	else if (show=='middle'){
		check_pos=DSInt(pos-this_size/2);
		if (check_pos<=0)
			pos=-onmouseout_space-mouse_space;
		else if (check_pos+this_size/2>=this_lim)
			pos=this_lim-this_size-onmouseout_space-mouse_space;
		else
			pos=check_pos-onmouseout_space-mouse_space;
	}
	else if (show=='bottom' || show=='right'){
		check_pos=pos+this_size+mouse_to_context;
		if (check_pos<=this_lim){
			pos=pos-onmouseout_space-mouse_to_closer;
		}
		else{
			pos=pos-onmouseout_space-mouse_space-this_size-mouse_to_context;
		}
	}
	return pos;
}
// ***************************
// * END ContextMenu         *
// ***************************



/* DS Slider used in Assets */
function theslider(element,thewindowobject) {
	thewindowobject[element+'_slider'] = new Control.Slider(element+'_handle',element+'_track',{
		maximum:30,
		minimum:5,
		step:0.5,
		increment:0.5,
		range:$R(5,30),
		disabled:sliderDisabled,
		sliderValue:sliderValue,
		handleImage:'dssliderbutton',
		onSlide:function(v){
			// zoomboxes are set in _asset_view.cfm
			// zoomboxes=$(element).select('[name="'+element+'_zoombox"]');
			zoomboxes.each(function(s) { 
				Element.setContentZoom(s, (v+0.25)*7);
			});
		},
		onChange:function(v){
			// zoomboxes=$(element).select('[name="'+element+'_zoombox"]');
			zoomboxes.each(function(s) { 
				Element.setContentZoom(s, (v+0.25)*7);
			});
		 	$(element+'_dsslidervalue').value=v;
		}
	});
}





if (typeof(dynasite) == "undefined") { dynasite = {}; }
/* DSSliderBox: */
dynasite.DSSliderBox = {
	productSlider: null,
	sliderVal: 0,
	animationId: false,
	// viewportWidth: 980,
	// contentWidth: 980,
	 /* init with offsets, this can be overridden at init */
	categories: [{id: 'pb-cat1', offset: 0}, {id: 'pb-cat2', offset: 0.32}],
	isSliding: false,
	lastX: 0.5,
	isMouseDown: false,
	dif: 0,
	overlap: 0,
	offsetImageWidth: 0,
	sliderOffset: 0,
	// offsetContentWidth: -980,
	clicked: false,
	startIndex: 0,
	name: 'webmart',
	arrowScrollAmount: 0.24,
	init: function(setupArgs) {
		if (typeof(setupArgs.categories) != 'undefined') {this.categories = setupArgs.categories;}
		if (typeof(setupArgs.imageOverlap) != 'undefined') {this.overlap = setupArgs.imageOverlap;}
		if (typeof(setupArgs.sliderCentering) != 'undefined') {this.sliderOffset = setupArgs.sliderCentering;}
		if (typeof(setupArgs.initialCategory) != 'undefined') {this.startIndex = setupArgs.initialCategory;}
		if (typeof(setupArgs.arrowScrollAmount) != 'undefined') {this.arrowScrollAmount = setupArgs.arrowScrollAmount;}

		$('dssliderbox_content').style.display = "block";

		$('dssliderbox_track').style.visibility = "visible";
		$('dssliderbox_container').style.overflow = "hidden";
		
		this.viewportWidth = $('dssliderbox_container').getWidth();
		this.offsetImageWidth = $$('#dssliderbox_content .dssliderbox_image')[0].getWidth()-this.overlap;
		this.contentWidth = this.offsetImageWidth * $$('#dssliderbox_content .dssliderbox_image').length;
		this.offsetContentWidth = -1 * (this.contentWidth - this.viewportWidth);
		
		this.productSlider = new Control.Slider('dssliderbox_handle', 'dssliderbox_track', {axis:'horizontal'});
		/* initial slide */
		dynasite.DSSliderBox.animateSlide(this.categories[this.startIndex].offset); 
		/* Slider callbacks */
		this.productSlider.options.onChange = function(value) {
			$('dssliderbox_handleimage').style.left = $('dssliderbox_handle').style.left;
			
			if (dynasite.DSSliderBox.isThrow && ! dynasite.DSSliderBox.isSliding) {
				dynasite.DSSliderBox.isSliding = true;
				dynasite.DSSliderBox.isThrow = false;
				
				var mod = value + dynasite.DSSliderBox.throwMod;
				if (mod < 0) {mod = 0;}
				if (mod > 1) {mod = 1;}
				dynasite.DSSliderBox.animateSlide(mod);
			}
			else if (! dynasite.DSSliderBox.isSliding && value){
				dynasite.DSSliderBox.isSliding = true;
				dynasite.DSSliderBox.animateSlide(value);
			}	
		};
		this.productSlider.options.onSlide = function(value) {		 
			$('dssliderbox_handleimage').style.left = $('dssliderbox_handle').style.left;
			if (value && ! dynasite.DSSliderBox.isSliding) {
					dynasite.DSSliderBox.isSliding = true;
				 	dynasite.DSSliderBox.isThrow = false;
					if (dynasite.DSSliderBox.isMouseDown) {
						dynasite.DSSliderBox.dif = value - dynasite.DSSliderBox.lastX;
						dynasite.DSSliderBox.lastX = value;	
						
						/* check for throw, the dif thresholds will affect how easily the throw happens */
						if(dynasite.DSSliderBox.dif > 0.05) {
							dynasite.DSSliderBox.isThrow = true;
							dynasite.DSSliderBox.throwMod = 0.2;
						}
						else if (dynasite.DSSliderBox.dif < -0.04) {
							dynasite.DSSliderBox.isThrow = true;
							dynasite.DSSliderBox.throwMod = -0.2;
						}
					}
			
					var w = dynasite.DSSliderBox.offsetContentWidth;
					$('dssliderbox_content').style.left = w * value + "px";
					
					this.sliderVal = value;
					dynasite.DSSliderBox.lastX = value;
					dynasite.DSSliderBox.colorCats();		
					dynasite.DSSliderBox.isSliding = false; /* reset */
			}
			
			Element.setStyle($('dssliderbox_container'), { overflow: "hidden"} );
		};
		
		Event.observe('dssliderbox_track', 'mousedown', function(e) {
			var o = e.offsetX || e.layerX;
			if (Event.element(e).id =='dssliderbox_track' && o < 100) {dynasite.DSSliderBox.animateSlide(0);}
		});
		Event.observe('dssliderbox_leftarrow', 'mousedown', function() {
			dynasite.DSSliderBox.left();
		});
		Event.observe('dssliderbox_rightarrow', 'mousedown', function() {
			dynasite.DSSliderBox.right();
		});
		
		Event.observe('dssliderbox_handle', 'mousedown', function() {
			dynasite.DSSliderBox.isMouseDown = true;
			$('dssliderbox_handle').style.zIndex = "5";
		});
		
		Event.observe('dssliderbox_handle', 'mouseup', function() {
			dynasite.DSSliderBox.isMouseDown = false;
		});
		
		dynasite.DSSliderBox.categories.each(function(c) {
			Event.observe($(c.id), 'mouseup', function(e) {
				dynasite.DSSliderBox.animateSlide(c.offset);
			});
		});			
	},
	
	animateSlide: function(toX) {
		/* make sure toX is sane: */
		if (toX > 1) {toX = 1;}
		if (toX < 0) {toX = 0;}
		dynasite.DSSliderBox.sliderVal = toX;
		window.clearInterval(dynasite.DSSliderBox.animationId); /* kill any running animation */
		var w = dynasite.DSSliderBox.offsetContentWidth;
		var stopPoint = w * toX;
		/* stopPoint = Math.round(stopPoint / dynasite.DSSliderBox.offsetImageWidth) * dynasite.DSSliderBox.offsetImageWidth; */
		var sliderStopPoint = (Math.round(dynasite.DSSliderBox.viewportWidth - dynasite.DSSliderBox.sliderOffset) * toX);
		
		dynasite.DSSliderBox.isSliding = true;
		

		dynasite.DSSliderBox.animationId = window.setInterval(function() {
			var sliderPos = parseInt($('dssliderbox_content').getStyle('left')) || 0;
			var handlePos = parseInt($('dssliderbox_handle').getStyle('left')) || 0;
			var x = dynasite.DSSliderBox.calculateDecel(sliderPos, stopPoint);
			var sx = dynasite.DSSliderBox.calculateDecel(handlePos, sliderStopPoint); 
			$('dssliderbox_content').style.left = x + "px";
			$('dssliderbox_handle').style.left = sx + "px";
			$('dssliderbox_handleimage').style.left = sx + "px";		
			dynasite.DSSliderBox.colorCats();
		
			if (x == stopPoint) {
				window.clearInterval(dynasite.DSSliderBox.animationId);
				dynasite.DSSliderBox.isSliding = false;			
			}
		}, 60);
	},
	
	colorCats: function() {
		var sliderX = parseInt($('dssliderbox_handle').getStyle('left')) + (($('dssliderbox_handle').getWidth()-20)/2);
		dynasite.DSSliderBox.categories.each(function(c) {
			var left = parseInt($(c.id).getStyle('left')) 
		 	var clr = Math.ceil((Math.min(sliderX,left) / Math.max(sliderX,left))*10);
		 	$(c.id).className = 'pb-catclass'+clr;
		});
	},
	
	left: function() {
		dynasite.DSSliderBox.animateSlide(dynasite.DSSliderBox.sliderVal - dynasite.DSSliderBox.arrowScrollAmount);
	},
	
	right: function() {
		dynasite.DSSliderBox.animateSlide(dynasite.DSSliderBox.sliderVal + dynasite.DSSliderBox.arrowScrollAmount);
	},
	
	calculateDecel: function(from, to) {
		var n = from - Math.floor( (from - to) * .4);
		if (Math.abs(from - to) < 4) {return to;}
		else {return n;}
	}
};

/* END DS Slider used in Assets */

/* DS roundedCorner */
// DSRoundedCorner('[class="dsarticle_3 dsarticle"], [class="dsarticle_2 dsarticle"]','top,bottom,both','##F0F0E7','size:medium');
function DSRoundedCorner(selector,corner,color,optionlist){
	var i;
	var v=$('dssubbody').getElementsBySelector('['+selector+']');
	size='medium';
	backgroundColor='#FFF';		
	DSOptionList(optionlist);
	for(i=0;i<v.length;i++){
		if(corner=='top' || corner=='both' || corner=='top,bottom')
			DSRoundedCorner_Add(v[i],backgroundColor,color,size,'top');
		if(corner=='bottom' || corner=='both'|| corner=='top,bottom')
			DSRoundedCorner_Add(v[i],backgroundColor,color,size,'bottom');
	}
}

function DSRoundedCorner_Add(el,bk,color,size,addtype) {
	var i;
	var d=document.createElement("b");
	var cn="dsrounded";
	var lim=4;
	if(size && size=="small"){ cn="dsroundedsmall"; lim=2}
	if(size && size=="wide"){ cn="dsroundedwide"; lim=12}
	d.style.backgroundColor=bk;
	if(addtype=='top') {
		d.className="dsroundedtop";
		for(i=1;i<=lim;i++) {
				var x=document.createElement("b");
				x.className=cn + i;
				x.style.backgroundColor=color;
				d.appendChild(x);
		}
		el.insertBefore(d,el.firstChild);
	}
	else {
		d.className="dsroundedbottom";
		for(i=lim;i>0;i--) {
			var x=document.createElement("b");
			x.className=cn + i;
			x.style.backgroundColor=color;
			d.appendChild(x);
		}
		el.appendChild(d,el.firstChild);
	}
}

/* END DS roundedCorner */

/* DS Tree */
// DispatchEvent=moz FireEvent=ie
function DSDispatchEvent(theobject) {
	//	alert(theobject);

	// alert(theobject);
	obj=$(theobject);
	if(obj!=null) {
		if(ie)
			obj.fireEvent('onclick');							
		else {
			if(document.createEvent && obj.dispatchEvent) {
				var evt=document.createEvent("MouseEvents");
				if(evt && evt.initMouseEvent){
					evt.initMouseEvent("click",true,true,document.defaultView,1,0,0,0,0,false,false,false,false,0,null);
					obj.dispatchEvent(evt);
				}
			}
		}
	}
}

function DSGetParentNodes(thetree,objID){
	var parent_nodes=[];
	var i;
	if ($(objID)){
		this_node=$(objID);
		for (i=0;i<50;i++){
			this_node=this_node.parentNode;
			if (this_node.id==thetree)
				break;
			else
				parent_nodes[parent_nodes.length]=this_node
		}
	}
	return parent_nodes;
}

function DSGetChildNodes(objID){
	var child_nodes=[];
	var i;
	if ($(objID)){
		this_node=$(objID);
		for (i=0; i<this_node.childNodes.length; i++){
			child_nodes[child_nodes.length]=this_node.childNodes[i];
		}
	}
	return child_nodes;
}

function DSTree_Opener(optionlist){
	var i=0;
	treename='';
	treeid='';
	objID='';
	dispatchevent=0;
	treeitemid='';
	DSOptionList(optionlist);
	if(treeid=='')
		treeid='DSTree_'+treename;
	objID=treeid+'_'+treeitemid+'_link';
	// alert('Obj:'+objID+'TreID:'+treeid);
	if($(objID)) {
		theul=$(objID).up('ul',0);
		if($(theul)) {
			while($(theul).id!=treeid) {
				$(theul).style.display='block';
				theul=$(theul).up('ul',0);
			}
		}
		if($(objID) && dispatchevent==1) {
			// alert(4);
			DSDispatchEvent(objID);
		}
	}
}


/* END DS Tree  */

/* DSSelectRow */
var DSSelectRow_ID='';
var DSSelectRow_lastrow='';
var DSSelectRow_lastrow_color='';
var DSSelectRow_lastrow_class='';

function DSSelectRow(thisrow,thisid) {
	if(DSSelectRow_lastrow!='') {
		DSSelectRow_lastrow.className=DSSelectRow_lastrow_class;
	}
	DSSelectRow_ID=thisid;
	DSSelectRow_lastrow=thisrow;
	DSSelectRow_lastrow_class=thisrow.className;	
	thisrow.className='dslist_selected';
}

/* END DSSelectRow */

// ******************************
// * START GUI Tree/TabBar/Accordion 
// ******************************

function DSTree(e,name,element,optionlist) {
	onclickevent='display';
	reloadtype='display';
	showcontent=1;
	dstreeitemdepth=0;
	expand=1;
	IsLoaded=0;
	dispatchTabBar=1;
	cmd='';
	xhr=0;
	var QueryString='';
	var ActiveCommandBarElement='';
	DSOptionList(optionlist);
		
	// Start ALL
	if(cmd!='')
		IsLoaded=top.DSFindLoader_Loaded(element,this.window);
	if($(element) && $(element).innerHTML.length==0)
		IsLoaded=-1;
	if(cmd!='' && $(element) && $(element).innerHTML.length==0 && IsLoaded<=0)
		onclickevent='load';
	// alert('Name:'+name+' Element:'+element+' IsLoaded:'+IsLoaded+' onclickevent:'+onclickevent);
	if((IsLoaded<=0 && onclickevent=='load') || (IsLoaded>=0 && reloadtype=='reload') || (cmd!= '' && e.ctrlKey && $(element)) || (cmd!= '' && e.metaKey && $(element))) {
		e.cancelBubble = true;
		if (e.stopPropagation) {
			e.preventDefault();			
			e.stopPropagation();
		}
		// 2008-06-30 [AP]
		if (element!=cmd)
			QueryString='&DSElement='+element;
		// 2008-06-16 [AP]
		if ($(name).readAttribute('commandbarelement')!='')
			QueryString+='&DSCommandBarElement='+$(name).readAttribute('commandbarelement');
		
		
		if ($(name).readAttribute('commandbarelement')!='') {
			ActiveCommandBarElement=$($(name).readAttribute('commandbarelement')).readAttribute('active');
			if (ActiveCommandBarElement!='' && ActiveCommandBarElement!=null && $(ActiveCommandBarElement))		
				$(ActiveCommandBarElement).style.display='none';
		}
		
		dsloader(dsxpath+'dynasite.cfm?'+cmd+'&DSRefresh=1'+QueryString,'dsloader',element,'xhr:'+xhr);
	}
	else if ($(name).readAttribute('commandbarelement')!='' && expand==0){
		// 2008-06-19 [AP] GUI Element	
		DSDistributor('element:'+element+',guielement:'+$(name).readAttribute('commandbarelement')+',display:1,type:DisplayGuiPlace');
	}

	// End All
	/*	// if(Event.element(e).readAttribute('expander')==1)
	if(Event.element(e).tagName=='IMG' || $(id).up(0).tagName=='A') {
		var expanderem=Event.element(e).up(0);
		innercode=$(expanderem).innerHTML;
		if(innercode.indexOf("maxi") != -1 ) {
			$(expanderem).innerHTML=top.DSTree_Expander_Opened;
		}
		else if (expand==1) {
			$(expanderem).innerHTML=top.DSTree_Expander_Closed;
		}		
		
	}*/
	if($(name+'_'+id+'_arrow')) {
		innercode=$(name+'_'+id+'_arrow').innerHTML;
		if(innercode.indexOf("maxi") != -1 ) {
			$(name+'_'+id+'_arrow').innerHTML=top.DSTree_Expander_Opened;
		}
		else if (expand==1 && innercode.indexOf("mini") != -1 ) {
			$(name+'_'+id+'_arrow').innerHTML=top.DSTree_Expander_Closed;
		}	
	}
	// expand function
	if(expand==1 && $(name+'_'+id+'_list')) {
		if(innercode.indexOf("<img") != -1) {
			DSStyle(name+'_'+id+'_list','effect:1,displayshowhide:1,dsnavname:'+name+element+',writingmode:'+name+'_'+element+'_arrow');
		}
		else {
			DSStyle(name+'_'+id+'_list','effect:1,displayshowhide:1,dsnavname:'+name+element);
		}
	}
	if(showcontent==1) {
		DSStyle(element,'display:1,dsnavname:'+name+'_Content');
		DSStyle(element+'_context','display:1,dsnavname:'+name+'_context');
		
		if($(name+'_'+id+'_list')) {
			$(name+'_'+id+'_list').style.display='block';
		}
		if($(name+'_'+id+'_arrow') && innercode.indexOf("<img") != -1)
			$(name+'_'+id+'_arrow').style.writingMode='tb-rl';
		// alert(name+'_'+id,'classname:'+style+',dsnavname:'+name);
		if($(name).readAttribute('active')!='')
			var activeobject=name+'_'+$(name).readAttribute('active');
		else
			var activeobject=name+'_'+element;
		$(activeobject+'_link').removeClassName('dstree_explorer_active');
		$(name+'_'+id+'_link').addClassName('dstree_explorer_active');
	$(name).writeAttribute('active',id);

	}
	// TabBar
	var tabbaroption=$(name).readAttribute('tabbar');
	if(DSJS.Len(tabbaroption)) {
		var tabBar=DSJS.ListGetAt(tabbaroption,1,',');
		var tabBar_Element=DSJS.ListGetAt(tabbaroption,2,',');
		var tabBar_Style=DSJS.ListGetAt(tabbaroption,3,',');
		if(dispatchTabBar==1) {
			if($(tabBar_Element)) {
				$('aDSTabBar_'+tabBar_Element+'_'+tabBar_Element).setAttribute('tree',element);
				if($(tabBar_Element).style.display=='none'){
					DSTabBar(e,tabBar_Element,tabBar_Element,'style:'+tabBar_Style+',position:1,dispatchTabBar:1');
				}
			}
		}
	}
	// if(this.window.name=='dsmanager') {
	//	if(this.window.name=='dsmanager' && element=='calendar_calendar_calendar_view_'+DSUID)
	//		$('ds_calendar_month_small_'+DSUID).style.display='block';
	//	else
	//		$('ds_calendar_month_small_'+DSUID).style.display='none';
	// }
	DSTree_Opener('treeid:'+name+',treeitemid:'+element);
	DSPopUpResize();
}

function DSTabBar(e,name,element,optionlist) {
	// 2006-10-25 [AP] New, Option Position & Recordcount, wird für die DSTabBar aquacenter benötigt
	onclickevent='display'; // 2008-11-13 [AP] Variable von onlick in onclickevent geändert. der variablen name onclick funktioniert nicht unter Safari
	reloadtype='display';
	cmd='';
	IsLoaded=0;
	position='';
	commandbar='';
	recordcount='';
	dispatchTabBar=0; // 2008-01-30 [AP] Wird von der DSTree Funktion ausgelöst
	xhr=0;
	var QueryString='';
	var ActiveElement='';
	var GuiElement=element;
	var CommandBarElement='';
	var AssignedCommandbar='';
	DSOptionList(optionlist);
	
	ParentNavigator=$('DSTabBar_'+name).readAttribute('parentnavigator');
	CommandBarElement=$('DSTabBar_'+name).readAttribute('commandbarelement');	
	
	// Start ALL
	if($('ankerDSTabBar_'+name+'_'+element)) {
		if($('ankerDSTabBar_'+name+'_'+element).readAttribute('display')) {
			if($('ankerDSTabBar_'+name+'_'+element).readAttribute('display')=='autodisplay')
				$('aDSTabBar_'+name+'_'+element).style.display='block';
				
		}
	}
	if(cmd!='')
		IsLoaded=top.DSFindLoader_Loaded(element,this.window);
	if($(element).innerHTML.length==0)
		IsLoaded=-1;
	if(cmd!='' && $(element) && $(element).innerHTML.length==0 && IsLoaded<=0)
		onclickevent='load';
	// alert(Name:'+name+' Element:'+element+' IsLoaded:'+IsLoaded+' onclickevent:'+onclickevent);
	
	if((IsLoaded<=0 && onclickevent=='load') || (IsLoaded>=0 && reloadtype=='reload') || (cmd!= '' && e.ctrlKey && $(element))){
		e.cancelBubble=true;
		if (e.stopPropagation) e.stopPropagation();
		
		//2008-06-18 [AP]
		if (CommandBarElement!='') {
			if ($(CommandBarElement) && $($(CommandBarElement).readAttribute('active')))
				$($(CommandBarElement).readAttribute('active')).style.display='none';
			
			QueryString='&DSCommandBarElement='+CommandBarElement;
			
			ActiveElement=top.DSGUIObject_Active['DSTabBar_'+name];
			$('a'+ActiveElement).setAttribute('assignedcommandbar',$(CommandBarElement).readAttribute('active'));
			
			if(ParentNavigator!='')			
				$('aDSTabBar_'+ParentNavigator).setAttribute('assignedcommandbar',element+'_commandbar');		
		}
		dsloader(dsxpath+'dynasite.cfm?'+cmd+QueryString,'dsloader',element,'xhr:'+xhr);
	}
	// 2008-01-30 [AP] Wenn die commandbar ausserhalb vom command div sitzt muss diese ein und ausgeblendet werden
	else if (dispatchTabBar==0 && $(element).style.display=='none') {	
		
		AssignedCommandbar=$('aDSTabBar_'+name+'_'+element).readAttribute('assignedcommandbar');
		//if (DSCAID==2260)
		//	alert('AssignedCommandbar:'+AssignedCommandbar+'\nelement:'+element+'\name:'+name)
		
		if (typeof DSExplorer.GUIPlace.CommandBar=='object') {
			DSExplorer.GUIPlace.CommandBar.Element.each(function(s) { 
				if (s==element){
					AssignedCommandbar=null;
					$break;
				}
			}); 
		}					

		if (AssignedCommandbar!=null) {
			if (AssignedCommandbar!='none_commandbar' && $(AssignedCommandbar)){
				GuiElement=$(AssignedCommandbar).readAttribute('classelement');
				AssignedCommandbar='';
			}
			else
				AssignedCommandbar=',assignedcommandbar:'+DSJS.ReplaceNoCase(AssignedCommandbar,'_commandbar','','All');
		}
		else
			AssignedCommandbar='';
		if($('aDSTabBar_'+name+'_'+element).readAttribute('tree'))
			GuiElement=$('aDSTabBar_'+name+'_'+element).readAttribute('tree');		
		
		if ($('DSTabBar_'+name).readAttribute('commandbarelement') && $('DSTabBar_'+name).readAttribute('commandbarelement')!=null) {		
			dontdoit=0;
			if (typeof DSExplorer.GUIPlace.CommandBar=='object') {
				DSExplorer.GUIPlace.CommandBar.Element.each(function(s) { 
					if (s==GuiElement){
						dontdoit=1;
						$break;
					}
				}); 
			}					
			if (dontdoit==0) {
				activeelement=top.DSGUIObject_Active['DSTabBar_'+name];
				$('a'+activeelement).setAttribute('assignedcommandbar',$($('DSTabBar_'+name).readAttribute('commandbarelement')).readAttribute('active'));	
			}
			
		}
		// alert('element:'+GuiElement+',guielement:'+CommandBarElement+AssignedCommandbar+',display:1,type:DisplayGuiPlace');
		DSDistributor('element:'+GuiElement+',guielement:'+CommandBarElement+AssignedCommandbar+',display:1,type:DisplayGuiPlace');
		
		if(ParentNavigator!='')
			$('aDSTabBar_'+ParentNavigator).setAttribute('assignedcommandbar',$(CommandBarElement).readAttribute('active'));		
		
	}
	// End All
	DSStyle(element,'display:1,dsnavname:'+name);
	DSStyle(element+'_context','display:1,dsnavname:'+name+'_context');	
	DSStyle('DSTabBar_'+name+'_'+element,'classname:dstabbar_'+style+',recordcount:'+recordcount+',position:'+position+',dsnavname:DSTabBar_'+name);
	DSPopUpResize();
}




function DSAccordion(e,thiselement,element,cmd,optionlist) {
	onclickevent='display';
	reloadtype='display';
	boxelement='';
	effect=1;	
	palette=0;
	xhr=0;
	air=0;
	// style='classic';
	DSOptionList(optionlist,'=');
	// Start ALL
	if(cmd!='')
		IsLoaded=top.DSFindLoader_Loaded(element,this.window);
	if($(element).innerHTML.length==0)
		IsLoaded=-1;
	if(cmd!='' && $(element) && $(element).innerHTML.length==0 && IsLoaded<=0)
		onclickevent='load';
	// alert('CMD:'+cmd+' Name:'+name+' Element:'+element+' IsLoaded:'+IsLoaded+' onclickevent:'+onclickevent);
	if((IsLoaded<0 && onclickevent=='load') || (IsLoaded>=0 && reloadtype=='reload' && $(element).style.display=='none') || (cmd!= '' && e.ctrlKey && $(element))){
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
		dsloader(dsxpath+'dynasite.cfm?'+cmd,'dsloader',element,'xhr:'+xhr);
	}
	// End ALL
	statusindicatorcode_element='writingmode:dsacc_'+element+'_arrow';
	if(style=='plusminus' || style =='plusminusaqua')
		statusindicatorcode_element='displayswitch:'+element+'_plusminus_';
	// 2007-02-01 [AP] New
	if(boxelement!='') {
		parentelement=DSFindParnetNodeByName(thiselement,boxelement);
		if(parentelement.style.borderRightWidth=='0px') 
        	borderwidth=2;
		else
			borderwidth=0;
		parentelement.style.borderRightWidth=borderwidth+'px';
		parentelement.style.borderBottomWidth=borderwidth+'px';
		parentelement.style.borderLeftWidth=borderwidth+'px';
	}
	if(group!='') {
		if(top['DSGUIObject_Active']['DSAccordion_'+group]==null)
			top['DSGUIObject_Active']['DSAccordion_'+group]=element;
		lastelement=top['DSGUIObject_Active']['DSAccordion_'+group];
		statusindicatorcode_lastelement='writingmode:dsacc_'+lastelement+'_arrow';
		if(style=='plusminus' || style =='plusminusaqua')
			statusindicatorcode_lastelement='displayswitch:'+lastelement+'_plusminus_';
		top['DSGUIObject_Active']['DSAccordion_'+group]=element;
		// alert('element: '+element+' lastelement: '+lastelement+' lastdisplay: '+$(lastelement).getStyle('display'));
		if(lastelement!=element && $(lastelement).getStyle('display')=='block')
			DSStyle(lastelement,'guitype:DSAccordion,style:'+style+',effect:'+effect+',palette:'+palette+',dsnavname:DSAccordion_'+group+',displayshowhide,'+statusindicatorcode_lastelement);
		DSStyle(element,'guitype:DSAccordion,style:'+style+',effect:'+effect+',palette:'+palette+',dsnavname:DSAccordion_'+group+',displayshowhide,'+statusindicatorcode_element);
	}
	else if(IsLoaded<=0 || reloadtype!='reload') {
		DSStyle(element,'guitype:DSAccordion,style:'+style+',air:'+air+',effect:'+effect+',palette:'+palette+',dsnavname:DSAccordion_'+element+',displayshowhide,resize:0,'+statusindicatorcode_element);
		// DSStyle(element,'guitype:DSAccordion,style:'+style+',dsnavname:DSAccordion_'+element+',resize:0,'+statusindicatorcode_element);
		// new Effect.Appear(element);
	}
}


function DSSortNavigation(thiscmd,sortorderelement,label,optionlist) {
	sort_window=DSLoader_getWindowObject(thiscmd);
	
	if (top['DSSortingNavigator_'+thiscmd]==null)
		top['DSSortingNavigator_'+thiscmd]=new Array();
	
	DSSortingNavigator=top['DSSortingNavigator_'+thiscmd];
	
	//if (DSCAID==2260)
	//	alert('nav: DSSortingNavigator_'+sortorderelement)
	
	if (sort_window.$(sortorderelement)!=null) {
		seperater='>';
		sortorder=0;
		lastelement='';
		DSOptionList(optionlist);
		DSSortingNavigator[sortorder]=label;
		seperater='<span class="dshead_sortorder_seperater">'+seperater+'</span>';
		if (sort_window.$(sortorderelement).innerHTML!=null) {
			sort_window.$(sortorderelement).innerHTML='';
			for(i=0;i<DSJS.ArrayLen(DSSortingNavigator);i++) {
				//alert(DSSortingNavigator[i]);
				if (i==0)
					lastelement=DSSortingNavigator[i];
				else
					sort_window.$(sortorderelement).innerHTML+=DSSortingNavigator[i]+seperater;
			}
			sort_window.$(sortorderelement).innerHTML+=lastelement;
		}
	}
}

// 2007-08-10 [AP]
function DSMultipleSort(e,theElement,element) {	
	if(e.ctrlKey || e.metaKey){
		DSSorting=new Array();
		LastElement='';
		ElementArray1=$(theElement).previousSiblings();
		ElementArray2=$(theElement).nextSiblings();
		// Join both Arrays
		ElementArray=ElementArray1.concat(ElementArray2); 	
		for(i=0;i<DSJS.ArrayLen(ElementArray);i++) {			
			if (DSJS.ListFindNoCase(ElementArray[i].className,'dshead_active',' ')) {
				if (ElementArray[i].readAttribute('sortorder')==0)
					LastElement=ElementArray[i].readAttribute('sortby')+'|'+ElementArray[i].readAttribute('sortdirection');
				else
					DSSorting[ElementArray[i].readAttribute('sortorder')]=ElementArray[i].readAttribute('sortby')+'|'+ElementArray[i].readAttribute('sortdirection');
			}
		}		
		if (LastElement!='')
			 DSSorting.unshift(LastElement);

		//DSJS.ArrayAppend(DSSorting,LastElement);
		// Deletes empty Array entries		
		DSSorting=DSSorting.compact();
		DSSorting=DSJS.ArrayToList(DSSorting,'@')+'@';	
		//alert(LastElement+'\n '+DSSorting);
		if ($(element)){
			$(element).setAttribute('multiplesorting',DSSorting);	
			//alert(element);
		}
		
		//if (DSSorting!='')
		//	top.DSLoader_URLAdd='&dssorting='+DSSorting;
	}
	else if ($(element)){
		$(element).setAttribute('multiplesorting','');		
		//alert('ms: DSSortingNavigator_'+element)
		if (top['DSSortingNavigator_'+element]!=null)
			delete top['DSSortingNavigator_'+element];
	}
	//top.DSLoader_URLAdd='';
}




function DSStyle(element,optionlist) {
	//Needed for Scriptaculous [TR] 07.08.07	
	dsnavname='';
	dsresize=1;
	palette=0;
	effect=0;
	air=0;	
	DSOptionList(optionlist);

	if(dsnavname!='')
		activeelement=top['DSGUIObject_Active'][dsnavname];
	 // alert('GUIName:'+dsnavname+' ElementIN:'+element+' Activeelement:'+activeelement);
	for (i=0; i<function_list.length; i++) {
		this_function=function_list[i].split(":")
		if (this_function[0]=='height')
			$(element).style.height=this_function[1];
		else if (this_function[0]=='classname'){
			if(this_function[1]=='dssystemmenu') {
				$(activeelement).className=this_function[1]+'_inactive';			
				$('a'+activeelement).className=this_function[1]+'_inactive';
				$(element).className=this_function[1]+'_active';			
				$('a'+element).className=this_function[1]+'_active';
			}
			else if(this_function[1]=='dstree_explorerXXXNOTMOREINUSE' || this_function[1]=='dstree_explorer_subXXXNOTMOREINUSE') {
				if(activeelement!=null && $(activeelement+'_link')!=null) {
					$(activeelement+'_listitem').className=this_function[1]+'_inactive';			
					$(activeelement+'_link').className=this_function[1]+'_inactive';
				}
				$(element+'_link').className=this_function[1]+'_active';
			}
			else if(this_function[1]=='dstabbar_narrow' || this_function[1]=='dstabbar_custom') {
				if($('anker'+activeelement)) {
					$('anker'+activeelement).className='';			
				}
				$('anker'+element).className='active';
				if (this_function[1]=='dstabbar_custom')
					$('anker'+element).className+=' DSTabBarCustomClass';
			}
			else if(this_function[1]=='dstabbar_straight') {
				if($('a'+activeelement)) {
					$('a'+activeelement).removeClassName('dstabbar_straighta');
				}
				$('a'+element).addClassName('dstabbar_straighta');
			}
			else {
				if($('a'+activeelement))
					$('a'+activeelement).className=this_function[1];
				if($('a'+element))					
					$('a'+element).className=this_function[1]+'a';
				if(this_function[1]=='dstabbar_aquacenter') {
					if (position==1) {
				 		$(element).previousSibling.className='dstabbar_aquacenter_spacer_left_active';
						$(dsnavname+'_spacer_right').className='dstabbar_aquacenter_spacer_right';
					}
					else if (position==recordcount) {
						$('a'+element).style.border='0px';
						$(element).nextSibling.className='dstabbar_aquacenter_spacer_right_active';
						$(dsnavname+'_spacer_left').className='dstabbar_aquacenter_spacer_left';
					}
					else {
						$(dsnavname+'_spacer_left').className='dstabbar_aquacenter_spacer_left';
						$(dsnavname+'_spacer_right').className='dstabbar_aquacenter_spacer_right';						
					}
				}
			}
		}
	
		else if (this_function[0]=='visibility'){
			$(activeelement).style.visibility="hidden";
			$(element).style.visibility="visible";
		}
		else if (this_function[0]=='writingmode' && $(this_function[1])) {
				innercode=$(this_function[1]).innerHTML;
				if(innercode.indexOf("foldeXXXXr") != -1 ) {
					if(innercode.indexOf("maxi") != -1 )
						$(this_function[1]).innerHTML=top.DSTree_Expander_Opened;
					else
						$(this_function[1]).innerHTML=top.DSTree_Expander_Closed;
				}
				else {
					if ($(this_function[1]).style.writingMode == "lr-tb")
						$(this_function[1]).style.writingMode = "tb-rl";
					else 
						$(this_function[1]).style.writingMode = "lr-tb";
				}
		}
		else if (this_function[0]=='display' ){
			if($(activeelement)) {
				// new Effect.Fade(activeelement);
				$(activeelement).style.display="none";
			}
			if($(element)) {
				//new Effect.Appear(element);
				$(element).style.display="block";
			}
		}
		else if (this_function[0]=='displayswitch') {
			if($(this_function[1]+'0').style.display=='inline') {
				$(this_function[1]+'0').style.display='none';
				$(this_function[1]+'1').style.display='inline';
			}
			else {
				$(this_function[1]+'1').style.display='none';
				$(this_function[1]+'0').style.display='inline';
			}
		}
		else if (this_function[0]=='hide')
			$(this_function[1]).style.visibility="hidden";
		else if (this_function[0]=='show')
			$(this_function[1]).style.visibility="visible";
		else if (this_function[0]=='displayhide')
			$(activeelement).style.display='none';
		else if (this_function[0]=='displayshow')
			$(element).style.display='block';
		else if (this_function[0]=='displayshowhide' && $(element)) {
			if($(element).getStyle('display')=="block") {
				//new Effect.Fade(element);
				if(effect==1){
					if(palette==1)
						new Effect.BlindUp(element,{duration:0.5,afterUpdate:DSPopupHelper,afterFinish:DSPaletteStyle});
					else if(palette==2)
						new Effect.BlindUp(element,{duration:0.5,afterUpdate:DSPopupHelper,afterFinish:paletteupdate});
					else{
						if(air==1)
							new Effect.BlindUp(element,{duration:0.5});
						else
							new Effect.BlindUp(element,{duration:0.5,afterUpdate:DSPopupHelper,afterFinish:DSPopupHelper});
					}
				}
				else{
					$(element).style.display="none";
					if(palette==1)
						DSPaletteStyle();
					else if(palette==2)
						paletteupdate();
				}
			}
			else {
				//new Effect.Appear(element);	
				if(effect==1){
					if(palette==1)
						new Effect.BlindDown(element,{duration:0.5,afterUpdate:DSPopupHelper,afterFinish:DSPaletteStyle});
					else if(palette==2)
						new Effect.BlindDown(element,{duration:0.5,afterUpdate:DSPopupHelper,afterFinish:paletteupdate});
					else{
						if(air==1)
							new Effect.BlindDown(element,{duration:0.5});
						else
							new Effect.BlindDown(element,{duration:0.5,afterUpdate:DSPopupHelper,afterFinish:DSPopupHelper});
					}
				}
				else{
					$(element).style.display="block";
					if(palette==1)
						DSPaletteStyle();
					else if(palette==2)
						paletteupdate();
				}
			}
		}
	}
	//alert('top.DSGUIObject_Active.'+dsnavname+'=element');
	if(dsnavname!='')
		top['DSGUIObject_Active'][dsnavname]=element;
	if(dsresize==1)
		DSPopUpResize();
}
function DSPopupHelper(){
	DSPopUpResize();
}

// ***************************
// * END TabBar/Accordion    *
// ***************************

// Sortable

var DSSortable = Class.create();

DSSortable.prototype = {
	initialize: function (options) {
		// Set Options
		this.setOptions(options);
		// Get sortable elements by classname
		if(this.options.portal=='dssubbody')
			var sortables = $(this.options.portal).select('.'+this.options.column);
		else
			var sortables = $(this.options.portal).select('.'+this.options.column).concat($(this.options.portal+'_context').select('.'+this.options.column));
		// Bind sortable function to each element in sotables variable
		sortables.each(function (sortable) {
			var that=this;
			Sortable.create(sortable, {
				containment: sortables,
				constraint: false,
				tag: this.options.tag,
				//only: this.options.block,
				elements:sortable.childElements().findAll(function(s) { return s.hasClassName(that.options.block)==true && s.hasClassName(that.options.block+'_nodrag')==false;}),
				dropOnEmpty: true,
				ghosting: this.options.ghosting,
				handle: this.options.handle,
				hoverclass: this.options.hoverclass,
				/* onChange: function (block) {	}.bind(this),*/
				onUpdate: function (container) {
					// poststring = Sortable.serialize(container);
					// alert(poststring);
					if (!this.options.saveurl)
						return;
					if (container.id == this.options.blocklist)
						return;
					var url = this.options.saveurl;
					var postBodyContent='';
					var blocks = $(container.id).select('.'+this.options.block);
					if(this.options.accordion==true){
						for(blockitem=0; blockitem<blocks.length;v++)						{
							commacode='';
							if(blockitem!=blocks.length-1)
								commacode=',';
							if(blocks[blockitem].getElementsByClassName('nix')[0].getStyle('display')=='block')
								styledisplay='block';
							else
								styledisplay='none';							
							postBodyContent+=blocks[blockitem].id+':'+styledisplay+commacode;
						}
					}
					else{
						if(this.options.portal=='dssubbody')
							postBodyContent += container.id+'='+blocks.pluck('id').join(',');
						else{
							var counter=1;
							sortables.each(function (sortable) {
								if(counter==1)		
									postBodyContent+='columnvalue='+sortable.id+'='+$(sortable.id).select('.'+that.options.block).pluck('id').join(',');
								else
									postBodyContent+='|'+sortable.id+'='+$(sortable.id).select('.'+that.options.block).pluck('id').join(',');
								counter+=1;
							});
						}
					}
					postBodyContent = '' + postBodyContent;					
					//alert(postBodyContent);
					new Ajax.Updater(this.options.portal+'_widgetsets',url, {method: 'post', postBody: postBodyContent});
				}.bind(this)
			});
		}.bind(this));
		// Get draggable elements by classname
		var blocks = $(this.options.portal).select('.'+this.options.block);
		// Bind block function to each element in blocks variable
		blocks.each(
			function (block) {
				if($(block).hasClassName(this.options.block+'_nodrag')==false){
					var content = Element.childrenWithClassName(block, this.options.content, true);
					var toggle = Element.childrenWithClassName(block, this.options.toggle, true);
					for (i=0;i<toggle.length;i++){
						Event.observe(toggle[i], 'click',function (e) { Effect.toggle(content[i], 'Slide'); },false);
					}
				}
			}.bind(this)
		);
		// Click-Event for displaying widget-list box -> onclickevent call displayBlockList Function
		if(this.options.blocklistlink!='')
			Event.observe(this.options.blocklistlink,'click',this.displayBlockList.bindAsEventListener(this),false);

		// Dragging for widget-list box
		if(this.options.blocklist!='' && this.options.blocklistdragging==1)
			new Draggable(this.options.blocklist, {handle: this.options.blocklisthandle});
	},
	
	displayBlockList: function (e) {
		Effect.toggle(this.options.blocklist,'blind');
		Event.stop(e);
	},

 	setOptions: function (options) {
		this.options = options;
		Object.extend(this.options, options || {});
	},
	// Append blocks to assigned containers
	applySettings: function (settings) {
		that=this;
		for (var container in settings) {
			$(container).select('.'+this.options.block).each(function (block) {
				$(that.options.blocklist).appendChild($(block));
			});
			settings[container].each(function (block) {
				$(container).appendChild($(block));
			});
		}
	}
}
// End Sortable



function dsformwait(wait,form,delay_msec){
	if(isNaN(delay_msec)==false) {
		window.setTimeout("DSStyle(\'"+form+"\','dsnavname:DSFormWait,displayshowhide:1');DSStyle(\'"+wait+"\','dsnavname:DSFormWait,displayshowhide:1');DSPopUpResize()",delay_msec);
	}
	else {
		DSStyle(wait,'dsnavname:DSFormWait,displayshowhide:1');
		DSStyle(form,'dsnavname:DSFormWait,displayshowhide:1')
		DSPopUpResize();
	}
}

// 2005-04-12 [AP]
function ds_dom_table_cellcontent(table){
	counter=counter+1;
	cellcontent_1 = '<input type="text" class="ds_text" name="dsipfilter_'+counter+'" id="dsipfilter_'+counter+'" value="" maxlength="15" />';
	cellcontent_2 = '<div style="width:180px" id="dsipfilterdelete_'+counter+'" onclick="ds_dom_table_deleterow(event);">['+DSLang('delete')+']</div>';
	ds_dom_table_insertrow(table,2);
	DSPopUpResize();
}

function ds_dom_table_insertrow(table,cells) {
	tbl = $(table);
	row = tbl.insertRow(-1);
	listclass='dslist2';
	if ($(table).rows.length/2==parseInt($(table).rows.length/2))
		listclass='dslist1';
	row.className=listclass;				
	for (repeater=1;repeater<cells+1;repeater++) {	
		td = row.insertCell(-1);
		if (typeof eval('cellcontent_'+repeater)=='object') {
			td.appendChild(eval('cellcontent_'+repeater));
		}
		else {
			td.innerHTML=eval('cellcontent_'+repeater);
		}
	}
}

function ds_dom_table_deleterow(e) {
	var searchfortable=ns6? e.target : event.srcElement;
	while(searchfortable.tagName!="TABLE") {
		if(searchfortable.tagName=="TR")
			rowindex=searchfortable.rowIndex;
		searchfortable=ns6? searchfortable.parentNode : searchfortable.parentElement;
	}
	searchfortable.deleteRow(rowindex);
}

function dsresizetextarea(element,smallheight,largeheight) {
	if($('resize_'+element).innerHTML=='[++]') {
		$(element).style.height=largeheight+'px';
		$('resize_'+element).innerHTML='[--]';
		$('dsacc_dseditor_'+element+'_option').innerHTML=$('DSEditorCall_'+element).innerHTML;
		if(tinyMCE.get(element)!=null)
			$(element+"_ifr").style.height=largeheight+'px';
	}
	else {
		$(element).style.height=smallheight+'px';
		$('resize_'+element).innerHTML='[++]';
		$('dsacc_dseditor_'+element+'_option').innerHTML=$('DSEditorCall_'+element).innerHTML;
		if(tinyMCE.get(element)!=null)
			$(element+"_ifr").style.height=smallheight+'px';
	}
	DSPopUpResize();
}

// ***************************
// * START DsPopUP           *
// ***************************
function dspopup_zindex(callerem) {
	if(callerem=='dspopup1'){
		if($('dspopup3').style.zIndex>$('dspopup2').style.zIndex*1)
			current=eval($('dspopup3').style.zIndex*1);
		else
			current=eval($('dspopup2').style.zIndex*1);		
	}
	else if(callerem=='dspopup2'){
		if($('dspopup1').style.zIndex>$('dspopup3').style.zIndex*1)
			current=eval($('dspopup1').style.zIndex*1);
		else
			current=eval($('dspopup3').style.zIndex*1);		
	}
	else if(callerem=='dspopup3'){
		if($('dspopup1').style.zIndex>$('dspopup2').style.zIndex*1)
			current=eval($('dspopup1').style.zIndex*1);
		else
			current=eval($('dspopup2').style.zIndex*1);		
	}
	else
		return;
	$(callerem).style.zIndex=eval(current+'*1+1');
}

// Popup Actions
function dspopup(command,callerem,receiver,receiverem,displayfirstem,actionurl) {
	this_function=command.split("|");
	if (this_function[0]=='display') {
		if(this_function[1]=='dspopup1_body' || this_function[1]=='dspopup2_body' || this_function[1]=='dspopup3_body') {
			display="none";
			if ($('popupcontent').style.display=="none")
				display="block";
			$('popupcontent').style.display=display;
			if($('dspopupresize'))
				$('dspopupresize').style.display=display;
			DSPopUpResize();
		}
	}
	if (this_function[0]=='close' || this_function[0]=='saveclose') {
		$(this_function[1]).style.display="none";
		// loadiframe('dscmd=document_document_document_unlock');
	}
}



function DSButton_Cancel(urlstring,optionlist) {
	cancelalert=0;
	DSOptionList(optionlist);
	if(cancelalert==1){
		cancelquestion=confirm(DSLang('alertclosewindow'));
		if(cancelquestion==false)
			return;
	}
	if(urlstring!=''){
		if(window.name=='MAIN_loader') {
			dsloader(urlstring,'dsloader');
			top.dsexplorer_action_height=0;
			top.DSSetFrames() ;
		}
		if(window.name=='dsmanager_loader') {
			dsloader(urlstring,'dsloader');
			top.dsmanager_action_height=0;
			top.DSSetFrames() ;
		}
	
		else {		
			target=DSLeft(window.name,8);
			dsloader(urlstring,'dsloader');
			parent.dspopup('close|'+target);
		
		}
	}
	else{
		target=DSLeft(window.name,8);		
		parent.dspopup('close|'+target);
	}
}


// DSPopUpResize('dspopup1','height:*,width:)
function DSPopUpResize(target,optionlist) {
	if($('dsformwaitcode')) {
		if($('dsformwaitcode').style.display=='block')
			return false;
	}
	if(target==null)
		target=window.name;

	if(target!='ds') {
// Wird nicht mehr benötig da es in dscommand gesetzt wird [TR] 02.08.07
//		if($('dspopupbody')!=null)
//			$('dspopupbody').className=window.name.split("_")[0];
		resize=0;
		width=0;
		height='*';
		DSOptionList(optionlist);
		if(resize!=0 && parent.dsloader1!=null)
			parent.dsloader1.resizeTo(this_function[1].split("|")[0],this_function[1].split("|")[1]);
		if(height!=0 && $("dspopupbody")) {
			if(target=='dspopup0')
				heightadd=0;
			if((window.name=='dspopup1_loader' || window.name=='dspopup2_loader' || window.name=='dspopup3_loader') && parent.$(target)!=null && eval('parent.'+window.name+'.document').getElementById("dspopupbody")!=null ) {
				parent.$(window.name).style.height=eval($("dspopupbody").offsetHeight+'*1')+'px';
				parent.$(window.name).height = eval($("dspopupbody").offsetHeight+'*1')+'px';
				temptarget=target.slice(0,8);
				parent.$(temptarget).style.height = eval($("dspopupbody").offsetHeight+'*1')+'px';
				//$('popupcontent').style.height = eval($("dspopupbody").offsetHeight+'*1')+'px';
			}
		}
		if(width!=0 && parent.$(target)!=null) {
			if (isNaN(width))
				width=width;
			else 
				width=width+'px';
			parent.$(target).style.width=width;
			parent.$(target+'_body').style.width=width;
			// parent.$(target+'_footer').style.width=width;
			// parent.$(target+'_title').style.width=this_function[1]-2;
			// parent.$(target+'_body').style.width=this_function[1];
			// parent.$(target+'_footer').style.width=this_function[1];
		}
	}
	if(Dialog!=null && Dialog.container && Dialog.visible()){
		Dialog.shadowUnder();
		if(parent.$(window.name) && parent.$(window.name).getHeight()<Dialog.container.cumulativeOffset()[1]+Dialog.container.getHeight()+5){
			parent.$(window.name).style.height=Dialog.container.cumulativeOffset()[1]+Dialog.container.getHeight()+5+"px"
			parent.$(window.name).height=Dialog.container.cumulativeOffset()[1]+Dialog.container.getHeight()+5+"px"
			temptarget=target.slice(0,8);
			parent.$(temptarget).style.height=Dialog.container.cumulativeOffset()[1]+Dialog.container.getHeight()+5+"px"
		}
	}
}

// ***************************
// * End DSPopUp             *
// ***************************

// ***************************
// * Start DragDrop          *
// ***************************


var dsdragapproved=false;
var dsdrag_z,dsdrag_x,dsdrag_y;
document.onmouseup=new Function("dsdragapproved=false");

function dsdrag(e,dragelement) {
	thedragelement=dragelement;
	dspopup_zindex(dragelement);
	dsdrag_z=$(dragelement);
	dsdrag_body=$(dragelement+'_body');
	dsdragapproved=true;
	if(dragelement=='dspopup2')
		startoffset=65;
	else if(dragelement=='dspopup3')
		startoffset=75;		
	else
		startoffset=50;
	if(dragelement=='dspopup1' || dragelement=='dspopup2' || dragelement=='dspopup3')
		dsdrag_body.style.display='none';
	temp1=parseInt(dsdrag_z.style.left+startoffset);
	temp2=parseInt(dsdrag_z.style.top+startoffset);
	dsdrag_x=ns6? e.clientX : event.clientX;
	dsdrag_y=ns6? e.clientY : event.clientY;
	document.onmousemove=dsdrag_move;
	return false;
}

function dsdrag_move(e) {
	if (dsdragapproved) {
		dsdrag_z.style.left=ns6? temp1+e.clientX-dsdrag_x+'px' : temp1+event.clientX-dsdrag_x+'px';
		// if(ie && parseInt(eventtop) > 20)
			dsdrag_z.style.top=ns6? temp2+e.clientY-dsdrag_y+'px' :  temp2+event.clientY-dsdrag_y+'px';
		eventtop=ns6? e.clientY :  event.clientY;
		if(ie && parseInt(eventtop) < 20 && (thedragelement=='dsm' || thedragelement=='dspopup1' || thedragelement=='dspopup2' || thedragelement=='dspopup3')) {
			document.onselectstart=new Function ("return false");
			dsdrag_z.style.top=ns6? e.clientY-dsdrag_y+15+'px' :  temp2+event.clientY-dsdrag_y+15+'px';
			dsdrag_body.style.display='block';
			// if(ie)
			// 	dsdrag_z.fireEvent('onmouseup');
			dsdragapproved=false;
			// document.onselectstart=new Function ("return true");
		}
		else
			return false;	
	}
}



//*****************
//* NewDSDragging *
//*****************
// Global object to hold drag information.

var dragObj = new Object();
dragObj.zIndex = 0;


function dsdragstart(event,id,popup,el,option) {
  var el;
  var x, y;
  palette=0;
	if(option!=null) {
		DSOptionList(option);
	}
  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if(id){
	if(popup){
		dragObj.elNode = parent.$(id);
		parent.dspopup_zindex(id);
		//DSsetDocumentLock(true,dragObj.elNode);
	}
	else
		dragObj.elNode = $(id);
  }
  else {
    if (ie)
      dragObj.elNode = window.event.srcElement;
    else
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }
  // Get cursor position with respect to the page.
    x = event.screenX;
    y = event.screenY;
  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);
  dragObj.mouseDownWidth = parseInt(dragObj.elNode.style.width);
  dragObj.mouseDownHeight = parseInt(dragObj.elNode.style.height);  

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Update element's z-index.

//  dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.

	functionstopcode=dsdragstop;
	if(palette==1)
		functionstopcode=function (e) { dsdragstop(event,1);}
		
  if (ie) {
    parent.document.attachEvent("onmousemove", dsdraggo);
    parent.document.attachEvent("onmouseup",   functionstopcode);
    document.attachEvent("onmousemove", dsdraggo);
    document.attachEvent("onmouseup",   functionstopcode);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  else{
    parent.document.addEventListener("mousemove", dsdraggo,   true);
    parent.document.addEventListener("mouseup",   functionstopcode, true);
    document.addEventListener("mousemove", dsdraggo,   true);
    document.addEventListener("mouseup",   functionstopcode, true);
    event.preventDefault();
  }
}

function dsdraggo(event) {

  var x, y, top, left;

  // Get cursor position with respect to the page.

   x = event.screenX;
   y = event.screenY;

  // Move drag element by the same amount the cursor has moved.
  top=dragObj.elStartTop+y-dragObj.cursorStartY;
  top=top < 0 ? 0 : top;
  
  left=dragObj.elStartLeft+x-dragObj.cursorStartX;
  left=left < 0 ? 0 : left;

  dragObj.elNode.style.left = left + "px";
  dragObj.elNode.style.top  = top + "px";

  if (ie) {
	if(window.event==null){
		parent.window.event.cancelBubble = true;
		parent.window.event.returnValue = false;
	}
	else{
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
  }
  else
    event.preventDefault();
}

function dsdragstop(event,palette) {
	if(palette!=null && palette==1)
		paletteupdate();
	
  // Stop capturing mousemove and mouseup events.
  if (ie) {
    parent.document.detachEvent("onmousemove", dsdraggo);
    parent.document.detachEvent("onmouseup",   functionstopcode);
    document.detachEvent("onmousemove", dsdraggo);
    document.detachEvent("onmouseup",   functionstopcode);
  }
  else {
    parent.document.removeEventListener("mousemove",dsdraggo,true);
    parent.document.removeEventListener("mouseup",functionstopcode,true);
    document.removeEventListener("mousemove",dsdraggo,true);
    document.removeEventListener("mouseup",functionstopcode,true);
  }
  //DSsetDocumentLock(false,dragObj.elNode);
}

function paletteupdate(){
	new Ajax.Request(DSAdminURL+'/dynasite.cfm?dscmd=system_palette_palette_position&left='+$('dspalette').getStyle('left')+'&top='+$('dspalette').getStyle('top')+'&open='+$('dspalette').getStyle('display')+'&minimize='+$('dspalette_content').getStyle('display'), {method: 'get'});	
}

function dsresizestart(event, id, ownobject) {

  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id){
    dragObj.elNode = parent.$(id);
	parent.dspopup_zindex(id);
	dragObj.ownobject=ownobject;
  }
  else {
    if (ie)
      dragObj.elNode = window.event.srcElement;
    else (browser.isNS)
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

    x = event.clientX;

    y = event.clientY;


  // Save starting positions of cursor and element.
  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left,10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,10);
  dragObj.mouseDownWidth = parseInt(dragObj.elNode.style.width);
  dragObj.mouseDownHeight = parseInt(dragObj.elNode.style.height);   
  dragObj.Iframe=parent.$(id+'_loader');  

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Update element's z-index.

//  dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.

  if (ie) {
    document.attachEvent("onmousemove", dsresizego);
    document.attachEvent("onmouseup", dsresizestop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  else {
    parent.document.addEventListener("mousemove",dsresizego2,true);
    parent.document.addEventListener("mouseup",dsresizestop,true);
    document.addEventListener("mousemove",dsresizego,true);
    document.addEventListener("mouseup",dsresizestop,true);

    event.preventDefault();
  }
}

function dsresizego(event) {
	width = dragObj.mouseDownWidth + (event.clientX - dragObj.cursorStartX);
	height = dragObj.mouseDownHeight + (event.clientY - dragObj.cursorStartY);

	width = width < 606 ? 606 : width;
	height = height < 100 ? 100 : height;


	dragObj.Iframe.style.width = (width) + 'px';
	dragObj.Iframe.style.height = (height) + 'px';
	dragObj.Iframe.width = width;
	dragObj.Iframe.height = height;
	dragObj.elNode.style.width = width + 'px';
	dragObj.elNode.style.height = height + 'px';
	//$('dspopupbody').style.width = (width-2) + 'px';
	//$('dspopupbody').style.height = height + 'px';
	$('popupcontent').style.width = (width-6) + 'px';
	$('popupcontent').style.height = (height-46) + 'px';
	DSsetDocumentLock(true,dragObj.ownobject);
//	this.headElement.style.width = width + 'px';
//	this.statusElement.style.width = width + 'px';

  if (ie) {
	window.event.cancelBubble = true;
	window.event.returnValue = false;
  }
  else
    event.preventDefault();
}

function dsresizego2(event) {
	width = dragObj.mouseDownWidth + (event.clientX - dragObj.cursorStartX - dragObj.elStartLeft);
	height = dragObj.mouseDownHeight + (event.clientY - dragObj.cursorStartY - dragObj.elStartTop );

	width = width < 606 ? 606 : width;
	height = height < 100 ? 100 : height;


	dragObj.Iframe.style.width = (width) + 'px';
	dragObj.Iframe.style.height = (height) + 'px';
	dragObj.Iframe.width = width;
	dragObj.Iframe.height = height;
	dragObj.elNode.style.width = width + 'px';
	dragObj.elNode.style.height = height + 'px';
//	$('dspopupbody').style.width = (width-2) + 'px';
//	$('dspopupbody').style.height = height + 'px';
	$('popupcontent').style.width = (width-2) + 'px';
	$('popupcontent').style.height = (height-46) + 'px';
	DSsetDocumentLock(true,dragObj.ownobject);	
//	this.headElement.style.width = width + 'px';
//	this.statusElement.style.width = width + 'px';

  if (ie) {
	window.event.cancelBubble = true;
	window.event.returnValue = false;
  }
  else
    event.preventDefault();
}

function dsresizestop(event) {

  // Stop capturing mousemove and mouseup events.

  if (ie) {
    document.detachEvent("onmousemove",dsresizego);
    document.detachEvent("onmouseup",dsresizestop);
  }
  else {
    parent.document.removeEventListener("mousemove",dsresizego2,true);
    parent.document.removeEventListener("mouseup",dsresizestop,true);	  
    document.removeEventListener("mousemove",dsresizego,true);
    document.removeEventListener("mouseup",dsresizestop,true);
  }
  	DSsetDocumentLock(false,dragObj.ownobject);
}


function DSsetDocumentLock (state,object) {
	var elm = $('mcWindowEventBlocker');

	if (state) {
		if (elm == null) {
			elm = document.createElement("div");

			elm.id = "mcWindowEventBlocker";
			elm.style.position = "absolute";
			elm.style.left = "0";
			elm.style.top = "0";

			document.body.appendChild(elm);
		}
		elm.style.display = "none";

		var width = document.body.clientWidth;
		var height = document.body.clientHeight-20;

		elm.style.width = width;
		elm.style.height = height;
		elm.innerHTML = '<img src="' + DSAdminURL + '/dot.gif" width="' + width + '" height="' + height + '" />';
		elm.style.zIndex = object.style.zIndex-1;
		elm.style.display = "block";
	} else if (elm != null) {
		elm.parentNode.removeChild(elm);
	}
};



// ***************************
// * END DragDrop            *
// ***************************

// ***************************
// * START dsfx_object       *
// ***************************
// 2005-04-21 [AP] In der project/_overview.cfm werden bis zu 7 Instances bengigt.
var dsfxlastobject_1='';
var dsfxlastobject_2='';
var dsfxlastobject_3='';
var dsfxlastobject_4='';
var dsfxlastobject_5=''; 

function dsfx_object(newobject,lastobject,functions,instance){
	if(newobject!='' && lastobject!='') {	
		if(instance==null)
			dsfxlastobject=dsfxlastobject_1;
		else	
			dsfxlastobject=this['dsfxlastobject_'+instance];
		if (dsfxlastobject=='')
			dsfxlastobject=lastobject;
	}
	function_list= functions.split(",");
	for (i=0; i<function_list.length; i++){
		this_function=function_list[i].split("=")
		if (this_function[0]=='height'){
			$(newobject).style.height=this_function[1];
		}
		else if (this_function[0]=='class'){
			$('a'+dsfxlastobject).className=this_function[1];			
			$('a'+newobject).className=this_function[1]+'a';
		}
		else if (this_function[0]=='visibility'){
			$(dsfxlastobject).style.visibility="hidden";
			$(newobject).style.visibility="visible";
		}
		else if (this_function[0]=='display'){
			$(dsfxlastobject).style.display="none";
			$(newobject).style.display="block";
		}
		else if (this_function[0]=='resize'){
			parent.dsloader1.resizeTo(this_function[1].split("|")[0],this_function[1].split("|")[1]);
		}
		else if (this_function[0]=='hide'){
			$(this_function[1]).style.visibility="hidden";
		}
		else if (this_function[0]=='show'){
			$(this_function[1]).style.visibility="visible";
		}
		else if (this_function[0]=='displayshowhide'){
			if($(newobject).style.display=="block"){
				$(newobject).style.display="none";
			}
			else{
				$(newobject).style.display="block";
				if(newobject!=lastobject)
					$(lastobject).style.display="none";
			}
		}
	}
	if(newobject!='' && lastobject!='') {	
		if(instance==null)		
			dsfxlastobject_1=newobject;
		else if (instance==2)
			dsfxlastobject_2=newobject;
		else if (instance==3)			
			dsfxlastobject_3=newobject;
		else if (instance==4)			
			dsfxlastobject_4=newobject;
		else if (instance==5)			
			dsfxlastobject_5=newobject;
	}
}
// ***************************
// * END dsfx_object         *
// ***************************

// ***************************
// * START Form            *
// ***************************
function dsform_submit_parent(theform) {
	parent.$('dsloaderform').innerHTML=$(theform).innerHTML;
	dsgetloaderid();
	parent.document.dsloaderform.target='dsloader'+dsloaderid;	
	if(actionurl!=null)
		parent.document.dsloaderform.action=actionurl;
	else
		parent.document.dsloaderform.action=$(theform).action;
	parent.document.dsloaderform.submit();
}

/* Replace
function dsform_submit(theform) {
	if(theform==null){
		$('f1').submit();
	}
	else{
		eval('document.'+theform+'.submit()');
	}
}
*/
// 2006-08-29 [AP] added Form-Validation 


function dsform_submit(option) {
	msg='';
	form='f1';
	posttarget='';
	validate=0;
	if(option!=null) {
		form=option.split(":");
		if(form.length!=1) {
			form='f1';
			DSOptionList(option);
		}
	}
	if($(form)){
		if (validate==1 && typeof form_validation=="function") 
			form_validation();
		else if (isNaN(validate)==true)
			eval(validate);	
		if (msg=='' || validate==0) {
			if (posttarget=='dsloader'){
				dsgetloaderid();
				$(form).target='dsloader'+dsloaderid;
			}
			$(form).submit();
		}
		else{
			alert(msg);			
			 if (document.getElementsByName('dsbutton_submit')!=null) {
				 for(i = 0; i < document.getElementsByName('dsbutton_submit').length; i++) {
					 if (document.getElementsByName('dsbutton_submit')[i]!=null)
						 document.getElementsByName('dsbutton_submit')[i].disabled=false;
				   }
			 }
			return false;
		}
	}
}


function dsform_submitversion(versioning) {
	if ($('dsbutton_versioning'))
		$('dsbutton_versioning').value=versioning;	
}


// 2006-03-30 [AP] Wenn ein Form per innerHTML neu gestzt wird mssen vorher alle Formfelder im DOM registriert werden fr den Firefox
function dsform_registerdom(theform) {
	for(i=0; i<eval('document.'+theform+'.elements.length'); i++){
		formfield=eval('document.'+theform+'.elements[i]');
		if (formfield.type=="select-one") {
			for (var k=0; k<formfield.options.length; k++) {
				if (k == formfield.selectedIndex) 
					formfield.options[formfield.selectedIndex].setAttribute("selected","selected");								
			}
		}
		else if (formfield.type=="text")
			formfield.setAttribute("value",formfield.value);	
	}
} 

// 2006-10-31 [AP] Transfered die Search-Form-Einstellungen in das Popup-Fenster, damit die Einstellung für den Reset-Command bestehen bleiben
function DSFormTransfer(elementlist,option) {
	var element=elementlist.split(",");
	var i=0;
	var k=0;
	runtime=1;
	cmd='';	
	if(option!=null){
		DSOptionList(option);
	}
	this_parent=eval('parent');
	if(cmd!=''){
		pos=top.DSFindLoader_Loaded(cmd);
		if (pos>-1)
			this_parent=top.DSLoader_Loaded[pos][0];	
	}
	for (i=0; i<element.length; i++) {
		var element_name=DSJS.ListFirst(element[i],"|");
		var element_id=DSJS.ListLast(element[i],"|");
		if (this_parent.$(element_id) && DSJS.ListFindNoCase('text,hidden,select-one',this_parent.$(element_id).type)) {			
			if (this_parent.$(element_id).type=="select-one")
				$(element_id+runtime).value=this_parent.$(element_id).options[this_parent.$(element_id).selectedIndex].value;
			else
				$(element_id+runtime).value=this_parent.$(element_id).value;
		}
		else if (this_parent.$(element_id) && this_parent.$(element_id).type=='textarea') {
			newTextarea=new Element("textarea", {				
				"name":$(element_id+runtime).name,
				"id":$(element_id+runtime).id	
			});
			if (ie)
				newTextarea.value=this_parent.$(element_id).value;	
			else
				newTextarea.innerHTML=this_parent.$(element_id).innerHTML;	
			$(element_id+runtime).remove();
			$('DSFormTransferContainer'+runtime).insert(newTextarea);			
		}
		else {
			if (this_parent.document.getElementsByName(element_name)!=null) {
				 for(k = 0; k < this_parent.document.getElementsByName(element_name).length; k++) {
					 if (this_parent.document.getElementsByName(element_name)[k].checked==true)
						$(element_name+runtime).value=this_parent.document.getElementsByName(element_name)[k].value;						
				 }
			 }			
		}		
	}
}



function dsmove(formular,feld,was,jump,newsort){
	ok=0;
	df=eval('document.'+formular);
	von=eval('df.'+feld+'.selectedIndex');
	textvon=eval('df.'+feld+'.options[von].text');	
	valuevon=eval('df.'+feld+'.options[von].value');
	l=eval('df.'+feld+'.length');
	if (was=='up' && von > 0 && von-jump>=0){
		if (jump==0)
			nach=0;
		else
			nach=von-jump;
		ok=1;
		for(pos = von; pos>nach; pos--){
			eval('df.'+feld+'.options[pos].text=document.'+formular+'.'+feld+'.options[pos-1].text');
			eval('df.'+feld+'.options[pos].value=document.'+formular+'.'+feld+'.options[pos-1].value')
		}
	}
	else if (was=='down' && von < l-1 && von+jump<l) {
		if (jump==0)
			nach=l-1;
		else
			nach=von+jump;
		ok=1;
		for(pos = von; pos < nach; pos++){
			eval('df.'+feld+'.options[pos].text=document.'+formular+'.'+feld+'.options[pos+1].text');
			eval('df.'+feld+'.options[pos].value=document.'+formular+'.'+feld+'.options[pos+1].value')
		}
	}
	if (ok==1){
		eval('df.'+feld+'.options[nach].text=textvon');
		eval('df.'+feld+'.options[nach].value=valuevon')
		eval('df.'+feld+'.selectedIndex=nach');
		newpos=new Array();;
		for(i = 0; i < l; i++)
			newpos[i]=eval('df.'+feld+'.options[i].value');
		eval('df.'+newsort+'.value=newpos.join(",")');
	}
}

function DSColorPicker(element){
	selected_color=$(element).value.replace('#','');
	Edit=open(dsxpath+"dynasite.cfm?dscmd=system_colorpicker_colorpicker_view&element="+element+"&selected_color="+selected_color,"Colopicker","width=250,height=550,screenX=0,screenY=0,locationbar=no,resizable=no,status=no,dependent=no");
	Edit.focus();
}

function dsform_select_move(this_select){
	select_id=this_select.id.split('_');
	this_value=this_select.value;
	active_value=$('active_'+select_id[2]).value.split(',');
	if (this_value!=''){
		if (select_id[1]=='inactive'){
			if($('active_'+select_id[2]).value=='')
				active_value[0]=this_value;
			else
				active_value[active_value.length]=this_value;			
		}
		else if (select_id[1]=='active'){
			new_value=new Array();
			for(k=0;k<active_value.length;k++){
				if(active_value[k]!=this_value){
					new_value[new_value.length]=active_value[k];
				}
			}
			active_value=new_value;
		}
		$('active_'+select_id[2]).value=active_value;
		dsform_select_move_init(select_id[2]);
	}
}

function dsform_select_move_init(id){
	active_value=$('active_'+id).value.split(',');
	select_active=$('select_active_'+id);
	select_inactive=$('select_inactive_'+id);
	dsform_select_move_option_name=eval('dsform_select_move_option_name_'+id);
	dsform_select_move_option_value=eval('dsform_select_move_option_value_'+id);
	for (i=select_active.length-1;i>=0;i--){
		select_active.options[i]=null;
	}
	for (i=select_inactive.length-1;i>=0;i--){
		select_inactive.options[i]=null;
	}
	for (i=0;i<dsform_select_move_option_value.length;i++){
		this_select=0;
		for(k=0;k<active_value.length;k++){
			if(active_value[k]==dsform_select_move_option_value[i]){
				this_select=1;
				break;
			}
		}
		if(this_select==0){
			select_inactive.options[select_inactive.length]=new Option(dsform_select_move_option_name[i],dsform_select_move_option_value[i],false,true);
		}
	}
	for(k=0;k<active_value.length;k++){
		for (i=0;i<dsform_select_move_option_value.length;i++){		
			if(active_value[k]==dsform_select_move_option_value[i]){
				select_active.options[select_active.length]=new Option(dsform_select_move_option_name[i],dsform_select_move_option_value[i],false,true);
				break;
			}
		}
	}
	select_active.selectedIndex=0;
	select_inactive.selectedIndex=0;
}

// 2005-04-22 [AP] Setzt eine Lists von Felder auf disabled true oder false in _articel.cfm, _site.cfm, _dsincludesettings.cfm, category.cfm
function dschangestatus(element,fieldlist,opposite) {
	if ($(element).options!=null) 
		thisvalue=$(element).options[$(element).selectedIndex].value;
	else
		 thisvalue=$(element).value;
	if (opposite!=null){
		if (thisvalue==0) thisdisabled=1;
		else thisdisabled=0;					
	}
	else {
		if (thisvalue==0){
			thisdisabled=0;
		}
		else { 
			thisdisabled=1;
		}
	}	
	field =fieldlist.split(",");						
	for(i=0; i < field.length; ++i){
		$(field[i]).disabled=thisdisabled;														
	}
}





// ***************************
// * END Form                *
// ***************************

// ****************************************
// * 2006-08-28 [AP] Validation *
// ****************************************

last_element='';
function dsvalidate(element_name,condition,error_msg){	
	condition=condition.split(' ');
	dfe=$(element_name);
	
	write_msg=0;
	if (condition[0]=='len' || condition[0]=='num' || condition[0]=='strg' || condition[0]=='si' ||  condition[0]=='date'){
		if (condition[0]=='len'){
			dfev=DSTrim(dfe.value);			
			dfev=dfev.length
			comparer=condition[2]*1;
		}
		else if (condition[0]=='num'){
			dfev=DSTrim(dfe.value);
			dfev=DSNumChk(dfe.value);
			if (isNaN(dfev)){
					//msg+=element_name+' ist keine Zahl, bitte geben Sie eine gueltige Zahl ein.\n'
					condition[1]="notanumber";
					write_msg=1;
			}
			else{
				dfev=dfev*1;
				if (isNaN(condition[2])){
					comparer=DSNumChk(eval('df.'+condition[2]+'.value'));
					if (isNaN(DSNumChk(comparer))){
						//msg+=condition[2]+' ist keine Zahl, bitte geben Sie eine gueltige Zahl ein.\n'
						condition[1]="notanumber"
						write_msg=1;
					}
					else
						comparer=comparer*1
				}
				else
					comparer=condition[2]*1;
			}
		}
		else if (condition[0]=='strg'){
			dfev=DSTrim(dfe.value.toLowerCase());
			comparer=condition[2].toLowerCase();
		}
		else if (condition[0]=='si'){
			dfev=dfe.options[dfe.selectedIndex].value;			
			//dfev=dfe.selectedIndex			
			comparer=condition[2];
		}
		// check for date , check for datetime  ('start_date','date <= end_date')
		else if (condition[0]=='date'){
			dfev_a=dfe.value.split("-");
			//dfe=eval('df.'+element_name+'_freetext')
			dfev_b=$(condition[2]).value.split("-");
			dfev=new Date(dfev_a[0],dfev_a[1]-1,dfev_a[2],0,0,0);
			dfev=dfev.getTime() / 1000;
			comparer=new Date(dfev_b[0],dfev_b[1]-1,dfev_b[2],0,0,0);
			comparer=comparer.getTime() / 1000;
		}
	
		if (condition[1] == 'eq'){
			if (dfev == comparer) write_msg=1;
		}
		else if (condition[1] == 'neq'){
			if (dfev != comparer) write_msg=1;
		}
		else if (condition[1] == 'gt'){
			if (dfev > comparer) write_msg=1;
		}
		else if (condition[1] == 'gte'){
			if (dfev >= comparer) write_msg=1;
		}
		else if (condition[1] == 'lt'){
			if (dfev < comparer) write_msg=1;

		}
		else if (condition[1] == 'lte'){
			if (dfev <= comparer) write_msg=1;
		}
		else if (condition[1] == 'notanumber'){// this condition is set above if not a numeric value
			write_msg=1;
		}
	}
	else if (condition[0]=='isnum' || condition[0]=='isnumeric'){
		dfev=DSTrim(dfe.value);
		dfev=DSNumChk(dfe.value);
		if (typeof condition[1]=='undefined')// condition[1] required or not required field
			condition[1]=0;
		if (condition[1]==1 && dfev==''){
			write_msg=1;
			dfev=' ';
		}		
		if (write_msg==0 && isNaN(dfev)) {
			write_msg=1;
		}		
	}
	else if (condition[0]=='findany'){
		dfev=dfe.value;
		if (condition.length==1){
			condition=new Array('\'',',','>','<',' ',':',';','(',')','"','*');
			startpos=0;
		}
		else{
			startpos=1;
		}
		for(i=startpos;i<condition.length;i++){
			if(condition[i]=='space')
				condition[i]=' ';
			if (dfev.indexOf(condition[i])>-1){
				if(condition[i]==' ')
					dfev='space';
				else
					dfev=condition[i];
				dfev=dfev.replace("<","&lt;");
				dfev=dfev.replace(">","&gt;");
				write_msg=1;
				break;
			}
		}
	}
	else if (condition[0]=='find'){
		dfev=dfe.value;
		if (dfev.indexOf(condition[1])>-1) write_msg=1;
	}
	else if (condition[0]=='findnocase'){
		dfev=dfe.value;
		dfev=dfev.toUpperCase(dfev);
		comparer=condition[1].toUpperCase();
		if (dfev.indexOf(comparer)>-1) write_msg=1;
	}	
	else if (condition[0]=='notfind'){
		dfev=dfe.value;
		if (dfev.indexOf(condition[1])==-1) write_msg=1;
	}
	else if (condition[0]=='notfindnocase'){
		dfev=dfe.value;
		dfev=dfev.toUpperCase(dfev);
		comparer=condition[1].toUpperCase();		
		if (dfev.indexOf(comparer)==-1) write_msg=1;
	}
	else if (condition[0]=='range'){
		range=condition[1].split('-');
		dfev=DSNumChk(dfe.value)*1;
			if (isNaN(dfev)){
				write_msg=1;
			}
			else if (dfev<range[0] || dfev>range[1]){
				write_msg=1;
			}
	}
	else if (condition[0]=='ishexa'){
		dfev=DSTrim(dfe.value);
		if (dfev!=''){
			write_msg=hex_chk(dfev);
		}
	}
	else if (condition[0]=='email'){
		if(typeof email_errors=='undefined')
			email_errors=new Array(DSLang('alertnoemailaddress'),DSLang('alertnoatsymbol'),DSLang('alertnonameforat'),DSLang('alertatatend'),DSLang('alertmaxoneat'),DSLang('alertnodot'),DSLang('alertdotnotbeginning'),DSLang('alertdotnotend'),DSLang('alertwrongcharacter'),DSLang('alertwrongcharacteratposition'),DSLang('alertmissingdotafterat'),DSLang('alertwrongtopleveldomain'));
		dfev=DSTrim(dfe.value);
		wrong_chr='';
		if(typeof condition[1]=='undefined')// pass condition[1]=1 only if Email is required field
			condition[1]=0;
		
		dfev_list=dfev.split(';');
		for (ee=0;	ee<dfev_list.length; ee++){
			dfev=DSTrim(dfev_list[ee]);
			if (condition[1]==1 || (condition[1]==0 && dfev!='')){
				if(typeof condition[2]=='undefined')
					error=email_chk(dfev);
				else
					error=email_chk(dfev,1);				
				if (error>-1){
					error_msg+=email_errors[error].replace("@@wrong@@",wrong_chr);
					write_msg=1;
				}
			}
		}
	}
	else if (condition[0]=='url'){
		if(typeof url_errors=='undefined'){
			url_errors=new Array(DSLang('alertnourl'),DSLang('alerturlstarthttp'),DSLang('alerurlminlength'),DSLang('alerturlmusthavedot'),DSLang('alerturlwrongcharacter'));
		}
		dfev=DSTrim(dfe.value);
		wrong_chr='';
		if(typeof condition[1]=='undefined')// pass condition[1]=1 only if URL is required field
			condition[1]=0;
		if (condition[1]==1 || (condition[1]==0 && dfev.length >7)){
			error=url_chk(dfev);
			if (error>-1){
				error_msg+='<ul>'+url_errors[error].replace("@@wrong@@",wrong_chr)+'</ul>';
				write_msg=1;
			}
		}
	}
	if (write_msg)
		msg+=error_msg;
	/*if (write_msg){
		error_msg=error_msg.replace("@@dfev@@",dfev);
		msg+='<li>'+error_msg+'</li>';
		dfe.style.borderTop="2px solid #cc0000";
		dfe.style.borderRight="2px solid #cc0000";
		dfe.style.borderBottom="2px solid #ff0a0a";
		dfe.style.borderLeft="2px solid #ff0a0a";
		if (element_tofocus=='')
			element_tofocus=dfe;
	}
	else if (last_element!=dfe.name){// if (dfe.style.borderTopColor != '#cc0000')
		dfe.style.borderTop="2px solid #606060";
		dfe.style.borderRight="1px solid #606060";
		dfe.style.borderBottom="1px solid #606060";
		dfe.style.borderLeft="2px solid #606060";
	} */
	last_element=dfe.name;
}

function hex_chk(hex){
	write_msg=0;
	if (hex.length != 6){
		//Hexadecimal code should be 6 chrs long
		write_msg=1;
	}
	if(write_msg==0){
		for (i=0; i<6; i++){
			if (isNaN(parseInt(hex.substring(i,i+1) , 16))){
				//Hexadecimal code should be 0,1,2,3,4,5,6,7,8,9,A,a,B,b,C,c,D,d,E,e,F,f
				write_msg=1;
				break;
			}
		}
	}
	return 	write_msg;
}

function email_chk(email,extend){
	error=-1;
	email_sub='';
	if(extend!=null && extend==1){
		email_temp=email;
		email_sub=email.split(' ');
		if(email_sub.length > 1){
			email=email_sub[0];
			email_sub=email_temp.slice(email_sub[0].length+1,email_temp.length);
		}
	}
	if (email.length < 6){
		error=0;
	}
	else{
		if(email.indexOf("@")==-1)
			error=1;
		else if(email.indexOf("@")==0)
			error=2;
		else if(email.indexOf("@")==email.length-1)
			error=3;
		else if(email.indexOf("@")!= email.lastIndexOf("@"))
			error=4;
		else if(email.indexOf(".")==-1)
			error=5;
		else if(email.indexOf(".")==0)
			error=6;
		else if(email.indexOf(".")==email.length-1)
			error=7;
		if (error==-1){
			wrongchk=email.split('(');
			wrong=new Array(',','>','<',' ','*',':',';','(',')','"','\'');
			for(i=0;i<wrong.length;i++){
				if (email.indexOf(wrong[i])>-1){
					error=8;
					wrong_chr='"'+wrong[i]+'"';
					break;
				}	
			}
		}
		if (error==-1){
			for(i=0;i<email.length;i++){
				if(email.charCodeAt(i)<=31 || email.charCodeAt(i)>=127){
					error=9;
					wrong_chr=i;
					break;
				}
			}
		}
		if (error==-1){
			tld_chk=email.split("@");
			tld_chk=tld_chk[tld_chk.length-1];
			tld_chk=tld_chk.split(".");
			if (tld_chk.length==1)
				error=10;
			else{
	toplevel_domain=['com','net','edu','arpa','org','gov','museum','biz','info','pro','name','aero','coop','mil','ac','ad','ae','af','ag','ai','al','am','an','ao','aq','ar','as','at','au','aw','az','ba','bb','bd','be','bf','bg','bh','bi','bj','bm','bn','bo','br','bs','bt','bv','bw','by','bz','ca','cc','cd','cf','cg','ch','ci','ck','cl','cm','cn','co','cr','cu','cv','cx','cy','cz','de','dj','dk','dm','do','dz','ec','ee','eg','eh','er','es','et','eu','fi','fj','fk','fm','fo','fr','ga','gd','ge','gf','gg','gh','gi','gl','gm','gn','gp','gq','gr','gs','gt','gu','gw','gy','hk','hm','hn','hr','ht','hu','id','ie','il','im','in','io','iq','ir','is','it','je','jm','jo','jp','ke','kg','kh','ki','km','kn','kp','kr','kw','ky','kz','la','lb','lc','li','lk','lr','ls','lt','lu','lv','ly','ma','mc','md','mg','mh','mk','ml','mm','mn','mo','mp','mq','mr','ms','mt','mu','mv','mw','mx','my','mz','na','nc','ne','nf','ng','ni','nl','no','np','nr','nu','nz','om','pa','pe','pf','pg','ph','pk','pl','pm','pn','pr','ps','pt','pw','py','qa','re','ro','ru','rw','sa','sb','sc','sd','se','sg','sh','si','sj','sk','sl','sm','sn','so','sr','st','sv','sy','sz','tc','td','tf','tg','th','tj','tk','tm','tn','to','tp','tr','tt','tv','tw','tz','ua','ug','uk','um','us','uy','uz','va','vc','ve','vg','vi','vn','vu','wf','ws','ye','yt','yu','za','zm','zr','zw','int','local'];
				tld=tld_chk[tld_chk.length-1].toLowerCase();
				chk_ok=0;
				for (t=0; t<toplevel_domain.length; t++){
					if (tld==toplevel_domain[t]){
						chk_ok=1;
						break;
					}
				}
				if (chk_ok==0){
					error=11;
					wrong_chr='"'+tld+'"';
				}
			}
		}
	}
	if(email_sub.length>1 && error==-1){
		if(email_sub.charAt(email_sub.length-1)!=')' || email_sub.charAt(0)!='(')
			error=8;
	}
	return error;
}

function url_chk(url){
	error=-1;
	if (url.length <12)
		error=0;
	else{
		if (url.indexOf("http://")!=0)
			error=1;
		else if (url.length < 12)
			error=2;
		else if (url.indexOf(".")==-1)
			error=3;
		else {	
			wrong=new Array('>','<',' ','*',';','"','\'');
			for(i=0;i<wrong.length;i++){
				if (url.indexOf(wrong[i])>-1){
					error=4;
					if (wrong[i]==' ')
						wrong_chr='space';
					else
						wrong_chr=wrong[i];
					break;
				}	
			}
		}			
	}
	return error;
}

// Form - Validation 
/*
function dsform_validation(){
	url_cmd=dscommand.split("_");
	
	if (url_cmd[0]=='site' && url_cmd[1]=='export' && url_cmd[2]=='queue'){
		start_date=DSCreateDateTime('start_date','start_time');		
		compare_date=DSCreateDateTime('compare_date','compare_time');
		if (start_date<compare_date)
			msg+='Das Datum muss in der Zukunft liegen';
	}
	
	if (url_cmd[0]=='site' && url_cmd[1]=='export' && url_cmd[2]=='export' && url_cmd[3]!='select'){

	}
	// site_export_export_select
	else if (url_cmd[0]=='site' && url_cmd[1]=='export' && url_cmd[2]=='export' && url_cmd[3]=='select'){
		
		
	}
}
*/

// END Validation

var LACalendarMonth = new Array (DSLang('january'),DSLang('february'),DSLang('march'),DSLang('april'),DSLang('may'),DSLang('june'),DSLang('july'),DSLang('august'),DSLang('september'),DSLang('october'),DSLang('november'),DSLang('december'));
var LACalendarMonthShort = new Array ("Jan","Feb","M&auml;r","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez");

var LACalendarDayNames= new Array(DSLang('sunday'),DSLang('monday'),DSLang('tuesday'),DSLang('wednesday'),DSLang('thursday'),DSLang('friday'),DSLang('saturday'));
var LACalendarDay = new Array (DSLang('SO'),DSLang('MO'),DSLang('TU'),DSLang('WE'),DSLang('TH'),DSLang('FR'),DSLang('SA'));

MonthNames = LACalendarMonth;
DayNames= LACalendarDayNames;
DayNamesShort=LACalendarDay;

WeekStart="m"//s: if week starts on Sunday, m: if week starts on Monday
SS_oneday=1; // Show Saturday and Sunday in one field at month_view ( 1 or 0) only possibile if WeekStart is "m" (Monday)

CalendarWeek=DSLang('calendarweek');

period_option_list='none,wholeday,n-5,n-15,n-30,n-45,h-1,h-2,h-3,h-4,h-5,h-6,h-7,h-8,h-9,h-10,h-11,h-12,h-18,d-1,d-2,d-3,d-4,d-5,d-6,w-1,w-2,w-3,noend';
wholeday=DSLang('wholeday');
noend=LANoEnd=DSLang('noend');
n_var_text=DSLang('minutes');
h_var_text=DSLang('hours');
d_var_text=DSLang('days');
w_var_text=DSLang('weeks');

last_selected_date="";
last_selected_week="";

thisTimeElement="";
ds_new_calendar_hour=-1;
ds_new_calendar_minute=-1;


status_list_de=''+DSLang('Cancelled')+','+DSLang('Notstarted')+','+DSLang('Workinprogress')+','+DSLang('done')+','+DSLang('Waitingforsomeoneelse')+','+DSLang('Pushedback')+''.split(',');	


status_list_en='cancelled,notstarted,started,finished,waitforother,rejected'.split(',');
status_image_list_single='checkbox02.gif,checkbox00.gif,checkbox00.gif,checkbox01.gif,checkbox00.gif,checkbox02.gif'.split(',');
status_image_list_multiple='checkbox12.gif,checkbox10.gif,checkbox10.gif,checkbox11.gif,checkbox10.gif,checkbox12.gif'.split(',');


// 2006-10-05 [AP] Aus der Calendar/_entry.cfm ausgelagert
function dscalendar_entrytype(isevent) {
	entrytypeevent=new Array('Event_Label_DateStart','Event_Label_DateEnd','eventbox','event_alarm_type');
	entrytypetask=new Array('Task_Label_DateStart','Task_Label_DateEnd','task_alarm_type');
	var i=0;
	if(isevent==1) {
		settoblock=entrytypeevent;
		settonone=entrytypetask;
	}
	else{
		settoblock=entrytypetask;
		settonone=entrytypeevent;
	}
	// 2006-10-14 [AP] Müssen die Elemente noch auf Block gesetzt werden ?????
	for(i=0;i<settoblock.length;i++){
		if ($(settoblock[i])!=null)
			$(settoblock[i]).style.display='block';
	}
	for(i=0;i<settonone.length;i++){
		if ($(settonone[i])!=null)
			$(settonone[i]).style.display='none';
	}	
	DSPopUpResize();
}
function recurrence_show(onoff){
	if (onoff==1)
		$("recurrence_div").style.display="block";
	else
		$("recurrence_div").style.display="none"		
	DSPopUpResize();
 }
 function changeRecurrenceType(type){
	if (type==null)
		type=$('recurrence_type').options[$('recurrence_type').selectedIndex].value;
	if (type==0)
		$('recurrence_all').style.display="none";
	else
		$('recurrence_all').style.display="block";
	for(i=1; i<=4; i++){
		if (i==type)
			$('recurrence_'+i).style.display="block";
		else
			$('recurrence_'+i).style.display="none"
	}
	DSPopUpResize();
 }
 
 function entry_chk(caller){
	// 2006-10-22 [AP] Arguement Caller hinzugefügt, wenn ein Task vom Artikel gespeichert wird
	start_date=DSCreateDateTime('start_date','start_time');		
	end_date=DSCreateDateTime('end_date','end_time');
	d_diff=DSDateDiff('d',start_date,end_date);
	msg=''; 
	period=$('period');


	DSCal=eval('top.DSCal_'+$('dscalid').value);
	if (DSCal!=null && $('CalendarCurrDate')!=null){
		//alert(document.getElementById('dscalid').value);
		this_currdate=DSCal.calendar_currentdate;
		//alert(this_currdate.toString())
		thisvar=this_currdate.getFullYear()+'-'+DSInt(this_currdate.getMonth()+1)+'-'+this_currdate.getDate();
		$('CalendarCurrDate').value=thisvar;
	}	
	
	if (caller!='article' && DSTrim($('title').value)=='')
		msg+=DSLang('alertcalsubject');
	if ((end_date.getFullYear()==1901 || end_date.getFullYear()==2500) && end_date.getMonth()==0 && end_date.getDate()==1){
		msg+='';
	}
	else if (period!=null && period.value=='wholeday')
		msg+='';
	else if (start_date >end_date)
		msg+=DSLang('alertstartforenddate');
	
	if ($('recurrence_type').selectedIndex!=0){
		if ($('recurrence_type').selectedIndex==1){ //daily
			if (document.getElementsByName('daily_type')[0].checked){
				day_step=$('day_step').value;
				if (!DSIsNum(day_step)) {
					msg+=DSLang('alertnovalidinterval');
					msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",day_step);
				}
				else{
					day_step=DSInt(day_step);
					if (d_diff >= day_step) {
						msg+=DSLang('alertintervaldailyrepeat');
						msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",day_step);
						msg=DSJS.ReplaceNoCase(msg,"@@replace2@@",d_diff);
					}
				}
			}
			else{
				if (d_diff > 0)
					msg+=DSLang('alertrepeatworkdays');
			}
		}
		else if($('recurrence_type').selectedIndex==2){ // weekly
			if (!DSIsNum($('week_step').value)) {
				msg+=DSLang('alertnotavlidnumber');
				msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",$('week_step').value)
			}
			else{
				wd=document.getElementsByName('weekdays');
				start_date_wd_found=0;
				this_wd=new Array();
				for(i=0; i<wd.length; i++){
					if (wd[i].checked){
						this_wd[this_wd.length]=i
						if (start_date.getDay()==eval(wd[i].value-1))
							start_date_wd_found=1;	
					}
				}
				if (this_wd.length==0)
					msg+=DSLang('alertrepeatweekdays');
				else{
					if (this_wd.length==1)
						chk_days=6;
					else{
						start_diff=this_wd[0]-0;
						end_diff=6-this_wd[this_wd.length-1];
						chk_days=start_diff+end_diff;
						for(i=1; i<this_wd.length; i++){
							this_diff=this_wd[i]-this_wd[i-1]-1;
							if (this_diff<chk_days)
								chk_days=this_diff;
						}
					}
					if (d_diff>=$('week_step').value*7){
						msg+=DSLang('alerttimeperiodinterval');
						msg=DSJS.ReplaceNoCase(msg,"@@replace2@@",eval(DSInt(d_diff/7)+1),"All");
					}
					else if (d_diff >=7 && this_wd.length!=1)
						msg+=DSLang('alertrepeatoneweekday');
					else if (d_diff > chk_days)
						msg+=DSLang('alerttimeperiodrepeatweekday');
					if (start_date_wd_found==0) {
						msg+=DSLang('alertrepeatweeklyacitve');
						msg=DSJS.ReplaceNoCase(msg,"@@replace3@@",DayNames[start_date.getDay()],"All");
					}
					msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",d_diff,"All");
					
					
				}
			}
		}
		else if($('recurrence_type').selectedIndex==3){ // monthly
			if (document.getElementsByName('monthly_type')[0].checked){
				if (!DSIsNum($('month_day').value)) {
					msg+=DSLang('alertnotavlidnumber');
					msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",$('month_day').value);
				}
				else if (!DSIsNum($('month_step').value)){
					msg+=DSLang('alertnotavlidnumber');
					msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",$('month_step').value);
				}
				else{
					rundate=new Date(start_date.getFullYear(),start_date.getMonth(),1,0,0,0);
					rundate=DSDateAdd('m',$('month_step').value,rundate);
					totalDays=DSDaysInMonth(rundate.getFullYear(),rundate.getMonth());
					month_day=$('month_day').value;
					if (month_day>totalDays)
						month_day=totalDays;
					rundate=new Date(rundate.getFullYear(),rundate.getMonth(),month_day,0,0,0);
					if (end_date>=rundate) {
						msg+=DSLang('alertendolderbeginn');
						msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",DSDateTimeFormat('date',end_date),"All");
						msg=DSJS.ReplaceNoCase(msg,"@@replace2@@",DSDateTimeFormat('date',rundate),"All");
					}
				}
			}
			else{
				if (!DSIsNum($('month_selector_step').value)){
					msg+=DSLang('alertnotavlidnumber');
					msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",$('month_selector_step').value)
				}
				else{
					selector_type=$('month_selector_type').value;
					selector=$('month_selector').value-1;
					rundate=new Date(start_date.getFullYear(),start_date.getMonth(),1,0,0,0);
					rundate=DSDateAdd('m',$('month_selector_step').value,rundate);
					totalDays=DSDaysInMonth(rundate.getFullYear(),rundate.getMonth());
					if (selector_type==5){
						rundate=new Date(rundate.getFullYear(),rundate.getMonth(),totalDays,0,0,0);
						for (i=0;i<totalDays;i++){
							if (rundate.getDay()==selector)
								break;
							else
								rundate=DSDateAdd('d',-1,rundate)
						}
					}
					else{
						counter=0;
						for (i=0;i<totalDays;i++){
							if (rundate.getDay()==selector)
								counter++
							if (counter==selector_type)
								break;
							else
								rundate=DSDateAdd('d',1,rundate)
						}
					
					}
					if (end_date>=rundate) {
						msg+=DSLang('alertendolderbeginn');
						msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",DSDateTimeFormat('date',end_date),"All");
						msg=DSJS.ReplaceNoCase(msg,"@@replace2@@",DSDateTimeFormat('date',rundate),"All");
					}
				}
			}
		}
		else if($('recurrence_type').selectedIndex==4){ // yearly
			if (document.getElementsByName('yearly_type')[0].checked){
				if (!DSIsNum($('year_step').value)) {
					msg+=DSLang('alertnotavlidnumber');
					msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",$('year_step').value);
				}
				else if (!DSIsNum($('year_day').value)) {
					msg+=DSLang('alertnotavlidnumber');
					msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",$('year_day').value);
				}
				else{
					this_month=$('year_month').value-1;
					this_year=start_date.getFullYear()*1+$('year_step').value*1;
					rundate=new Date(this_year,this_month,1,0,0,0);
					totalDays=DSDaysInMonth(rundate.getFullYear(),rundate.getMonth());
					year_day=$('year_day').value;
					if (year_day>totalDays)
							year_day=totalDays;
						rundate=new Date(rundate.getFullYear(),rundate.getMonth(),year_day,0,0,0);
					
					if (end_date>=rundate){
						msg+=DSLang('alertendolderbeginn');
						msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",DSDateTimeFormat('date',end_date),"All");
						msg=DSJS.ReplaceNoCase(msg,"@@replace2@@",DSDateTimeFormat('date',rundate),"All");
					}
				}
			}
			else{
				if (!DSIsNum($('year_selector_step').value)) {
					msg+=DSLang('alertnotavlidnumber');
					msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",$('year_selector_step').value);
				}
				else{
					selector_type=$('year_selector_type').value;
					selector=$('year_selector').value-1;
					this_year=start_date.getFullYear()*1+$('year_selector_step').value*1;
					this_month=$('year_selector_month').value*1-1;
					rundate=new Date(this_year,this_month,1,0,0,0);
					totalDays=DSDaysInMonth(rundate.getFullYear(),rundate.getMonth());
					if (selector_type==5){
						rundate=new Date(rundate.getFullYear(),rundate.getMonth(),totalDays,0,0,0);
						for (i=0;i<totalDays;i++){
							if (rundate.getDay()==selector)
								break;
							else
								rundate=DSDateAdd('d',-1,rundate)
						}
					}
					else{
						counter=0;
						for (i=0;i<totalDays;i++){
							if (rundate.getDay()==selector)
								counter++
							if (counter==selector_type)
								break;
							else
								rundate=DSDateAdd('d',1,rundate)
						}
					
					}
					if (end_date>=rundate){
						msg+=DSLang('alertendolderbeginn');
						msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",DSDateTimeFormat('date',end_date),"All");
						msg=DSJS.ReplaceNoCase(msg,"@@replace2@@",DSDateTimeFormat('date',rundate),"All");
					}
				}
			}
		}
	}
	
	if (msg=='') {
		if (caller!=null && caller=='article')
			submitform=1;
		else 
			dsform_submit();
	}
	else{
		alert(msg);
		$('dsbutton_submit').disabled=false;
	}
 }	

// END 2006-10-05 [AP] Aus der Calendar/_entry.cfm ausgelagert


function dsautodate(datename,datevalue,allow_no_date,info){
	var i;
	yearstart='';
	yearend='';
	dateid=datename;
	if (typeof info!='undefined'){
		info_array=info.split(",")
		for (i=0;i<info_array.length;i++){
			eval(info_array[i].replace(":","='")+"'")
		}
	}
	display=DSDateTimeFormat('weekday_date',datevalue);
	if(typeof allow_no_date == "undefined")
		allow_no_date=0
	if (datevalue=='2500-01-01')
		datevalue='1901-01-01';
	if (datevalue=='1901-01-01')
		display=DSLang('nodate');
	
	datevar='<input type="hidden" id="'+datename+'" name="'+datename+'" value="'+datevalue+'" />';
	datevar+='<div id="display_'+datename+'" class="ds_date" onClick="DSCalendarGetValue(event,\''+datename+'\','+allow_no_date+');" yearstart="'+yearstart+'" yearend="'+yearend+'">'+display+'</div>';
	//alert(datevar)
	document.write(datevar);
}

function dsautotime(timename,timevalue,info){
	showMinute=1;
	if (typeof info!='undefined'){
		info_array=info.split(",")
		for (i=0;i<info_array.length;i++){
			eval(info_array[i].replace(":","='")+"'")
		}
	}	
	display=DSDateTimeFormat('time',timevalue)
	datevar='<input type="hidden" id="'+timename+'" name="'+timename+'" value="'+timevalue+'" />';
	datevar+='<div id="display_'+timename+'" class="ds_time" onclick="DSTimeGetValue(event,\''+timename+'\','+showMinute+');" >'+display+'</div>';
	//alert(datevar)
	//datevar='<b>huhu</b>';
	document.writeln(datevar);
}

function dsautodatetime(datetimename,datevalue,allow_no_date,info){
	date_value=datevalue.split(" ");
	this_date_name=datetimename+'_date';
	this_time_name=datetimename+'_time';
	dsautodate(this_date_name,date_value[0],allow_no_date,info);
	dsautotime(this_time_name,date_value[1],info);
	if (date_value[0]=='1901-01-01' || date_value[0]=='2500-01-01'){
		$('display_'+this_time_name).style.display='none';
		$('display_'+this_date_name).innerHTML=DSLang('nodate');
	}
}

function DSCalendarGetValue(e,thiselement,allow_no_date){
	if (ie==true)
		thisDisplayDateElement=e.srcElement;
		
	else
		thisDisplayDateElement=e.target;
	thisDateElement=$(thisDisplayDateElement).previous('input');	
	now=DSCreateDateTime(thisDateElement,'');
	now=DS1901_2500Calibrate(now);
	DSCalendarView(now.getFullYear(),now.getMonth(),now.getDate(),'form',0,allow_no_date);
	DSContextShow(e,'','x_show="middle";y_show="bottom";onmouseout=1;');
}

function DSTimeGetValue(e,thiselement,showMinute){
	thisTimeElement=thiselement;
	ds_new_calendar_hour=-1;
	ds_new_calendar_minute=-1;
	this_time=$(thiselement).value;
	this_time_array=this_time.split(':');
	hour = this_time_array[0];
	minute =this_time_array[1];
	DSTimeView(hour,minute,showMinute);
	DSContextShow(e,'','x_show="right";y_show="bottom";onmouseout=1;');	
}

function DSCalendarNewTime(){
	new_time=ds_new_calendar_hour+':'+ds_new_calendar_minute
	$(thisTimeElement).value=new_time;
	$('display_'+thisTimeElement).innerHTML=new_time;
	
	start_enddate_adjust(thisTimeElement);
	
	DSContextHide();
	if (DSPeriodFunction){
		period_adjust(thisTimeElement)
	}
}

function DSTimeSelect(hour_minute,value){
	if (hour_minute=='hour'){
		$('time_hour_'+ds_new_calendar_hour).className='dscalendar_month_small_day';
		ds_new_calendar_hour=value;
		$('time_hour_'+ds_new_calendar_hour).className='dscalendar_month_small_active';
	}
	else{
		$('time_minute_'+ds_new_calendar_minute).className='dscalendar_month_small_mid';
		ds_new_calendar_minute=value;
		$('time_minute_'+ds_new_calendar_minute).className='dscalendar_month_small_active';
	}
}
function DSTimeView(hour,minute,showMinute){
	if (hour<10 && hour.length<2)
		hour='0'+hour;
	
	ds_new_calendar_hour=hour;
	ds_new_calendar_minute=minute;
	
	html_str='';
	html_str+='<table cellspacing="1" id="dscalendar_small">';
	html_str+='<tr>';
	//html_str+='<tr><td rowspan="2" valign="top" align="right">Hour:</td>';
	for (i=0;i<=23;i++){
		if (i<10)
			ii='0'+i;
		else
			ii=i;
		if(showMinute==1)
			html_str+='<td id="time_hour_'+ii+'" class="dscalendar_month_small_day" onclick="DSTimeSelect(\'hour\',\''+ii+'\');"><a href="javascript: DSBlank();"><strong>'+ii+'</strong></a></td>';
		else
			html_str+='<td id="time_hour_'+ii+'" class="dscalendar_month_small_day" onclick="DSTimeSelect(\'hour\',\''+ii+'\');DSCalendarNewTime();"><a href="javascript: DSBlank();"><strong>'+ii+'</strong></a></td>';		
		if (i==11)
			html_str+='</tr><tr>';
	}
	html_str+='</tr>';
	html_str+='<tr><td colspan="12"></td></tr>';
	if(showMinute==1){	
		html_str+='<tr>';
		//html_str+='<tr><td rowspan="6" valign="top" align="right">Minute:</td>';
		for (i=0;i<=55;i=i+5){
			if (i<10)
				ii='0'+i;
			else
				ii=i;
			html_str+='<td id="time_minute_'+ii+'" class="dscalendar_month_small_monthnav_mid" onclick="DSTimeSelect(\'minute\',\''+ii+'\');"><a href="javascript: DSBlank();"><strong>:'+ii+'</strong></a></td>';
		}
		html_str+='</tr>';
		html_str+='<tr><td colspan="12"></td></tr>';
		for (j=0;j<4;j++){
			html_str+='<tr>';
			for (i=1;i<=12;i++){
				ii=(i-1)*4+i+j
				if (ii<10)
					ii='0'+ii;
				html_str+='<td id="time_minute_'+ii+'" class="dscalendar_month_small_monthnav_mid" onclick="DSTimeSelect(\'minute\',\''+ii+'\');"><a href="javascript: DSBlank();">:'+ii+'</a></td>';
			}
			html_str+='</tr>';
		}
	}
	now = new Date();
	hour = now.getHours();
	minute = now.getMinutes();
	html_str+='<tr height="30">';
	if(showMinute==1){
		html_str+='<td colspan="4" class="ds_calendar_footer" valign="middle"><a style="width:auto;" href="javascript: DSTimeView('+hour+','+minute+')">'+DSLang('now')+'</a></td>';
		html_str+='<td colspan="4" class="ds_calendar_footer" align="center" valign="middle"><a style="width:auto;" href="javascript: DSCalendarNewTime()">'+DSLang('apply')+'</a></td>';
		html_str+='<td colspan="4" class="ds_calendar_footer" align="right" valign="middle"><a style="width:auto;" href="javascript:DSContextHide();">'+DSLang('close')+'</a></td>';		
	}
	else{
		html_str+='<td colspan="6" class="ds_calendar_footer" valign="middle"><a style="width:auto;" href="javascript: DSTimeView('+hour+',\'00\',0);DSCalendarNewTime();">'+DSLang('now')+'</a></td>';	
		html_str+='<td colspan="6" class="ds_calendar_footer" align="right" valign="middle"><a style="width:auto;" href="javascript:DSContextHide();">'+DSLang('close')+'</a></td>';		
	}
	html_str+='</tr>';
	html_str+='</table>';
	DSContextInnerHTML(html_str,1);
	DSTimeSelect('hour',ds_new_calendar_hour);
	if(showMinute==1){	
		DSTimeSelect('minute',ds_new_calendar_minute);
	}
}

//START  NEUE ZEITFUNKTION

function DSTimeWriteBack(this_element,value){
	$(this_element).innerHTML=value;
}

function DSTimeSelect_new(this_element,hour_min){
	time_value=$(this_element).innerHTML;
	html_str='';
	if (hour_min=='hour'){
		html_str+='<select class="ds_calendar_month_small_select" style="font-size:0.9em" size="5" id="help_hourlist" name="help_hourlist" onchange="DSTimeWriteBack(\''+this_element+'\',this.value)">';
		for (i=0;i<=23;i++){0
			i_show=''+i;
			if (i<10)
				i_show='0'+i_show;
			html_str+='<option value="'+i+'"'+((i==time_value)?' selected':'')+'>'+i_show+'</option>';
		}
		html_str+='</select>';
	}
	else{
		html_str+='<select class="ds_calendar_month_small_select" style="font-size:0.9em" size="5" id="help_minutelist" name="help_hourlist" onchange="DSTimeWriteBack(\''+this_element+'\',this.value)">';
		for (i=0;i<=59;i++){
			i_show=''+i;
			if (i<10)
				i_show='0'+i_show;
			if (i/5==DSInt(i/5))
				style=' style="background-color:#dddddd;"';
			else
				style='';
			html_str+='<option value="'+i+'"'+style+((i==time_value)?' selected':'')+'>'+i_show+'</option>';
		}
		html_str+='</select>';
	}
	$(this_element).innerHTML=html_str;
}

function DSTimeView_new(hour,minute){
	var i;
	html_str='';
	html_str+='<table cellspacing="1" id="dscalendar_small">';
	html_str+='<tr height="80">';
	html_str+='<td align="right" valign="middle" id="help_selected_hour" style="font-size:1.8em; cursor:pointer; width:80;" onclick="DSTimeSelect(this.id,\'hour\')">'+hour+'</td>';
	html_str+='<td align="center" valign="middle" style="font-size:1.8em" width="20"><strong>:</strong></td>';
	html_str+='<td align="left" valign="middle" id="help_selected_minute" style="font-size:1.8em; cursor:pointer; width:80;" onclick="DSTimeSelect(this.id,\'minute\')">'+minute+'</td>';
	html_str+='</tr>';
	
	html_str+='<tr>';
	html_str+='<td class="ds_calendar_footer" colspan="3" align="center"><a style="width:auto;" href="javascript: DSCalendarNewTime(document.getElementById(help_hourlist).value,document.getElementById(help_minutelist).value)">Ok</a></td>';
	html_str+='</tr>';
	
	html_str+='<tr>';
	html_str+='<td class="ds_calendar_footer" align="center"><a style="width:auto;" href="javascript:DSContextHide();">'+DSLang('close')+'</a></td>';
	html_str+='</tr>';
	html_str+='</table>';
	
	DSContextInnerHTML(html_str,1);
}

//ENDE  NEUE ZEITFUNKTION

// Date Create and Format functions

function DS1901_2500Calibrate(this_date){
	if ((this_date.getFullYear()==1901 || this_date.getFullYear()==2500) && this_date.getMonth()==0 && this_date.getDate()==1){
		this_date=new Date();
	}
	return this_date;
}

function DSCreateDateTime(this_date_element,this_time_element){
	if ($(this_date_element)!=null)
		this_date=$(this_date_element).value;
	else
		this_date='';
		
	if (this_time_element!='' && $(this_time_element)!=null)
		this_time=$(this_time_element).value;
	else
		this_time='';
	now = new Date();
	this_date=this_date.split('-');
	this_time=this_time.split(':');
	if(this_date.length != 3) {
		this_date[0]=now.getFullYear();
		this_date[1]=now.getMonth()+1;
		this_date[2]=now.getDate();
	}
	if(this_time.length != 2) {
		this_time[0]= now.getHours();
		this_time[1]= now.getMinutes();
	}
	if (this_date[1].substr(0,1)=='0')
		this_date[1]=this_date[1].replace(/0/,"");
	if (this_date[2].substr(0,1)=='0')
		this_date[2]=this_date[2].replace(/0/,"");
	if (this_time[0]=='--' || this_time[1]=='--'){
		this_time[0]= now.getHours();
		this_time[1]= now.getMinutes();
	}
	
	this_date[1]=this_date[1]*1-1;
	new_date=new Date(this_date[0],this_date[1],this_date[2],this_time[0],this_time[1],0);
	//alert(new_date);
	return new_date;
	
}

function DSDateTimeFormat(dt,this_value){

	if (typeof this_value=='object'){
		if (dt=='time'){
			this_value=this_value.getHours()+':'+this_value.getMinutes();
		}
		else if(dt=='date' || dt=='weekday_date'){
			this_month=this_value.getMonth()+1;
			this_value=this_value.getFullYear()+'-'+this_month+'-'+this_value.getDate();
		}
	}
	if (dt=='time'){
		this_val=this_value.split(':');
		hour=this_val[0]*1;
		minute=this_val[1]*1;
		if (hour<10)
			hour='0'+hour;
		if (minute<10)
			minute='0'+minute;
		this_value=hour+':'+minute;
	}
	else if(dt=='date' || dt=='weekday_date'){
		this_val=this_value.split('-');
		year=this_val[0]*1;
		month=this_val[1]*1;
		day=this_val[2]*1;
		if (month<10)
			month='0'+month;
		if (day<10)
			day='0'+day;
		this_value=day+'.'+month+'.'+year;
		if (dt=='weekday_date'){
			this_date=new Date(this_val[0],this_val[1]*1-1,this_val[2],0,0,0);
			this_weekday=DayNamesShort[this_date.getDay()];
			this_value=this_weekday+', '+this_value;
		}
	}
	return this_value;
}

function DSTimeFormat(chk_date){
	var hh=chk_date.getHours()*1;
	var mm=chk_date.getMinutes()*1;
	var ss=chk_date.getSeconds()*1;
	var ampm='PM';
	if (hh<12)
		ampm='AM';
	if (hh<10)
		hh='0'+hh;
	if (mm<10)
		mm='0'+mm;
	if (ss<10)
		ss='0'+ss;	
	return hh+':'+mm+' '+ampm
}


// END Date Create and Format functions

// DateADD and Datediff 
function DSDateAdd(datepart,dnum,chk_date){
	var this_date = new Date(chk_date);
	dnum=dnum*1;
	if (datepart=="y" || datepart=="year"){
		this_date.setFullYear(this_date.getFullYear() + dnum);
	}
	else if (datepart=="m" || datepart=="month"){
		this_date.setMonth(this_date.getMonth() + dnum);
	}
	else if (datepart=="d" || datepart=="day"){
		this_date.setDate(this_date.getDate() + dnum);
	}
	else if (datepart=="h" || datepart=="hour"){
		this_date.setHours(this_date.getHours() + dnum);
	}
	else if (datepart=="n" || datepart=="minute"){
		this_date.setMinutes(this_date.getMinutes() + dnum);
	}
	else if (datepart=="s" || datepart=="sec"){
		this_date.setSeconds(this_date.getSeconds() + dnum);
	}
	return this_date;
}

function DSDateDiff(datepart,chk_date1,chk_date2){
	date1 = new Date(chk_date1);
	date2 = new Date(chk_date2);
	
	TimezoneOffset=(date1.getTimezoneOffset()-date2.getTimezoneOffset())*60*1000;
	millisec_diff = date2.valueOf() - date1.valueOf()+TimezoneOffset;
	
	year_diff  = date2.getUTCFullYear() - date1.getUTCFullYear();
	month_diff = date2.getUTCMonth() - date1.getUTCMonth() + (year_diff!=0 ? year_diff*12 : 0);
	
	sec_diff = parseInt(millisec_diff/1000);
	min_diff = parseInt(sec_diff/60);
	hour_diff = parseInt(min_diff/60);
	day_diff  = parseInt(hour_diff/24);

	if (datepart=="y" || datepart=="year")
		return year_diff;
	else if (datepart=="m" || datepart=="month")
		return month_diff;
	else if (datepart=="d" || datepart=="day")
		return day_diff;
	else if (datepart=="h" || datepart=="hour")
		return hour_diff;
	else if (datepart=="n" || datepart=="minute")
		return min_diff;
	else if (datepart=="s" || datepart=="sec")
		return sec_diff;
	else
		return false;
}


// other usefull Date Functions

function DSIsLeapYear(year){
	ly=0;
	if ((year % 4) == 0 && (year < 1582 || (year % 100) > 0 || (year % 400) == 0))
		ly=1;
	return ly;
}
function DSDaysInMonth(year,month) {
	days_in_month=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	if (month==1 && DSIsLeapYear(year)){		
		days_in_month[1]=29;
	}		
	return days_in_month[month];
}
function DSDaysTotal(year,month,day){
	if ( month < 3 ){
		month = month + 12;
		year = year - 1;
	}
	month++;
	total_days = year * 365 + parseInt(year/4) - parseInt( year/100 ) + parseInt( year/400 ) + parseInt((month*306)/10) + day-426;
	return total_days;
}
function DSDayOfYear(year,month,day){
	total_days=day;
	for (mmi=0; mmi<month; mmi++) {
		total_days+=DSDaysInMonth(year,mmi);
	}
	return total_days;
}
function DSWeekOfYear(year,month,day){
	dayofyear=DSDayOfYear(year,month,day);
	td_0101=(DSDaysTotal(year,1,1) + 4) % 7;
	td_3112=(DSDaysTotal(year,12,31) + 4 ) % 7;
	td_0101_old=(DSDaysTotal(year-1,1,1) + 4 ) % 7;
	td_3112_old=(DSDaysTotal(year-1,12,31) + 4 ) % 7;
	d=td_0101-1;
	if ( td_0101 < 4 )
		d += 7;
	woy = parseInt((dayofyear+d)/7);
	if (woy==53 && td_3112 < 3)
		woy=1;
	if (woy==0){
		if ( ( td_0101_old == 3 ) || ( td_3112_old == 3 ) )
			woy = 53;
		else
			woy = 52;  
	}
	return woy;
}

// Period Functions
DSPeriodFunction=0;
function DSWritePeriod(){
	DSPeriodFunction=1;
 	option_list=period_option_list.split(',');
	html_str='<select class="ds_select" name="period" id="period" onchange="DSPeriodWriteNewDateTime(\'start_date\')">';
	for (i=0;i<option_list.length;i++){
		if (option_list[i]=="wholeday")
			this_text=wholeday;
		else if (option_list[i]=="none"){
			this_text='- - - - - - -';
		}
		else if (option_list[i]=="noend"){
			this_text=noend;
		}
		else{
			this_value=option_list[i].split('-');
			this_text=this_value[1]+' '+eval(this_value[0]+'_var_text');
		}
		html_str+='<option value="'+option_list[i]+'">'+this_text+'</option>';
	}
	html_str+='</select>';
	document.write(html_str);
}

function DSPeriodWriteNewDateTime(start_end_date){
	period=$('period');
	if (typeof start_end_date=='undefined')
		start_end_date='start_date';
	if (period.value=='none')
		return;
	period.options[0].text='- - - - - - -';
	
	this_val=period.value.split('-');
	datepart=this_val[0];
	dnum=this_val[1];
	if (datepart=='w'){
		datepart='d';
		dnum=dnum*7;
	}
	
	if (period.value=='wholeday'){
		$('display_start_time').style.display='none';
		$('display_end_time').style.display='none';
		$('display_end_date').style.display='none';
	}
	else{
		$('display_start_time').style.display='block';
		$('display_end_time').style.display='block';
		$('display_end_date').style.display='block';
		if (start_end_date=='end_date'){
			change_date='start';
			_time_display='block';
			if (period.value=='noend'){
				
			}
			else{
				enddate=$('end_date').value;
				endtime=$('end_time').value;
				start_date=DSDateAdd(datepart,-dnum,DSCreateDateTime('end_date','end_time'));
				month=start_date.getMonth()+1;
				startdate=start_date.getFullYear()+'-'+month+'-'+start_date.getDate();
				starttime=start_date.getHours()+':'+start_date.getMinutes();
			}
			$('start_date').value=startdate;
			$('display_start_date').innerHTML=DSDateTimeFormat('weekday_date',startdate);
			$('start_time').value=starttime;
			$('display_start_time').innerHTML=DSDateTimeFormat('time',starttime);
			$('display_'+change_date+'_time').style.display=_time_display;
		}
		else{
			change_date='end';
			if (period.value=='noend'){
				_date='2500-01-01';
				_date_show=DSLang('nodate');
				_time='23:59'
				_time_show=DSDateTimeFormat('time',_time)
				_time_display='none'
			}
			else{
				startdate=$('start_date').value;
				starttime=$('start_time').value;
				end_date=DSDateAdd(datepart,dnum,DSCreateDateTime('start_date','start_time'));
				month=end_date.getMonth()+1;
				_date=end_date.getFullYear()+'-'+month+'-'+end_date.getDate();
				_date_show=DSDateTimeFormat('weekday_date',_date);
				_time=end_date.getHours()+':'+end_date.getMinutes();
				_time_show=DSDateTimeFormat('time',_time)
				_time_display='block'
			}
			$(change_date+'_date').value=_date;
			$('display_'+change_date+'_date').innerHTML=_date_show;
			$(change_date+'_time').value=_time;
			$('display_'+change_date+'_time').innerHTML=_time_show;
			$('display_'+change_date+'_time').style.display=_time_display;
		}
	}
	//alert(datepart+'\n'+dnum+'\n'+start_date+'\n'+end_date);
 }
 
function period_chk(){
	//alert($('start_time').value);
	if ($('period')==null)
		return;
		
	var start_date_a=DSCreateDateTime('start_date','start_time');
	var end_date_a=DSCreateDateTime('end_date','end_time');
	
	var period=$('period');
	period.options[0].text='- - - - - - -';
	if ((end_date_a.getFullYear()==1901 || end_date_a.getFullYear()==2500) && end_date_a.getMonth()==0 && end_date_a.getDate()==1){
		period.options[period.length-1].selected=true;
		return; 
	}
	
	w_diff=0;
	d_diff=DSDateDiff('d',start_date_a,end_date_a)
	h_diff=DSDateDiff('h',start_date_a,end_date_a)
	n_diff=DSDateDiff('n',start_date_a,end_date_a)
	//period_option_list='none,wholeday,n-5,n-15,n-30,n-45,h-1,h-2,h-3,h-4,h-5,h-6,h-7,h-8,h-9,h-10,h-11,h-12,h-18,d-1,d-2,d-3,d-4,d-5,d-6,w-1,w-2,w-3,noend';
	if (d_diff > 6){
		w_diff=DSInt(d_diff/7);
		d_diff=d_diff-w_diff*7;
		h_diff=h_diff-w_diff*7*24;
		n_diff=n_diff-w_diff*7*24*60;
	}
	if (d_diff > 0){
		h_diff=h_diff-d_diff*24;
		n_diff=n_diff-d_diff*24*60;
	}
	if (h_diff > 0)
		n_diff=n_diff-h_diff*60;
	this_type='';
	if (w_diff==0 && d_diff==0 && h_diff==0 && n_diff>0)
		this_type='n';
	else if (w_diff==0 && d_diff==0 && h_diff>0 && n_diff==0)
		this_type='h';
	else if (w_diff==0 && d_diff>0 && h_diff==0 && n_diff==0)
		this_type='d';
	else if (w_diff>0 && d_diff==0 && h_diff==0 && n_diff==0)
		this_type='w';
	else if (h_diff==23 && n_diff==59)
		this_type='wholeday';
	else
		this_type='other';
	
	if (this_type=='other'){
		this_text='';			
		if (w_diff>0 || d_diff>0){
			this_diff=w_diff*7+d_diff*1
			if (this_diff>1)
				this_text+=this_diff+' Tage ';
			else
				this_text+=this_diff+' Tag ';	
		}
		if (h_diff>0)
			this_text+=h_diff+'h ';
		if (n_diff>0)
			this_text+=n_diff+'min ';
		period.options[0].text=this_text;
		period.options[0].selected=true;
	}
	else {
		period.options[0].text='- - - - - - -';
		if (this_type=='wholeday'){
			period.options[1].selected=true;
		}
		else {
			option_list=period_option_list.split(',');
			found_it=0;
			for (i=2;i<option_list.length;i++){
				this_value=option_list[i].split('-');
				if (this_value[0]==this_type && this_value[1]==eval(this_type+'_diff')){
					
					period.options[i].selected=true;
					found_it=i;
					break
				}
			}
			if (found_it==0){
				period.options[0].text=this_text;
				period.options[0].selected=true;
			}
		}
	}	
	//alert(start_date+'\n'+end_date+'\n w_diff:'+w_diff+'\n d_diff:'+d_diff+'\n h_diff:'+h_diff+'\n n_diff:'+n_diff+'\n this_type:'+this_type)
 }
 
 function period_adjust(DateTimeElement){
 	var period=$('period');
	if (period.value=='wholeday')
		return;
	start_end=$(DateTimeElement).name.split('_');
	if (start_end[0]=='start'){
		if (period.value=='none'){
			period_chk();
		}
		else if (period.value!='noend'){
			//if (dslang=='de')
				//period_check=confirm('Soll die eingestellte Dauer auf das Enddatum angewendet werden.');
			//else
				//period_check=confirm('Do you want to apply your setting to the start-period?\n(The end date will change automatically.)');
			period_check=true;
			if (period_check)
				DSPeriodWriteNewDateTime('start_date');
			else
				period_chk();
		}	
	}
	else{
		end_date=DSCreateDateTime('end_date','end_time');
		if ((end_date.getFullYear()==1901 || end_date.getFullYear()==2500) && end_date.getMonth()==0 && end_date.getDate()==1){
			period_chk();
		}
		else if (period.value=='noend' || period.value=='none'){
			period_chk();
		}
		else{		
			period_check=confirm(DSLang('alertapplysettingperiod'));
			if (period_check)
				DSPeriodWriteNewDateTime('end_date');
			else
				period_chk();
		}
	}
 }
  // End Period
  
  
function DSShowMonthList(e,year,month,day,view,dscalid){
	month_before=6;
	this_date=new Date(year,month,1,0,0,0);
	run_date=DSDateAdd('m',-month_before,this_date);
	html_str='';
	for (i=-month_before;i<=month_before;i++){
		this_year=run_date.getFullYear();
		this_month=run_date.getMonth();
		if (this_year==year && this_month==month)
			this_text='<b>'+MonthNames[this_month]+' '+this_year+'</b>';
		else
			this_text=MonthNames[this_month]+' '+this_year;
		if (view=='calendar_to_link')
			html_str+='<a class="dsconmenu" href="javascript: DSContextHide(); top.DSCalendar_Custom(\'month\','+this_year+','+this_month+','+day+','+dscalid+');">'+this_text+'</a>';
		else
			html_str+='<a class="dsconmenu" href="javascript: DSContextHide(); DSCalendarNewDataCHK('+this_year+','+this_month+','+day+',\''+view+'\','+dscalid+');">'+this_text+'</a>';
		run_date=DSDateAdd('m',1,run_date)
	}
	html_str+='<a class="dsconmenu" href="javascript: DSContextHide();"><b>'+DSLang('close')+'</b></a>';
	DSContextShow(e,html_str,'x_show="middle";y_show="middle";onmouseout=1;');
}


function DSMonthTotalDays(year,month){
	firstDay=startdate.getDay();
	lastDay=enddate.getDay();
	if (WeekStart=='s'){
		if (firstDay>0){
			startdate=DSDateAdd('d',-firstDay,startdate)
			totaldays=totaldays+firstDay;
		}
		if (lastDay<6){
			dayadd=6-lastDay;
			enddate=DSDateAdd('d',dayadd,enddate)
			totaldays=totaldays+dayadd;
		}
	}
	else{
		if (firstDay!=1){
			if (firstDay==0)
				dayadd=6;
			else
				dayadd=firstDay-1
			startdate=DSDateAdd('d',-dayadd,startdate);
			totaldays=totaldays+dayadd;
		}
		if (lastDay!=0){
			dayadd=7-lastDay;
			enddate=DSDateAdd('d',dayadd,enddate);
			totaldays=totaldays+dayadd;
		} 
	}
}


function DSCalendarNewDataCHK(year,month,day,view,dscalid,info){
	now = new Date(year,month,day);
	DSCal=eval('top.DSCal_'+dscalid);
	if (view=='form' || (now >= DSCal.range_startdate && now < DSCal.range_enddate)){
		DSCalendarView(year,month,day,view,dscalid,info);
	}
	else{
		month=month*1+1
		currdate=year+'-'+month+'-'+day;
		//alert(view)
		dsloader('dynasite.cfm?dscmd=calendar_calendar_calendar_view&currdate='+currdate+'&dscalid='+dscalid+'&calendar_load='+view,'dsloader');
	}
}

function DSCalendarScroll(datepart,dnum,year,month,day,view,dscalid,info) {
	now = new Date(year,month,day);
	now=DSDateAdd(datepart,dnum,now);
	year = now.getFullYear();
	month = now.getMonth();
	day = now.getDate();
	if (view=='calendar_to_link')
		DSCalendarView(year,month,day,view,dscalid,info);
	else
		DSCalendarNewDataCHK(year,month,day,view,dscalid,info)
}


function start_enddate_adjust(thisDateTimeElement){
	//alert($(thisDateTimeElement).readAttribute('thisname'))
	//start_end=$(thisDateTimeElement).readAttribute('thisname');
	start_end=$(thisDateTimeElement).name.split('_')[0];
	if (start_end=='start' && $('end_date')!=null){
		startdate=DSCreateDateTime('start_date','start_time');
		enddate=DSCreateDateTime('end_date','end_time');
		if (startdate>enddate){
			$('end_date').value=$('start_date').value;
			$('display_end_date').innerHTML=$('display_start_date').innerHTML;
			enddate=DSCreateDateTime('end_date','end_time');
			if (startdate>enddate){
				$('end_time').value=$('start_time').value;
				$('display_end_time').innerHTML=$('display_start_time').innerHTML;
			}
		}		
	}
	
	if (start_end=='end' && $('start_date')!=null){
		startdate=DSCreateDateTime('start_date','start_time');
		enddate=DSCreateDateTime('end_date','end_time');
		if (startdate>enddate){
			$('start_date').value=$('end_date').value;
			$('display_start_date').innerHTML=$('display_end_date').innerHTML;
			startdate=DSCreateDateTime('start_date','start_time');
			if (startdate>enddate){
				$('start_time').value=$('end_time').value;
				$('display_start_time').innerHTML=$('display_end_time').innerHTML;
			}
		}		
	}	
}

function DSCalendarNewDate(year,month,day,view,dscalid){
	if (view=='form'){
		olddate=$(thisDateElement).value;
		month=month*1+1;
		newdate=year+'-'+month+'-'+day;
		$(thisDateElement).value=newdate;
		
		do_period_chk=1; // NK 12.11.06 beim verstellen der startzeit soll keine Fehlermeldung bezüglich der endzeit auftreten,  daher ein verzicht auf periodenprüfung 
		
		if ((year==1901 || year==2500) && month==1 && day==1){
			show_date=DSLang('nodate');
			display_time='none';
		}
		else{
			show_date=DSDateTimeFormat('weekday_date',newdate)
			display_time='block';
		}
		
		if (DSPeriodFunction){
			period=$('period');
			if (period.value=='wholeday'){
				$('display_'+thisDateElement).innerHTML=show_date;
				DSContextHide();
				return;
			}
		}
		$(thisDisplayDateElement).innerHTML=show_date;
		
		start_enddate_adjust(thisDateElement);		
		chk_datetime_name=$(thisDateElement).name.split("_");
		if (chk_datetime_name.length==2){
			chk_time_name='display_'+chk_datetime_name[0]+'_time';
			if ($(chk_time_name)!=null)
				$(chk_time_name).style.display=display_time;
		}
		DSContextHide();
		
		if (DSPeriodFunction && do_period_chk==1){
			period_adjust(thisDateElement)
		}
	}
	else if (view=='calendar_to_link'){
		top.DSCalendar_Custom('day',year,month,day,dscalid);
	}
	else
		DSLoadCalendarView(year,month,day,'day',dscalid);		
	if (typeof DSCalendar_Custom_Validate=="function") 
		DSCalendar_Custom_Validate();
}

function DSCalendar_ContentCHK(view,dscalid){
	DSCal=eval('top.DSCal_'+dscalid);
	if ($('ds_calendar_'+view+'_'+dscalid)!=null){
		this_date=eval('top.DSCalInfo_'+dscalid+'.'+view+'_currdate');
		if (this_date < DSCal.range_startdate && this_date > DSCal.range_enddate)
			this_date=DSCal.calendar_currentdate;
	}
	else{
		this_date=DSCal.calendar_currentdate;
	}
	if (view=='week'){
		this_weekday=this_date.getDay();
		if (WeekStart=='s' && this_weekday!=0){
			this_date=DSDateAdd('d',-this_weekday,this_date);
		}
		else if (WeekStart=='m' && this_weekday!=1){
			if (this_weekday==0)
				this_weekday=6;
			else
				this_weekday--;
			this_date=DSDateAdd('d',-this_weekday,this_date);
		}
	}
	DSCalendarView(this_date.getFullYear(),this_date.getMonth(),this_date.getDate(),view,dscalid);
}


function DSLoadCalendarView(year,month,day,view,dscalid){
	if(typeof DSCalendarTree=='undefined')
		DSCalendarTree='dsmanagertree';
	DSCalInfo=eval('top.DSCalInfo_'+dscalid);
	DSCalInfo.view_to_load=view;
	DSCalInfo.view=view;
	this_date=new Date(year,month,day,0,0,0);
	eval('DSCalInfo.'+view+'_currdate=this_date');
	if ($('DSTree_'+DSCalendarTree+'_calendar_calendar_calendar_view_'+dscalid+'_link')!=null){
		DSDispatchEvent('DSTree_'+DSCalendarTree+'_calendar_calendar_calendar_view_'+dscalid+'_link');
	}
	else{
		DSDispatchEvent('DSTree_'+DSCalendarTree+'_module_calendar_calendar_view_link');
	}
	//DSDispatchEvent('DSTree_dsmanagertree_calendar_calendar_calendar_view_'+dscalid+'_link');
	DSDispatchEvent('aDSTabBar_CalendarNav_'+dscalid+'_ds_calendar_'+view+'_'+dscalid);
}

function DSCalendarView(year,month,day,view,dscalid,info){
	var i=0;
	if (view != 'form' && dscalid>0){
		DSContextHide();
		DSCal=eval('top.DSCal_'+dscalid);
		DSCalInfo=eval('top.DSCalInfo_'+dscalid);
		DSCalInfo.view=view;
		this_help_date=new Date(year,month,day,0,0,0);
		eval('DSCalInfo.'+view+'_currdate=this_help_date');
		allow_edit=0;
		if (DSArrayFind(DSCal.calendar_action,'edit'))
			allow_edit=1;
	}
	if (view != 'week' || view != 'day'){
		days=DSDaysInMonth(year,month)
		startdate=new Date(year,month,1);
		enddate=new Date(year,month,days,23,59,59);
		totaldays=days;
		DSMonthTotalDays(year,month);
	}
	if (view=='month_small' || view=='form' || view=='calendar_to_link'){		
		//alert('DSCalendarView'+year+','+month+','+day);		
		year_value='<strong>'+year+'</strong>';
		if (view=='form'){
			yearstart=$(thisDisplayDateElement).getAttribute('yearstart')
			yearend=$(thisDisplayDateElement).getAttribute('yearend');
			if (!isNaN(yearstart) && !isNaN(yearend) && yearstart!='' && yearend!=''){
				if (year>yearend)
					yearend=year+1;
				if (year<yearstart)
					yearstart=year-1;
				year_value='';
				year_value+='<select class="ds_calendar_month_small_select" size="1" id="help_yearlist" name="help_yearlist"  onChange="DSCalendarView(this.value,document.getElementById(\'help_monthlist\').value,'+day+',\''+view+'\','+dscalid+');">';
				for (i=yearstart;i<=yearend;i++){
					year_value+='<option value="'+i+'"'+((i==year)?' selected':'')+'>'+i+'</option>';
				}
				year_value+='</select>'
			}
		}
		else if (view=='calendar_to_link'){
			year_value='<a href="javascript: top.DSCalendar_Custom(\'year\','+year+','+month+','+day+','+dscalid+');"><strong>'+year+'</strong></a>';
		}
		
		html_str='<table cellspacing="0" id="dscalendar_month_small_yearnav"><tr>';
		html_str+='<td id="dscalendar_month_small_yearnav_left"><a href="javascript:DSCalendarScroll(\'year\',-1,'+year+','+month+','+day+',\''+view+'\','+dscalid+',\''+info+'\');">&laquo;</a></td>';
		html_str+='<td id="dscalendar_month_small_yearnav_mid">'+year_value+'</td>';
		html_str+='<td id="dscalendar_month_small_yearnav_right"><a href="javascript:DSCalendarScroll(\'year\',1,'+year+','+month+','+day+',\''+view+'\','+dscalid+',\''+info+'\');">&raquo;</a></td>';
		html_str+='</tr></table>';
		
		html_str+='<table cellspacing="0" id="dscalendar_month_small_monthnav"><tr>';
		html_str+='<td id="dscalendar_month_small_monthnav_left"><a href="javascript: DSCalendarScroll(\'month\',-1,'+year+','+month+','+day+',\''+view+'\','+dscalid+',\''+info+'\');">&laquo;</a></td>';
		if (view=='month_small'){
			html_str+='<td id="dscalendar_month_small_monthnav_mid" onclick="DSShowMonthList(event,'+year+','+month+','+day+',\''+view+'\','+dscalid+')">'+MonthNames[month]+'</td>';
		}
		else{
			html_str+='<td id="dscalendar_month_small_monthnav_mid"><select class="ds_calendar_month_small_select" size="1" id="help_monthlist" name="help_monthlist"'
			if (view=='calendar_to_link')
				html_str+=' onChange="top.DSCalendar_Custom(\'month\','+year+',this.selectedIndex,1,'+dscalid+');">'
			else
				html_str+=' onChange="DSCalendarView('+year+',this.selectedIndex,'+day+',\''+view+'\','+dscalid+');">'
			for(i = 0; i <= 11; i++){
					selectcode='';
				if(i==month)
					selectcode=' selected="selected"';
				html_str+='<option value="'+i+'"'+selectcode+'>'+MonthNames[i]+'</option>';
			}
			html_str+='</select></td>';
		}
		html_str+='<td id="dscalendar_month_small_monthnav_right"><a href="javascript:DSCalendarScroll(\'month\',1,'+year+','+month+','+day+',\''+view+'\','+dscalid+',\''+info+'\');">&raquo;</a></td>';
		html_str+='</tr></table>';
		
		html_str+='<table cellspacing="1" id="dscalendar_small">';		
		if (view=='month_small')
			html_str+='<tr id="dscalendar_month_small_dayname" onclick="DSLoadCalendarView('+year+','+month+','+day+',\'month\','+dscalid+')">';
		else
			html_str+='<tr id="dscalendar_month_small_dayname">'
		
		html_str+='<td>'+CalendarWeek+'</td>';
		for(i=0;i<7;i++){
			if (WeekStart=='s')
				this_day=i;
			else{
				this_day=i+1;
				if (this_day==7)
					this_day=0;
			}
			html_str+='<td>'+DayNamesShort[this_day]+'</td>';
		}
		html_str+='</tr>';		
		row=10;
		thisdate=startdate;
//top.DSCalendar_Custom(\'year\','+year+','+month+','+day+');
		for (i=1;i<=totaldays;i++){
			this_day=thisdate.getDate();
			this_month=thisdate.getMonth();
			this_year=thisdate.getFullYear();
			this_weekday=thisdate.getDay();
			if (row>=7){
				if (row>7)
					html_str+='</tr>';
				row=0;
				html_str+='<tr><td class="dscalendar_month_small_week">';
				if (view=='month_small')
					html_str+='<a href="javascript:DSLoadCalendarView('+this_year+','+this_month+','+this_day+',\'week\','+dscalid+')">'+DSWeekOfYear(this_year,this_month,this_day)+'</a></td>';
				else if (view=='calendar_to_link')
					html_str+='<a href="javascript:top.DSCalendar_Custom(\'week\','+this_year+','+this_month+','+this_day+','+dscalid+')">'+DSWeekOfYear(this_year,this_month,this_day)+'</a></td>';
				else
					html_str+=DSWeekOfYear(this_year,this_month,this_day)+'</td>';
			}
			//css=(this_day==day && this_month==month)?"dscalendar_month_small_active":((this_weekday==0 || this_weekday==6)?"dscalendar_month_small_weekend":"dscalendar_month_small_day");
			// css for link <a class="'+class+'"
			
			if (view=='calendar_to_link')
				tdcss=(this_day==top.DSCalendar_Custom_CurrentDate.getDate() && this_month==top.DSCalendar_Custom_CurrentDate.getMonth() && this_year==top.DSCalendar_Custom_CurrentDate.getFullYear())?" dscalendar_month_small_active":((this_weekday==0 || this_weekday==6)?" dscalendar_month_small_weekend":"");
			else
				tdcss=(this_day==day && this_month==month)?" dscalendar_month_small_active":((this_weekday==0 || this_weekday==6)?" dscalendar_month_small_weekend":"");
			html_str+='<td id="calendar_month_small_'+this_month+'_'+this_day+'_'+dscalid+'" class="dscalendar_month_small_day'+tdcss+'">';
			html_str+='<a href="javascript:DSCalendarNewDate('+this_year+','+this_month+','+this_day+',\''+view+'\','+dscalid+')">'+this_day+'</a></td>';
			thisdate=DSDateAdd('d',i,startdate);
			row++
		}

		if (view=='form'){
			now = new Date();
			year = now.getFullYear();
			month = now.getMonth();
			day = now.getDate();
			allow_no_date=info;
			html_str+='<tr height="35">';
			if (allow_no_date==1){
				html_str+='<td colspan="3" class="ds_calendar_footer" align="left"><a style="width:auto;" href="javascript: DSCalendarView('+year+','+month+','+day+',\'form\','+dscalid+')">'+DSLang('today')+'</a></td>';
				html_str+='<td colspan="2" class="ds_calendar_footer" align="center"><a style="width:auto;" href="javascript:DSCalendarNewDate(1901,0,1,\''+view+'\','+dscalid+');">'+DSLang('nodate')+'</a></td>';
				html_str+='<td colspan="3" class="ds_calendar_footer" align="right"><a style="width:auto;" href="javascript:DSContextHide();">'+DSLang('close')+'</a></td>';
			}
			else{
				html_str+='<td colspan="4" class="ds_calendar_footer" align="left"><a style="width:auto;" href="javascript: DSCalendarView('+year+','+month+','+day+',\'form\','+dscalid+')">'+DSLang('today')+'</a></td>';
				html_str+='<td colspan="4" class="ds_calendar_footer" align="right"><a style="width:auto;" href="javascript:DSContextHide();">'+DSLang('close')+'</a></td>';
			}
			
			html_str+='</tr>';
			//html_str+='</tr><td colspan="8">&nbsp;</td></tr>';
		}
		html_str+="</table>";
		if (view=='form')
			DSContextInnerHTML(html_str,1);
		else if (view=='month_small')
			$('ds_calendar_month_small_'+dscalid).innerHTML=html_str;
		else if (view=='calendar_to_link')
			$('ds_calendar_to_link_'+dscalid).innerHTML=html_str;
			
		if (view=='month_small' && DSCal!= null){
			loop_ok=0;
			for (ei=0;ei<DSCal.entries_length;ei++){
				if (DSCal.entries_show_date[ei] >= startdate && DSCal.entries_show_date[ei] < enddate){
					//alert(DSCal.entries_show_date[ei])
					$('calendar_month_small_'+DSCal.entries_show_date[ei].getMonth()+'_'+DSCal.entries_show_date[ei].getDate()+'_'+dscalid).className=' dscalendar_month_small_entry';
					loop_ok=1;
				}
				else if(loop_ok==1)
					break;
			}
		}
		
	}
	else if(view=='month'){
		//html_str='<div><a class="dscalendar_month_large_monthnav_left" href="javascript: DSCalendarScroll(\'month\',-1,'+year+','+month+','+day+',\''+view+'\','+dscalid+');">&laquo;</a><span style="width:300px; border:1px solid blue;"><a href="javascript:DSDoNothing()" class="dscalendar_month_large_monthnav_mid" onclick="DSShowMonthList(event,'+year+','+month+','+day+',\''+view+'\','+dscalid+')">'+MonthNames[month]+' '+year+'</a></span><a class="dscalendar_month_large_monthnav_right"><a href="javascript: DSCalendarScroll(\'month\',1,'+year+','+month+','+day+',\''+view+'\','+dscalid+');">&raquo;</a></div>';
			
		html_str='<table id="dscalendar_month_large_monthnav" class="dscalendar_month_large_monthnav" cellspacing="0" border="0">';
		html_str+='<tr>';
		html_str+='<td id="dscalendar_month_large_monthnav_left" class="dscalendar_month_large_monthnav_left"><a href="javascript: DSCalendarScroll(\'month\',-1,'+year+','+month+','+day+',\''+view+'\','+dscalid+',\''+info+'\');">&laquo;</a></td>';
		html_str+='<td id="dscalendar_month_large_monthnav_mid" class="dscalendar_month_large_monthnav_mid"><a href="javascript:DSDoNothing()" onclick="DSShowMonthList(event,'+year+','+month+','+day+',\''+view+'\','+dscalid+')">'+MonthNames[month]+' '+year+'</a></td>';
		html_str+='<td id="dscalendar_month_large_monthnav_right" class="dscalendar_month_large_monthnav_right"><a href="javascript: DSCalendarScroll(\'month\',1,'+year+','+month+','+day+',\''+view+'\','+dscalid+',\''+info+'\');">&raquo;</a></td>';
		html_str+='</tr></table>';
		
		
		html_str+='<table cellspacing="1" id="dscalendar_large"><tr id="dscalendar_month_large_dayname">';
		for(i=0;i<7;i++){
			if (WeekStart=='s'){
				this_day=i;
				html_str+='<td class="dscalendar_month_large_dayname">'+DayNamesShort[i]+'</td>';
			}
			else{
				this_day=i+1;
				if (this_day==7)
					this_day=0;
				if (WeekStart=="m" && SS_oneday==1 && this_day==6){
					html_str+='<td class="dscalendar_month_large_dayname">'+DayNamesShort[6]+' / '+DayNamesShort[0]+'</td>';
					break;
				}
				else{
					html_str+='<td class="dscalendar_month_large_dayname">'+DayNamesShort[this_day]+'</td>';
				}
			}
			
		}
		html_str+='</tr>';
		row=7;
		thisdate=startdate;
		for (i=1;i<=totaldays;i++){
			this_weekday=thisdate.getDay();
			this_day=thisdate.getDate();
			this_month=thisdate.getMonth();
			this_cf_month=this_month*1+1;
			this_year=thisdate.getFullYear();
			this_weekday=thisdate.getDay();
			if (row>=7){
				if (row>7)
					html_str+='</tr>';
				row=0;
				html_str+='<tr>';
			}
			css=(this_day==day && this_month==month)?"dscalendar_month_large_daynumber_active":((this_weekday==0 || this_weekday==6)?"dscalendar_month_large_daynumber_weekend":"dscalendar_month_large_daynumber");
			css='dscalendar_month_large_daynumber';
			tdcss=(this_day==day && this_month==month)?" dscalendar_month_large_active":((this_weekday==0 || this_weekday==6)?" dscalendar_month_large_weekend":"");
			if (WeekStart=="m" && SS_oneday==1){
				if (this_weekday==0 || this_weekday==6){
					if (this_weekday==0){
						html_str+='<tr>';
						html_str+='<td ondblclick="dsloader(\''+dsxpath+'dynasite.cfm?dscmd=calendar_calendar_event_new&amp;dscalid='+dscalid+'&amp;startdate='+this_year+'-'+this_cf_month+'-'+this_day+'\',\'dspopup2\')" id="calendar_month_'+this_month+'_'+this_day+'_'+dscalid+'" class="dscalendar_month_large_day'+tdcss+'"><a class="'+css+'" href="javascript:DSCalendarNewDate('+this_year+','+this_month+','+this_day+',\''+view+'\','+dscalid+')">'+this_day+'</a></td>';
						html_str+='</tr>';
					}
					else{
						html_str+='<td ondblclick="dsloader(\''+dsxpath+'dynasite.cfm?dscmd=calendar_calendar_event_new&amp;dscalid='+dscalid+'&amp;startdate='+this_year+'-'+this_cf_month+'-'+this_day+'\',\'dspopup2\')" id="calendar_month_'+this_month+'_'+this_day+'_'+dscalid+'" class="dscalendar_month_large_day'+tdcss+'"><a class="'+css+'" href="javascript:DSCalendarNewDate('+this_year+','+this_month+','+this_day+',\''+view+'\','+dscalid+')">'+this_day+'</a></td>';
					}
				}
				else{
					html_str+='<td rowspan="2" ondblclick="dsloader(\''+dsxpath+'dynasite.cfm?dscmd=calendar_calendar_event_new&amp;dscalid='+dscalid+'&amp;startdate='+this_year+'-'+this_cf_month+'-'+this_day+'\',\'dspopup2\')" id="calendar_month_'+this_month+'_'+this_day+'_'+dscalid+'" class="dscalendar_month_large_day'+tdcss+'"><a class="'+css+'" href="javascript:DSCalendarNewDate('+this_year+','+this_month+','+this_day+',\''+view+'\','+dscalid+')">'+this_day+'</a></td>';
				}
			}
			else{
				html_str+='<td ondblclick="dsloader(\''+dsxpath+'dynasite.cfm?dscmd=calendar_calendar_event_new&amp;dscalid='+dscalid+'&amp;startdate='+this_year+'-'+this_cf_month+'-'+this_day+'\',\'dspopup2\')" id="calendar_month_'+this_month+'_'+this_day+'_'+dscalid+'" class="dscalendar_month_large_day'+tdcss+'"><a class="'+css+'" href="javascript:DSCalendarNewDate('+this_year+','+this_month+','+this_day+',\''+view+'\','+dscalid+')">'+this_day+'</a></td>';
			}
			thisdate=DSDateAdd('d',i,startdate);
			row++
		}
		html_str+="</table>";
		
		$('ds_calendar_month_'+dscalid).innerHTML=html_str;

		loop_ok=0;
		//oncontextmenu="DSEntryContext(event,'+ei+','+dscalid+'); return false;" 
		for (ei=0;ei<DSCal.entries_length;ei++){
			if (DSCal.entries_show_date[ei] >= startdate && DSCal.entries_show_date[ei] < enddate){
				if (allow_edit)
					entry='<div class="dscalendar_month_large_entry" onmouseover="DSEventDetail(event,'+ei+','+dscalid+');" onclick="dsloader(\'dynasite.cfm?dscmd=calendar_calendar_event_edit&dscaleid='+DSCal.entries_id[ei]+'&dscalid='+dscalid+'\',\'dspopup2\')">'+DSCal.entries_title[ei]+'</div>';
				else
					entry='<div class="dscalendar_month_large_entry" onmouseover="DSEventDetail(event,'+ei+','+dscalid+');">'+DSCal.entries_title[ei]+'</div>';
				//alert(entry)
				$('calendar_month_'+DSCal.entries_show_date[ei].getMonth()+'_'+DSCal.entries_show_date[ei].getDate()+'_'+dscalid).innerHTML+=entry;
				loop_ok=1;
			}
			else if(loop_ok==1)
				break;
		}
	}
	else if(view=='week'){
		
		startdate=new Date(year,month,day);
		enddate=DSDateAdd('d',7,startdate);
		
		html_str='<table id="dscalendar_month_large_monthnav" class="dscalendar_month_large_monthnav" cellspacing="0" border="0">';
		html_str+='<tr>';
		html_str+='<td id="dscalendar_month_large_monthnav_left" class="dscalendar_month_large_monthnav_left"><a href="javascript: DSCalendarScroll(\'day\',-7,'+year+','+month+','+day+',\''+view+'\','+dscalid+',\''+info+'\');">&laquo;</a></td>';
		html_str+='<td id="dscalendar_month_large_monthnav_mid" class="dscalendar_month_large_monthnav_mid">'+DSWeekOfYear(year,month,day)+' in '+year+'</td>';
		html_str+='<td id="dscalendar_month_large_monthnav_right" class="dscalendar_month_large_monthnav_right"><a href="javascript: DSCalendarScroll(\'day\',7,'+year+','+month+','+day+',\''+view+'\','+dscalid+',\''+info+'\');">&raquo;</a></td>';
		html_str+='</tr></table>';

		
		html_str+='<table cellspacing="0" id="dscalendar_week"><tr>';

		c_str=""
		for(i=0;i<7;i++){
			thisdate=DSDateAdd('d',i,startdate);
			this_day=thisdate.getDate();
			this_month=thisdate.getMonth()+1;
			this_year=thisdate.getFullYear();
			if (WeekStart=="s")
				this_i=i;
			else{
				this_i=i+1;
				if (this_i==7)
					this_i=0;
			}
			html_str+='<tr>';
			html_str+='<td id="calendar_week_'+thisdate.getMonth()+'_'+this_day+'_'+dscalid+'" class="dscalendar_week_day" colspan="3" valign="top"><div class="dscalendar_week_day" style="cursor: pointer" onclick="DSCalendarView('+this_year+','+thisdate.getMonth()+','+this_day+',\'day\','+dscalid+')">'+DayNames[this_i]+' '+this_day+'.'+this_month+'.'+this_year+'</div></td>';
			html_str+='</tr>';
		}
		
		html_str+='</table>';
		$('ds_calendar_week_'+dscalid).innerHTML=html_str;

		loop_ok=0;
		for (ei=0;ei<DSCal.entries_length;ei++){
			if (DSCal.entries_show_date[ei]>=startdate && DSCal.entries_show_date[ei]<enddate){
				thisdate=DSCal.entries_show_date[ei];
				this_day=thisdate.getDate();
				this_month=thisdate.getMonth();
				if (allow_edit)
					entry='<div style="cursor: pointer" class="dscalendar_week_entry" onmouseover="DSEventDetail(event,'+ei+','+dscalid+');" onclick="dsloader(\'dynasite.cfm?dscmd=calendar_calendar_event_edit&dscaleid='+DSCal.entries_id[ei]+'\',\'dspopup2\')">'+DSCal.entries_title[ei]+'</div>';
				else
					entry='<div style="cursor: pointer" class="dscalendar_week_entry" onmouseover="DSEventDetail(event,'+ei+','+dscalid+');">'+DSCal.entries_title[ei]+'</div>';
				$('calendar_week_'+this_month+'_'+this_day+'_'+dscalid).innerHTML+=entry;
				loop_ok=1;
			}
			else if(loop_ok==1)
				break;
		}
		
		
	}
	
	else if(view=='day'){
		//document.getElementById('calendar_month_small_'+month+'_'+day).style.background='#EEEEEE';
		startdate=new Date(year,month,day,0,0,0);
		enddate=new Date(year,month,day,23,59,59);
		this_weekday=startdate.getDay();
		this_month=month*1+1;
		
		hour_height=20;
		day_width=650;
		day_height=DSInt(hour_height*24);		
		
		hour_width_left_listing=25;
				
		html_str='<div align="center" style="width:'+day_width+'px;"><table id="dscalendar_month_large_monthnav" class="dscalendar_month_large_monthnav" cellspacing="0" border="0">';
		html_str+='<tr>';
		html_str+='<td id="dscalendar_month_large_monthnav_left" class="dscalendar_month_large_monthnav_left"><a href="javascript: DSCalendarScroll(\'day\',-1,'+year+','+month+','+day+',\''+view+'\','+dscalid+',\''+info+'\');">&laquo;</a>&nbsp;</td>';
		html_str+='<td id="dscalendar_month_large_monthnav_mid" class="dscalendar_month_large_monthnav_mid">'+DayNames[this_weekday]+', den '+day+'.'+this_month+'.'+year+'</td>';
		html_str+='<td id="dscalendar_month_large_monthnav_right" class="dscalendar_month_large_monthnav_right">&nbsp;<a href="javascript: DSCalendarScroll(\'day\',1,'+year+','+month+','+day+',\''+view+'\','+dscalid+',\''+info+'\');">&raquo;</a></td>';
		html_str+='</tr>';
		html_str+='</table></div>';
		html_str+='<div id="calendar_day_'+day+'_'+dscalid+'" style="position:relative;">';
		html_str+='<table cellpadding="0" cellspacing="0" border="0">';
		for (i=0;i<=24;i++){
			if (i<10)
				real_i='0'+i;
			else
				real_i=i;
			html_str+='<tr height="'+hour_height+'"><td width="'+hour_width_left_listing+'">'+real_i+'</td><td><hr color="#DDDDDD" noshade="noshade" size="1" width="'+day_width+'"/></td></tr>';
		}
		html_str+='</table>';
		loop_ok=0;
		this_top=0;
		entry_list=new Array();
		entry_col=new Array();
		max_col=1;
		for (ei=0;ei<DSCal.entries_length;ei++){
			if (DSCal.entries_show_date[ei] >= startdate && DSCal.entries_show_date[ei] < enddate){
				entry_length=entry_list.length;
				entry_list[entry_length]=ei;
				entry_col[entry_length]=1;
				if (entry_length>0){
					for (ii=entry_length-1;ii>=0;ii--){
						if (DSCal.entries_end_date[entry_list[ii]]>DSCal.entries_show_date[ei]){
							this_col=entry_col[ii]+1;
							if (this_col>max_col)
								max_col=this_col;					
							entry_col[entry_length]=this_col;
							break;
						}
					}
				}
				html_str+='<div id="day_entry_time_'+ei+'_'+dscalid+'" style="position:absolute; border:0px solid blue; padding:0px; margin:0px; z-index:2; width:5px; height:5px; background-color: blue;"></div>';
				if (allow_edit)
					html_str+='<div id="day_entry_'+ei+'_'+dscalid+'" style="position:absolute; border:1px solid #333333; z-index: 1; padding-left:5px; background-color: #EFEBDE;" onmouseover="DSEventDetail(event,'+ei+','+dscalid+');" onclick="dsloader(\'dynasite.cfm?dscmd=calendar_calendar_event_edit&dscaleid='+DSCal.entries_id[ei]+'\',\'dspopup2\')">'+DSCal.entries_title[ei]+'</div>';
				else
					html_str+='<div id="day_entry_'+ei+'_'+dscalid+'" style="position:absolute; border:1px solid #333333; z-index: 1; padding-left:5px; background-color: #EFEBDE;" onmouseover="DSEventDetail(event,'+ei+','+dscalid+');">'+DSCal.entries_title[ei]+'</div>';
				loop_ok++;
			}
			else if(loop_ok>0)
				break;
		}
		
		
		html_str+='</div>';
		
		$('ds_calendar_day_'+dscalid).innerHTML=html_str;
		
		day_width=day_width-(hour_width_left_listing*1);
		
		for (i=0;i<entry_list.length;i++){		
			ei=entry_list[i];
			start_min=DSCal.entries_show_date[ei].getHours()*60+DSCal.entries_show_date[ei].getMinutes();
			if (DSCal.entries_end_date[ei]<enddate)
				end_min=DSCal.entries_end_date[ei].getHours()*60+DSCal.entries_end_date[ei].getMinutes();
			else
				end_min=1440;
			this_top=day_height*start_min/1440
			this_top=DSInt(this_top+hour_height/2)
			this_height=end_min-start_min;
			this_height=day_height*this_height/1440
			this_height=DSInt(this_height);
			if (this_height<1)
				this_height=1;
			this_width=DSInt(day_width/max_col);
			this_left=(this_width+10)*(entry_col[i]-1)+hour_width_left_listing;
			
			//alert(this_top+'px '+this_height+'px '+this_width+'px '+this_left+'px');
			
			this_entry=$('day_entry_'+ei+'_'+dscalid);
			this_entry.style.top=this_top+'px';
			if (this_height>25)
				this_entry.style.height=this_height+'px';
			this_entry.style.width=this_width+'px';
			this_entry.style.left=this_left+'px';

			time_entry=$('day_entry_time_'+ei+'_'+dscalid);
			time_entry.style.top=this_top+'px';
			time_entry.style.height=this_height+'px';
			time_entry.style.left=this_left+'px';

			//if (this_height>25 && max_col<=2){
				event_start_date='';
				if (DSCal.entries_start_date[ei]<startdate)
					event_start_date+=DayNamesShort[DSCal.entries_start_date[ei].getDay()]+', '+DSDateTimeFormat('date',DSCal.entries_start_date[ei])+' ';
				event_start_date+=DSDateTimeFormat('time',DSCal.entries_start_date[ei])
				event_end_date='';
				if (DSCal.entries_end_date[ei]>enddate)
					event_end_date+=DayNamesShort[DSCal.entries_end_date[ei].getDay()]+', '+DSDateTimeFormat('date',DSCal.entries_end_date[ei])+' ';
				event_end_date+=DSDateTimeFormat('time',DSCal.entries_end_date[ei]);
				this_entry.innerHTML+='<br />('+event_start_date+' - '+event_end_date+')';
			//}
			//else{
				//this_entry.style.fontSize='7pt';
			//}
			//this_entry.innerHTML+='start:'+start_min+' top:'+this_top+' height:'+this_height;
		}
	}
	else if(view=='overview_small'){
		
		now = new Date();
		now = new Date(now.getYear(), now.getMonth(),now.getDate(), 0, 0, 0);
		html_str='';
		maxshow=25;

		html_str+='<div align="center"><table class="dstable">';
		css_run=0;
		for (ei=0;ei<DSCal.entries_length;ei++){
			if (DSCal.entries_start_date[ei]>now){
				if ( DSInt(css_run/2) == css_run/2 ){
					css='dslist1';
				}
				else{
					css='dslist2';			
				}
				startdate=DSDateTimeFormat('date',DSCal.entries_start_date[ei])+' '+DSDateTimeFormat('time',DSCal.entries_start_date[ei]);
				html_str+='<tr class="'+css+'">';
				html_str+='<td style="vertical-align:top;white-space:nowrap;text-align:left">'+startdate+'</td>';
				if (allow_edit)
					html_str+='<td onmouseover="DSEventDetail(event,'+ei+','+dscalid+');" onclick="dsloader(\'dynasite.cfm?dscmd=calendar_calendar_event_edit&dscaleid='+DSCal.entries_id[ei]+'&dscalid='+dscalid+'\',\'dspopup2\')" style="padding-left:4px;text-align:left">'+DSCal.entries_title[ei]+'</td>';
				else
					html_str+='<td onmouseover="DSEventDetail(event,'+ei+','+dscalid+');" style="padding-left:4px;text-align:left">'+DSCal.entries_title[ei]+'</td>';
				html_str+='</tr>';
				css_run++;
			}
			if (css_run >= maxshow){
				break;
			}
		}
		html_str+='</table></div>';
		$('ds_calendar_overview_small_'+dscalid).innerHTML=html_str;
		$('ds_calendar_overview_small_'+dscalid).style.display='block';
	}
	else if(view=='overview'){
		now = new Date();
		now = new Date(now.getYear(), now.getMonth(),now.getDate(), 0, 0, 0);
		
		
		html_str='<table id="dscalendar_month_large_monthnav" class="dscalendar_month_large_monthnav" cellspacing="0" border="0">';
		html_str+='<tr>';
		html_str+='<td id="dscalendar_month_large_monthnav_left" class="dscalendar_month_large_monthnav_left"><a href="javascript: DSCalendarScroll(\'month\',-1,'+year+','+month+','+day+',\''+view+'\','+dscalid+',\''+info+'\');">&laquo;</a></td>';
		html_str+='<td id="dscalendar_month_large_monthnav_mid" class="dscalendar_month_large_monthnav_mid"><a href="javascript:DSDoNothing()" onclick="DSShowMonthList(event,'+year+','+month+','+day+',\''+view+'\','+dscalid+')">'+MonthNames[month]+' '+year+'</a></td>';
		html_str+='<td id="dscalendar_month_large_monthnav_right" class="dscalendar_month_large_monthnav_right"><a href="javascript: DSCalendarScroll(\'month\',1,'+year+','+month+','+day+',\''+view+'\','+dscalid+',\''+info+'\');">&raquo;</a></td>';
		html_str+='</tr></table>';
		
		html_str+='<table cellpadding="1" cellspacing="0" border="0" width="100%">';
		css_run=0;
		for (ei=0;ei<DSCal.entries_length;ei++){
			if (DSCal.entries_start_date[ei].getMonth()==month){
				if ( DSInt(css_run/2) == css_run/2 ){
					if (DSCal.entries_start_date[ei]>=now)
						css='class="dslist1"';
					else
						css='bgcolor="#c0c0c0"';	
				}
				else{
					if (DSCal.entries_start_date[ei]>=now)
						css='class="dslist2"';
					else
						css='bgcolor="#e0e0e0"';			
				}
				this_startdate=DSDateTimeFormat('date',DSCal.entries_start_date[ei]);
				html_str+='<tr '+css+'>';
				html_str+='<td align="left" valign="top" width="80">'+this_startdate+'</td>';
				if (allow_edit)
					html_str+='<td align="left" onclick="dsloader(\'dynasite.cfm?dscmd=calendar_calendar_event_edit&dscaleid='+DSCal.entries_id[ei]+'&dscalid='+dscalid+'\',\'dspopup2\')">'+DSCal.entries_title[ei];
				else
					html_str+='<td align="left">'+DSCal.entries_title[ei];
				html_str+='<div>Start: '+DSDateTimeFormat('time',DSCal.entries_start_date[ei])+'</div>';
				html_str+='<div>Ende: '+DSDateTimeFormat('time',DSCal.entries_end_date[ei])+'</div>';
				html_str+='</td>';
				html_str+='</tr>';
				css_run++
			}
		}
		html_str+='</table></div>';
		
		$('ds_calendar_overview_'+dscalid).innerHTML=html_str;

	}
	//if(view!='day') dscalendar_monthselect
		//DSPopUpResize();	
}



function DSEventDetail(e,ei,dscalid){
	DSCal=eval('top.DSCal_'+dscalid);
	//top.DSCal_#dscalid#.calendar_action
	startdate=DSDateTimeFormat('date',DSCal.entries_start_date[ei])+' '+DSDateTimeFormat('time',DSCal.entries_start_date[ei]);
	enddate=DSDateTimeFormat('date',DSCal.entries_end_date[ei])+' '+DSDateTimeFormat('time',DSCal.entries_end_date[ei]);
	html_str='<div class="dscontextmenucontent">'
	
	if (DSArrayFind(DSCal.calendar_action,'edit'))
		html_str+='<a class="dsconmenu" href="javascript: DSContextHide(); dsloader(\'dynasite.cfm?dscmd=calendar_calendar_event_edit&dscaleid='+DSCal.entries_id[ei]+'&dscalid='+dscalid+'\',\'dspopup2\')">'+DSLang('edit')+'</a>';
	//html_str+='<div class="dscalendar_monthselect" style="font-weight:bold;">'+DSCal.entries_createdname[ei]+'</div>';
	html_str+='<div class="dsconmenu">Start: '+startdate+'</div>';
	html_str+='<div class="dsconmenu">Ende: '+enddate+'</div>';
	html_str+='<div class="dsconmenu">'+DSCal.entries_title[ei]+'</div>';
	//html_str+='<a class="dscalendar_monthselect dsconmenu" href="javascript: DSContextHide(); DSEntryDeleteConfirm('+DSCal.entries_id[ei]+','+dscalid+');">Delete</a>';
	DSColorSchemeBar(3,'variable');
	html_str+='<div class="dscontextmenutitle">Event ['+DSCal.entries_id[ei]+']</div>'+colorschemebar+'</div></div>';
	DSContextShow(e,html_str,'onmouseout=1;');
}

function DSEventDeleteConfirm(dscaleid,dscalid){
	ok=confirm(DSLang('alertdeleteevent'));
	if (ok){
		self.location.href='dynasite.cfm?dscmd=calendar_calendar_event_delete&dscaleid='+dscaleid+'&dscalid='+dscalid;
	}
}


function DSTaskDeleteConfirm(dscaleid,dscalid){
	ok=confirm(DSLang('alertdeletetask'));
	if (ok)
		self.location.href='dynasite.cfm?dscmd=calendar_calendar_task_delete&dscaleid='+dscaleid+'&dscalid='+dscalid;
}

function DSTaskStatusConfirm_xxxxxxxxx (newstatus,dscaleid,querystring){
		//ok=confirm('Do you realy want to set the Task to "'+status_list_en[newstatus]+'"?')
	ok=true;
	if (ok){
		dsloader('dynasite.cfm?dscmd=calendar_calendar_task_status&dscaleid='+dscaleid+'&newstatus='+newstatus+querystring,'dsloader');
	}
	DSContextHide();
}

function DSTaskStatus(e,status,dscaleid,querystring){
	var i=0;
	if (querystring==null)
		querystring='';
	html_str='<div class="dscontextmenucontent">';
	html_str+='<a class="dsconmenu" href="javascript:DSContextHide(); dsloader(\'dynasite.cfm?dscmd=calendar_calendar_task_edit&dscaleid='+dscaleid+querystring+'\',\'dspopup2\')">'+DSLang('edit')+'</a>';
	for (i=0;i<status_list_en.length;i++){
		if (status==status_list_en[i])
			this_val='<strong>'+status_list_de[i]+'</strong>';
		else
			this_val=status_list_de[i];	
		html_str+='<a class="dsconmenu" href="javascript:DSContextHide(); dsloader(\'dynasite.cfm?dscmd=calendar_calendar_task_status&amp;dscaleid='+dscaleid+'&amp;newstatus='+status_list_en[i]+querystring+'\',\'dsloader\')">'+this_val+'</a>';
		//html_str+='<a class="dsconmenu" href="javascript: DSTaskStatusConfirm(\''+status_list_en[i]+'\','+dscaleid+',\''+querystring+'\');">'+this_val+'</a>';
	}		
	DSColorSchemeBar(3,'variable');
	html_str+='<div class="dscontextmenutitle">'+DSLang('Task')+' ['+dscaleid+']</div>'+colorschemebar+'</div></div>';
	DSContextShow(e,html_str);
}
document.write('<link rel="stylesheet" type="text/css" charset="utf-8" href="'+DSGlobalPath+'script/jscalendar/calendar-blue3.css"/>');
document.write('<script type="text/javascript" charset="utf-8" src="'+DSGlobalPath+'script/jscalendar/calendar.js"></script>');
document.write('<script type="text/javascript" charset="utf-8" src="'+DSGlobalPath+'script/jscalendar/lang/calendar-'+dslang+'.js"></script>');
document.write('<script type="text/javascript" charset="utf-8" src="'+DSGlobalPath+'script/jscalendar/calendar-setup.js"></script>');
if(window.navigator.appName=="Microsoft Internet Explorer")
	var IE=Number(navigator.appVersion.substr(navigator.appVersion.search("MSIE")+5,1));
else 
	var IE=false;
document.write('<link rel="stylesheet" type="text/css" charset="utf-8" href="'+DSGlobalPath+'script/dscalendarnew/css/result.css"/>');
document.write('<link rel="stylesheet" type="text/css" charset="utf-8" href="'+DSGlobalPath+'script/dscalendarnew/css/dialog.css"/>');

//AppointmentCalendar
var AppointmentCalendar=Class.create({
   
   	GETFORDAY:1,
	GETFORWEEK:2,
	GETFORMONTH:3,
	GETAGENDA:4,
	
	initialize: function(view,resContainer,calContainer,urls,calid,uid,showOwners,isEditable,calOnlickLink) {
		var that=this;
		this.actAction=null;
		this.actDate=new Date();
		this.appointment_days=null;
		this.calendar=null;
		this.editor=null;
		this.model=null;
		this.owners=new Object();
		this.refresh=true;
		this.resCont=null;
		this.view=null;
		this.timer=null;
		this.isCalendarAct=false;
		this.displayOwners=showOwners;
		this.isEditable=isEditable? isEditable:false;
		this.calOnlick=null;
		if(calOnlickLink && calOnlickLink!=""){
			this.calOnlickLink=calOnlickLink;
			this.calOnclick=function(){
					DSDispatchEvent(that.calOnlickLink); 
			}
		}
		this.URL={
			appointments:null,
			newappointment:null,
			remove:null,
			getOwners:null,
			updateOwner:null
		};
		this.URL=urls;
		this.uid=uid;
		this.isSmalInitialized=false;
		this.isBigInitialized=false;
		this.calid=calid;
		this.calContainer=calContainer;
		this.model=new CalendarModel(this);
		if(view=="month_small" || view=="month_big_small"){
			this.isSmalInitialized=true;
			$(this.calContainer).show();
			this.setCalender();
			this.loadAppointments();
		}
		this.actAction=this.GETFORMONTH;
		if(view=="month_big" || view=="month_big_small"){
			this.result=resContainer+"_result";
			var tmp=new Element("div",{"id":this.result});
			var rc=$(resContainer);
			rc.addClassName("dscal_container");
			rc.insert(tmp);
			var rcw=rc.getWidth();
			tmp.style.width=rcw>=350? (rcw-5)+"px":"500px";
			var rch=rc.getHeight();
			tmp.style.height=rch>=350? (rch-5)+"px":"500px";
			this.height=tmp.getHeight();
			this.width=tmp.getWidth();
			this.resCont=$(this.result);
			this.resCont.addClassName("dscal_result");
			this.view=new CalendarView(this.resCont, this,this.result);
			if(view!="month_big_small")
				this.setCalender();
			if(this.displayOwners){
				if(!$(this.result+"_favorites")){
					this.minusOwnerWidth=true;
					$(resContainer).insert("<div id='"+this.result+"_favorites' class='dscal_favorites_container'></div>");
				}
			}
			this.getOwners();
		}
		this.seldate1=null;
		this.seldate2=null;
		//this.result=resContainer;
	},
	reInitialize:function(view,resContainer,calContainer,showOwners,isEditable,urls,calOnlickLink){
		this.URL=urls;
		this.displayOwners=showOwners;
		this.isEditable=isEditable? isEditable:this.isEditable;
		this.calOnlick=null;
		if(calOnlickLink && calOnlickLink!=""){
			this.calOnlickLink=calOnlickLink;
			this.calOnclick=function(){
					DSDispatchEvent(that.calOnlickLink); 
			}
		}
		if(view=="month_small" || view=="month_big_small"){
			this.calContainer=calContainer;
			this.isSmalInitialized=true;
			this.calendar.destroy();
			this.setCalender();
			$(this.calContainer).show();
			this.loadAppointments();
		}else if(view=="month_big" || view=="month_big_small"){
			this.isBigInitialized=false;
			this.result=resContainer+"_result";
			var tmp=new Element("div",{"id":this.result});
			var rc=$(resContainer);
			rc.addClassName("dscal_container");
			rc.insert(tmp);
			var rcw=rc.getWidth();
			tmp.style.width=rcw>200? (rcw-5)+"px":"500px";
			var rch=rc.getHeight();
			tmp.style.height=rch>200? (rch-5)+"px":"500px";
			this.height=tmp.getHeight();
			this.width=tmp.getWidth();
			this.resCont=$(this.result);
			this.resCont.addClassName("dscal_result");
			this.view=new CalendarView(this.resCont, this,this.result);
			if(view!="month_big_small" && !$(this.calContainer)){
				this.calendar.destroy();
				this.setCalender();
			}
			if(this.displayOwners){
				if(!$(this.result+"_favorites")){
					this.minusOwnerWidth=true;
					$(resContainer).insert("<div id='"+this.result+"_favorites'  class='dscal_favorites_container'></div>");
				}
			}
			this.getOwners();
		}
	},
	showQuickForm:function(event,ftn,withHours){
		var that=this;
		if(this.seldate1<this.seldate2){
			var fdate=this.seldate1.print("%Y-%m-%d %H:%M");
			var tdate=this.seldate2.print("%Y-%m-%d %H:%M");
		}
		else{
			var fdate=this.seldate2.print("%Y-%m-%d %H:%M");
			var tdate=this.seldate1.print("%Y-%m-%d %H:%M");
		}
		new Ajax.Request(that.URL.quickform, {
		  method: 'post',
		  parameters:'fulltime_from='+fdate+'&fulltime_to='+tdate+'&fulltime_recurrence='+tdate,
		  onComplete: function(transport) {
			Dialog.setMsg(transport.responseText);
			Dialog.setFooter("");
			Dialog.info(event,ftn);
		  }
		});
		/*
		var sbmt=new Element('input',{'type':'button','value':DSLang('Save'),'class':'ds_button'});
		sbmt.observe("click",function(){
			that.createAppointment($(that.calid+'_quick_app_title').value);
		});
		var footer=new Element("div");
		footer.insert(sbmt);
		var dateilslink=new Element("a",{href:that.URL.newappointment});
		dateilslink.update(DSLang("Details"));
		footer.insert("&nbsp;&nbsp;");
		footer.insert(dateilslink);
		var format=withHours? "%a %d.%m.%Y %H:%M":"%a %d.%m.%Y";
		if(this.seldate1<this.seldate2){
			tmpstr=this.seldate1.print(format)+" - "
			+this.seldate2.print(format);
		}
		else{
			tmpstr=this.seldate2.print(format)+" - "
			+this.seldate1.print(format);
		}
		var msg="<div>"+tmpstr+"</div>\
		<div><div class='ds_label'>"+DSLang("Title")+"&nbsp;</div><div class='ds_field' style='width:150px'><input type='text' class='ds_text' id='"+this.id+"_quick_app_title' name='title'/></div></div>\
		";
		Dialog.setFooter(footer);
		Dialog.setMsg(msg);
		Dialog.info(event,ftn);
		$(this.id+'_quick_app_title').focus();
		*/
	},
	showAll:function(date,event){
		var obj=this.model.appointments_long;
		var divAll=new Element("div",{"style":"width:250px"});
		for(ap in obj){
			if(obj[ap].isEqualsDay(date)){
				if(this.owners[obj[ap].owner_id].show==1){
					var ld="<div class='side'></div>";
					var rd="<div class='side'></div>";
					var that=obj[ap];
					if(obj[ap].isActive=="Maybe" ||obj[ap].isActive=="Unconfirmed")
						sings="? ";
					var div=new Element('div',{"class": "appointment","align":"left", 'style':'position:static'});
					div.observe('click', function(){that.show()});
					divAll.insert(div);
					if(obj[ap].isActive=="Cancelled")
							div.style.textDecoration="line-through";
					div.update("<div class='appointment_title' style='position:static; border-right:1px solid #DDDDDD;width:99%'><div class='spacer'></div><div class='text'>"+obj[ap].what+"</div></div>");
					div.style.backgroundColor=this.owners[obj[ap].owner_id].color;
				}
			}
		}
		var obj=this.model.appointments_short;
		for(ap in obj){
			if(obj[ap].isEqualsDay(date)){
				if(this.owners[obj[ap].owner_id].show==1){
					var ld="<div class='side'></div>";
					var rd="<div class='side'></div>";
					var that=obj[ap];
					if(obj[ap].isActive=="Maybe" ||obj[ap].isActive=="Unconfirmed")
						sings="? ";
					var div=new Element('div',{"class": "appointment","align":"left", 'style':'position:static'});
					div.observe('click', function(){that.show()});
					divAll.insert(div);
					if(obj[ap].isActive=="Cancelled")
							div.style.textDecoration="line-through";
					div.update("<div class='appointment_title' style='position:static; border-right:1px solid #DDDDDD;;width:99%'><div class='spacer'></div><div class='text'>"+obj[ap].from_date.print("%H:%M")+" "+obj[ap].what+"</div></div>");
					div.style.color=this.owners[obj[ap].owner_id].color;
				}
			}
		}
		Dialog.setMsg(divAll);
		Dialog.info(event);
		
	},
	changeDate:function(int){
		switch(this.actAction){
				case this.GETFORMONTH:
						var tmpdate=new Date(this.calendar.date);
						tmpdate.setMonth(tmpdate.getMonth()+int);
						break;
				case this.GETFORDAY:
						var tmpdate=new Date(this.calendar.date);
						tmpdate.setDate(tmpdate.getDate()+int);
					break;
				case this.GETFORWEEK:
						var tmpdate=new Date(this.calendar.date);
						tmpdate.setDate(tmpdate.getDate()+(int*7));
					break;
				default:
					var tmpdate=new Date(this.calendar.date);
					tmpdate.setDate(tmpdate.getDate()+int);
				}
		this.calendar._init(this.calendar.firstDayOfWeek,tmpdate);
		this.showAppointments();
	},
	createAppointment:function(title){
		/*this.editor=new AppointmentEditor(this);
		this.editor.create();*/
		var that=this;
		if(title=='') title=DSLang("noname");
		if(this.seldate1<this.seldate2){
			var fdate=this.seldate1.toLocaleString();
			var tdate=this.seldate2.toLocaleString();
		}
		else{
			var fdate=this.seldate2.toLocaleString();
			var tdate=this.seldate1.toLocaleString();
		}
		new Ajax.Request(that.URL.newappointment, {
							  method: 'post',
							  parameters:'title='+title+'&fulltime_from='+fdate+'&fulltime_to='+tdate+'&fulltime_recurrence='+tdate,
							  onComplete: function(transport) {
								that.refresh=true;
								that.loadAppointments();
							  }
							});
		Dialog.close();
	},
	removeAppointment:function(appointment){
		var that=this;
		new Ajax.Request(that.URL.remove+appointment.id, {
							  method: 'post',
							  onComplete: function(transport) {
								that.refresh=true;
								that.loadAppointments();
							  }
							});
	},
	editAppointment:function(appointment){
		/*this.editor=new AppointmentEditor(this);
		this.editor.edit(appointment);*/
	},
	showDetails:function(appointment){
		var that=this;
		new Ajax.Request(that.URL.details+appointment.id+"&owner_id="+appointment.owner_id, {
		  method: 'post',
		  evalScripts: true,
		  onComplete: function(transport) {
			Dialog.setMsg(transport.responseText);
			Dialog.info();
		  }
		});
	},
	dateIsSpecial:function(date,year, month, day) {
		if(!this.appointment_days[date.getFullYear()])
			return false;
		if(!this.appointment_days[date.getFullYear()][date.getMonth()])
			return false;
		return this.appointment_days[date.getFullYear()][date.getMonth()][date.getDate()]? true:false;
	},
	
	setOwnerColor:function(elm,id,color){
		this.owners[id].color=color;
		elm.style.backgroundColor=color;
		this.updateOwner(id);
	},
	setOwnerShow:function(id){
		if(this.owners[id].show==1)this.owners[id].show=0;
		else this.owners[id].show=1;
		this.updateOwner(id);
	},	
		
	updateOwner:function(id){
		var that=this;
		var qs="owner_id="+id+"&color="+this.owners[id].color+"&show="+this.owners[id].show;
		new Ajax.Request(that.URL.updateOwner, {
							  method: 'post',
							  parameters: qs,
							  onSuccess: function() {
								that.refresh=true;
								that.loadAppointments();
							  }
							});
	},
	
	initOwners:function(){
		if(this.displayOwners){
			var that=this;
			var ows=Object.keys(this.owners);
			$(this.result+'_favorites').update("");
			ows.each(function(e){
				var owner=that.owners[e];
				if(owner.show==1)
					var ch=true;
				else
					var ch=false; 
				var tmpd=new Element('div',{'class':'favorite'});
				var tmpch=new Element("input",{"type":"checkbox"});
				var tmpid=e;
				tmpch.observe("click",function(){
											that.setOwnerShow(tmpid);   
											  });
				var tmpbtn=new Element("div",{"class":"favorite_button","style":'background-color: '+owner.color}).update(owner.name);
				tmpbtn.observe("click",function(event){
											colorPicker.showPicker(event,function(elm, color){that.setOwnerColor(elm,tmpid,color)});   
											  });
				var tmpdiv1=new Element("div",{"class":"div_10percent"}).insert(tmpch);
				var tmpdiv2=new Element("div",{"class":"div_90percent"}).insert(tmpbtn);
				tmpd.insert(tmpdiv1);
				tmpd.insert(tmpdiv2);
				$(that.result+'_favorites').insert(tmpd);  
				tmpch.checked=ch;
			});
			if(!this.isBigInitialized){
				if(this.minusOwnerWidth){
					this.resCont.style.width=this.resCont.getWidth()-$(this.result+'_favorites').getWidth()+"px";
					this.width=this.resCont.getWidth();
				}
				this.isBigInitialized=true;
			}
		}else
			this.isBigInitialized=true;
		this.loadAppointments();
	},
	
	getOwners:function(){
		var that=this;
		new Ajax.Request(that.URL.getOwners, {
		  method: 'post',
		  onSuccess: function(transport) {
			if(transport.responseText)
				{
					that.owners=transport.responseText.evalJSON();
					that.initOwners();
				}
		  }
		});
		/*this.owners={"1":{"name":"Aleks","color":"rgb(255,102,102)","show":"1"}};
		this.initOwners();*/
	},
	
	showAppointments:function (){
		if(this.isBigInitialized){
			if((this.actDate.getYear()!=this.calendar.date.getYear())||(this.actDate.getMonth()!=this.calendar.date.getMonth())){
				this.actDate.setTime(this.calendar.date.getTime());
				this.refresh=true;
				this.loadAppointments(this.calendar.date);
			}
			else {
				switch(this.actAction){
				case this.GETFORMONTH:
						$(this.result+'_datetime').update(this.calendar.date.print("%B %Y"));
						if(this.refresh){
							this.view.showForMonth();
								this.refresh=false;
						}
						break;
				case this.GETFORDAY:
						$(this.result+'_datetime').update(this.calendar.date.print("%a %d.%m.%Y"));
						this.view.showForDay();
						this.refresh=false;
					break;
				case this.GETFORWEEK:
						$(this.result+'_datetime').update(this.calendar.date.print(""));
						if(this.actDate.getWeekNumber()!=this.calendar.date.getWeekNumber()||this.refresh){
							this.actDate.setTime(this.calendar.date.getTime());
							this.view.showForWeek();
							this.refresh=false;
						}
					break;
				case this.GETAGENDA:
						$(this.result+'_datetime').update(this.calendar.date.print("%a %d.%m.%Y"));
						this.view.showAgenda();
						this.refresh=false;
					break;
				default:
				}
			};
		}
	},
	
	dateChanged:function() {
			if(this.calOnclick)
				this.calOnclick();
			this.showAppointments();
	},
	
	DateStatusFunc:function (date,y, m, d) {
		if(this.appointment_days){
			if (this.dateIsSpecial(date,y, m, d)){
				return "appointment";
			}
			else{
				return false;
			};
		}else return false;
	},
	
	setCalender:function(){
	  var that=this;
	  if(!$(this.calContainer)){
	  	var tmp=new Element("div",{"id":"tmp_month_small_"+that.calid});
		new Insertion.After(this.resCont,tmp);
		tmp.hide();
		this.calContainer="tmp_month_small_"+that.calid;
	  }
	  this.calendar=Calendar.setup(
		{
		  flat         : that.calContainer, 
		  flatCallback  : function(){that.dateChanged()}, 
		  dateStatusFunc : function(date, y, m, d){return that.DateStatusFunc(date, y, m, d)},
		  firstDay  : 1,
		  showOthers: true,
		  enableFirstDayChange: false
		}
	  );
	  this.model.calendar=this.calendar;
	},
	loadAppointments:function(date){
		//try{
			//Dialog.close();
			Dialog.close();
			if(this.calendar){
				var date = new Date(this.calendar.date.getTime());
			}
			else{
				var date=date? new Date(date.getTime()): new Date();
			};
			date=date.setFirstWKDay(this.calendar.firstDayOfWeek);
			var tdate=new Date(date.getTime());
			tdate.setDate(date.getDate()+41);
			date.setHours(0);
			date.setMinutes(0);
			date=date.toUTCString();
			tdate.setHours(23);
			tdate.setMinutes(59);
			tdate=tdate.toUTCString();
			var that=this;
			new Ajax.Request(that.URL.appointments, {
			  method: 'post',
			  parameters: 'date='+date+'&tdate='+tdate,
			  onSuccess: function(transport){
				that.model.reset();
				that.model.parseData(transport);
				that.appointment_days=that.model.getAppointmentDays();
				that.refresh=true;
				that.calendar.refresh();
 				that.showAppointments();
			},
			  onFailure: function(e){
				var err = new Error(); 
			    err.name = 'URIError'; 
			    err.message = "Kalender: Server gab einen Fehler zur&uuml;ck."; 
			    if(typeof console!='undefined')console.error(err.message); 
				alert("CalError: \n"+e.responseText);
				that.model.reset();
				that.refresh=true;
				that.showAppointments();
			  },
			  onException: function(e){
				var err = new Error(); 
			    err.name = 'ConversionError'; 
			    err.message = "Kalender: Fehler bei Termindarstellung"; 
			    if(typeof console!='undefined')console.error(err.message);
				alert("CalException: \n"+e.responseText);
				that.model.reset();
				that.refresh=true;
				that.showAppointments();
			  }
			});
		//}catch(e){Dialog.info(e.message)}
	}
});
//END AppointmentCalendar


//Dialog
var Dialog={
	container:null,
	content:null,
	shadowbox:'<table id="dlg_shadow" cellpadding="0" cellspacing="0">\
				<tbody>\
					<tr><td class="dlg_shadow_top_left">&nbsp;</td><td class="dlg_shadow_top">&nbsp;</td><td class="dlg_shadow_top_right">&nbsp;</td></tr>\
					<tr><td  class="dlg_shadow_left">&nbsp;</td>\<td class="dlg_shadow_middle">&nbsp;</td>\<td  class="dlg_shadow_right">&nbsp;</td></tr>\
					<tr><td class="dlg_shadow_bottom_left">&nbsp;</td><td class="dlg_shadow_bottom">&nbsp;</td><td class="dlg_shadow_bottom_right">&nbsp;</td></tr>\
				</tbody>\
			</table>',
	box:'<div id="dlg_info" class="dlg_info_middle">\
				<div align="left" class="dlg_top"><div id="dlg_close"></div></div>\
				<div id="dlg_content"></div>\
				<div id="dlg_footer"></div>\
		</div>',
	iefix:null,
	shadowUnder: function() {
		var element = this.container;
		var offset = element.cumulativeOffset();
		var dimensions = element.getDimensions();
		var style = {
			  left: (offset[0]-20) + 'px',
			  position: "absolute",
			  top: (offset[1]-20) + 'px',
			  zIndex: element.getStyle('zIndex') - 1
			};
		this.shadow.show();
		this.shadow.setStyle(style);
		if(!this.shadow_middle)
			this.shadow_middle=$$(".dlg_shadow_middle")[0];
		this.shadow_middle.width=(dimensions.width-22) + 'px';
		this.shadow_middle.height=(dimensions.height-22) + 'px';
	  }
	
};
Dialog.visible=function(){
	return Dialog.container.visible();
};
Dialog.setMsg=function(msg){
	if(!this.container){
		this.init();
	}
	this.content.update(msg);
};
Dialog.setFooter=function(text){
	if(!this.container){
		this.init();
	}
	this.footer.update(text);
};
Dialog.Shirm=Class.create({
	  
	  initialize: function() {
		/*if(ie){
			this.element = new Element("iframe", {
			  "class": "dlg_overlay",
			  "src": "#",
			  "frameborder": 0
			});
		}else{*/
			this.element=new Element("div",{ "class": "dlg_overlay"	});			
		/*};*/
		$(document.body).insert(this.element);
		this.element.hide();
	  },
	  hide: function() {
		this.element.hide();
		return this;
	  },
	
	  show: function() {
		this.element.show();
		return this;
	  },
	  
	  positionUnder: function(element) {
		var element = $(element);
		var offset = element.cumulativeOffset();
		var dimensions = element.getDimensions();
		var style = {
			  left: offset[0] + 'px',
			  top: offset[1] + 'px',
			  width: dimensions.width + 'px',
			  height: dimensions.height + 'px',
			  zIndex: element.getStyle('zIndex') - 1
			};
		this.show()
		this.element.setStyle(style);
	
		return this;
	  },
	  positionOver: function(element) {
		var element = $(element);
		var offset = element.cumulativeOffset();
		var dimensions = element.getDimensions();
		var style = {
			  left: offset[0] + 'px',
			  top: offset[1] + 'px',
			  width: dimensions.width + 'px',
			  height: dimensions.height + 'px',
			  zIndex: element.getStyle('zIndex') + 1
			};
		this.element.show()	
		this.element.setStyle(style);
	
		return this;
	  },
	
	  setBounds: function(bounds) {
		for (prop in bounds) {
		  bounds[prop] += 'px';
		}
		this.element.setStyle(bounds);
		return this;
	  },

	  destroy: function() {
		if (this.element)
		  this.element.remove();
	
		return this;
	  }
});
Dialog.setSize=function(){
	
};
Dialog.setBounds=function(event){
	var left=Event.pointerX(event);
	var top=Event.pointerY(event);
	this.container.style.left=left+"px";
	this.container.style.top=top+"px";
	var clickX=event.clientX;
	var clickY=event.clientY;
	var contWidth=this.container.getWidth();
	var contHeight=this.container.getHeight();
	var viewWidth=document.viewport.getWidth();
	var viewHeight=document.viewport.getHeight();
	if(clickX+contWidth>=viewWidth)
		left=left-contWidth;
	if(clickY+contHeight>=viewHeight)
		top=top-contHeight;
	this.container.style.left=left+"px";
	this.container.style.top=top+"px";
};
Dialog.init=function(event){
	$(document.body).insert(this.box);
	$(document.body).insert(this.shadowbox);
	this.container=$("dlg_info");
	this.content=$("dlg_content");
	this.footer=$("dlg_footer");
	this.shadow=$("dlg_shadow");
	$("dlg_close").observe("click",function(){Dialog.close()});
	this.container.hide();
	this.shadow.hide();
	/*this.iefix = new Dialog.Shirm();
	this.iefix.positionUnder("dlg_info");*/
	if(!event){
		this.container.style.left=(document.viewport.getWidth()/2-this.container.getWidth()/2)+"px"; 
		this.container.style.top=(document.viewport.getHeight()/2-this.container.getHeight()/2)+"px";
	}
	//this.iefix.setBounds(document.viewport.getDimensions());
	//this.iefix.setBounds({top:0,left:0});
};
Dialog.info=function(event,onclose){
	var that=this;
	if(!this.container){
		this.init(event);
	}
	if(onclose)this.onclose=onclose;
	this.container.show();
	if(event){
		this.setBounds(event);
	}
	if(!IE || IE>=7)
		this.shadowUnder();
	/*if(this.iefix){
		this.iefix.show();
		this.iefix.positionUnder("dlg_info");
	}*/
	if(event){
		document.observe("mousedown",function(e){
			if(that.container.visible()){
				if(!$(Event.element(e)).up('#dlg_info'))
					Dialog.close();  
			}
		});
	}
};
Dialog.close=function(onclose){
	if(this.container){
		this.setFooter("");
		this.setMsg("");
		this.container.hide();
	}
	if(this.shadow)
		this.shadow.hide();
	if(this.onclose){
		this.onclose();
		this.onclose=null;
	}
};
//END Dialog

//Shirm
var Shirm=Class.create({
	  
	  initialize: function(insertion,position,offset,cls,iefix) {
		/*if(ie){
			this.element = new Element("iframe", {
			  "class": "dlg_overlay",
			  "src": "#",
			  "frameborder": 0
			});
		}else{*/
						
		/*};*/
		var cls=cls?cls: "dlg_overlay";
		this.element=new Element("div",{ "class": cls	});
		this.iefix=iefix;
		this.position=position? position: "absolute";
		this.offset=offset?offset:"cumulative";
		var insertion=insertion? insertion: $$("body")[0];
		insertion.insert(this.element);
		this.element.hide();
	  },
	  hide: function() {
		this.element.hide();
		return this;
	  },
	
	  show: function() {
		this.element.show();
		return this;
	  },
	  
	  positionUnder: function(element) {
		var that=this;
		var element = $(element);
		if(this.offset=="positioned")
			offset = element.positionedOffset();
		else
			offset = element.cumulativeOffset();
		dimensions = element.getDimensions();
		
		style = {
		  left: offset[0] + 'px',
		  top: offset[1] + 'px',
		  postion:that.position,
		  width: dimensions.width + 'px',
		  height: dimensions.height + 'px',
		  zIndex: element.getStyle('zIndex') - 1
		};
		this.element.setStyle(style).show();
	
		return this;
	  },
	  positionOver: function(element) {
		var that=this;
		var element = $(element);
		if(this.offset=="positioned")
			offset = element.positionedOffset();
		else
			offset = element.cumulativeOffset();
		dimensions = element.getDimensions();
		if(IE &&  IE< 7 && this.iefix){
			var parent=element.offsetParent;
			offset[1]=$(parent).cumulativeOffset()[1];
		}
		style = {
		  left: offset[0] + 'px',
		  top: offset[1] + 'px',
		  postion:that.position,
		  width: dimensions.width + 'px',
		  height: dimensions.height + 'px',
		  zIndex: element.getStyle('zIndex') + 1
		};
		this.element.setStyle(style).show();
	
		return this;
	  },
	
	  setBounds: function(bounds) {
		for (prop in bounds) {
		  bounds[prop] += 'px';
		}
		this.element.setStyle(bounds);
		return this;
	  },

	  destroy: function() {
		if (this.element)
		  this.element.remove();
	
		return this;
	  }
});
//END Shirm

//CalendarModel
var CalendarModel=Class.create({
								  
	appointments:null,
	appointments_short:null,
	appointments_long:null,
	controller:false,
	initialize: function(controller){
		this.appointments=new Object();
		this.appointments_short=new Object();
		this.appointments_long=new Object();
		this.controller=controller;
	},
	
	getAppointmentDays:function(){
		var appointment_days=new Object();
		appointment_days=new Object();
		var date= new Date();
		if(this.controller.calendar!=null)
			date.setTime(this.controller.calendar.date.getTime());
		date.setDate(1);
		var w=date.getWeekNumber();
		date.setMonth(0);
		date.setDate(((w-1)*7)+this.calendar.firstDayOfWeek-1);
		 if(!appointment_days[date.getFullYear()])
			appointment_days[date.getFullYear()]=new Object();
		 if(!appointment_days[date.getFullYear()][date.getMonth()])
			appointment_days[date.getFullYear()][date.getMonth()]=new Object();
		for(var i=1;i<=42;i++){
			date.setDate(date.getDate()+1);
			for(d in this.appointments){
				date.setHours(0);
				date.setMinutes(0);
				date.setSeconds(0);
				date.setMilliseconds(0);
				var a=date.getTime();
				var ftemp=new Date();
				ftemp.setTime(this.appointments[d].from_date.getTime());
				var ttemp=new Date();
				ttemp.setTime(this.appointments[d].to_date.getTime());
				ftemp.setHours(0);
				ftemp.setMinutes(0);
				ttemp.setHours(23);
				ttemp.setMinutes(59);
				ttemp.setSeconds(59);
				ttemp.setMilliseconds(999);
				var f=ftemp.getTime();
				var t=ttemp.getTime();
				if(( a> f && a < t) || (a == t || a ==f)){
				 if(!appointment_days[date.getFullYear()])
				 	appointment_days[date.getFullYear()]=new Object();
				 if(!appointment_days[date.getFullYear()][date.getMonth()])
				 	appointment_days[date.getFullYear()][date.getMonth()]=new Object();
				 appointment_days[date.getFullYear()][date.getMonth()][date.getDate()]=date.getDate();
				}
			}
		 }
		return appointment_days;
	},
	reset:function(){
		this.appointments=new Object();
		this.appointments_short=new Object();
		this.appointments_long=new Object();
	},
	parseData:function(transport){
		//try{
			if (transport.responseText){
				this.appointments=transport.responseText.evalJSON();
				for(i in this.appointments){
					var temp=Date.parseDate(this.appointments[i].from_date,"%Y/%m/%d %k:%M");
					this.appointments[i].from_date=new Date(temp.getTime());
					var temp=Date.parseDate(this.appointments[i].to_date,"%Y/%m/%d %k:%M");
					this.appointments[i].to_date=new Date(temp.getTime());
					this.appointments[i]=new Appointment(this.appointments[i],this.controller);
					var tf=this.appointments[i].from_date;
					var tt=this.appointments[i].to_date;
					if(tf.toDateString()==tt.toDateString()
						&&!(tf.getHours()==0 && tf.getMinutes()==0 &&  tt.getHours()==23 && tt.getMinutes()==59)){
						this.appointments_short[i]=this.appointments[i];
					}
					else{
						this.appointments_long[i]=this.appointments[i];
					}
				}
			}
		/*}catch(e){
			Dialog.info(e.name+"<br/>"+transport.responseText);
		};*/
	}
})
//END CalendarModel

// DayView
var dayView=Class.create({	
	container:null,
	controller:null,
	calendar:null,
	table:null,
	hoverlays:false,
	hwidth:55,
	
	destroyOverlays:function(){
		if(this.ov1){
			try{
				this.ov1.destroy();
				this.ov1=null;
			}catch(e){return}
		}
	},
	setHOverlays:function(elm){
		var that=this;
		if(!this.ov1){
			
			var daycont=$(this.controller.calid+'_day_content');
			this.ov1=new Shirm(daycont,"relative","positioned");
			document.observe("mousemove",function(e){
				if(!that.hoverlays)
					return;
				Event.stop(e);
				try{
					var daytable=$(that.controller.calid+'_daytable');
					var elmleftoffset=that.ov1.element.cumulativeOffset()[0];
					var elmleftPositionedoffset=that.ov1.element.positionedOffset()[0];
					var elmwidth=that.ov1.element.getWidth();
					var contleftoffset=daytable.cumulativeOffset()[0];
					var contwidth=daytable.getWidth();
					var xpos=e.pointerX();
					var ypos=e.pointerY();
				}catch(exc){return}
				if(xpos<=that.ov1.leftoffset)
					that.ov1.left=true;
				else if(xpos>=that.ov1.leftoffset+that.hwidth)
					that.ov1.left=false;
				if(!that.ov1.left && that.ov1.leftoffset!=elmleftoffset){
					that.ov1.element.style.left=that.ov1.leftPositionedoffset+"px";
					elmleftPositionedoffset=that.ov1.leftPositionedoffset;
					elmleftoffset=that.ov1.leftoffset;
				}else if(that.ov1.left){
					var diff=(elmleftoffset+elmwidth)-(that.ov1.leftoffset+that.hwidth);
					if(diff>0){
						that.ov1.element.style.width=elmwidth-diff+"px";
						elmwidth=that.ov1.element.getWidth();
					}
				}
				if(xpos<elmleftoffset){
					var offleft=elmleftoffset-that.hwidth*(Math.ceil((elmleftoffset-xpos)/that.hwidth));
					var width=elmwidth+that.hwidth*(Math.ceil((elmleftoffset-xpos)/that.hwidth));
					if(offleft>contleftoffset){
						that.ov1.element.style.left=(elmleftPositionedoffset-that.hwidth*(Math.ceil((elmleftoffset-xpos)/that.hwidth)))+"px";
						that.ov1.element.style.width=width+"px";
					}
				}else if(xpos>elmleftoffset && that.ov1.left && xpos>elmleftoffset+that.hwidth){
					var width=elmwidth-that.hwidth*(Math.floor((xpos-elmleftoffset)/that.hwidth));
					var offleft=elmleftoffset+that.hwidth*(Math.floor((xpos-elmleftoffset)/that.hwidth));
					if(offleft<contleftoffset+contwidth){
						that.ov1.element.style.left=(elmleftPositionedoffset+that.hwidth*(Math.floor((xpos-elmleftoffset)/that.hwidth)))+"px";
						if(width>=that.hwidth){
							that.ov1.element.style.width=width+"px";
						}
					}
				}else if(xpos>elmleftoffset && xpos>elmleftoffset+elmwidth && !that.ov1.left){
					var width=elmwidth+that.hwidth*(Math.ceil((xpos-(elmleftoffset+elmwidth))/that.hwidth));
					if(elmleftoffset+width<=contleftoffset+contwidth){
						that.ov1.element.style.width=width+"px";
					}
				}else if(xpos>elmleftoffset && xpos<elmleftoffset+elmwidth && !that.ov1.left){
					if(xpos<=(elmleftoffset+elmwidth-that.hwidth)){
						var width=elmwidth-that.hwidth*(Math.floor(((elmleftoffset+elmwidth)-xpos)/that.hwidth));
						if(width>=that.hwidth){
							that.ov1.element.style.width=width+"px";
						}
					}
				}
			});
			document.observe("mouseup",function(event){
				if(that.hoverlays){
					var diff=Math.round(that.ov1.element.getWidth()/that.hwidth)-1;
					that.controller.seldate2=new Date(that.controller.seldate1.getTime());
					if(that.ov1.element.cumulativeOffset()[0]>=that.ov1.leftoffset)
						that.controller.seldate2.setHours(that.controller.seldate2.getHours()+diff);
					else if(that.ov1.element.cumulativeOffset()[0]<that.ov1.leftoffset)
						that.controller.seldate2.setHours(that.controller.seldate2.getHours()-diff);
					if(that.controller.seldate1>that.controller.seldate2)
						that.controller.seldate1.setMinutes(59);
					else
						that.controller.seldate2.setMinutes(59);
					that.controller.showQuickForm(event,function(){that.destroyOverlays()});
					that.hoverlays=false;
				}
			});
		}
		var date=new Date(this.controller.seldate1.getTime());
		this.ov1.date=date;
		this.ov1.date2=date;
		var id=this.controller.calid+"_hour_"+date.getHours();
		this.ov1.positionOver(id);
		this.ov1.leftoffset=this.ov1.element.cumulativeOffset()[0];
		this.ov1.leftPositionedoffset=this.ov1.element.positionedOffset()[0];
		this.ov1.element.style.zIndex=5;
	},
	
	makeTable:function(){
		var that=this;
		var cw=this.controller.width-1;
		var ch=this.controller.height;
		var table='<div id="'+this.controller.calid+'_daytable" class="daytable" style="width:'+cw+'px;height:'+ch+'px">';
			table+='<div id="'+this.controller.calid+'_daytable_hd" class="daytable_hd" style="width:'+cw+'px;height:'+(ch*0.2)+'px"></div>';
			table+='<div class="hours_scroll_h" align="left" style="width:'+(cw-2)+'px; float:left" id="'+this.controller.calid+'_dscroll_track_h">'
					+'<div id="'+this.controller.calid+'_dscroll_h" class="scroll_h"><div class="side moreleft">&nbsp;</div>'
					+'<div class="side moreright">&nbsp;</div></div></div>';
			table+='<div class="daytable_body" style="height:'+(ch-(ch*0.2)-17)+'px;width:'+(cw-17)+'px;">';
			table+='<div class="day_content" id="'+this.controller.calid+'_day_content">';
					table+='<div class="hours">';
					for (var i=0;i<=23; i++){
						table+="<div height='15px' class='hournr'>"+i+":00</div>";
					};
					table+='</div>';
					table+='<div class="hours">';
					for (var i=0;i<=23; i++){
						table+="<div class='hour hour_h' id='"+this.controller.calid+"_hour_"+i+"'>&nbsp;</div>";
					};
					table+='</div>';
			table+="</div>";
			table+="</div>";
		table+='<div class="hours_scroll_v" align="left" id="'+this.controller.calid+'_dscroll_track_v" style="height:'+(ch-(ch*0.2)-17)+'px;"><div id="'+this.controller.calid+'_dscroll_v" class="scroll_v"><div class="stop">&nbsp;</div><div class="sbottom">&nbsp;</div></div></div>';
		table+='</div>';
		this.table=table;
		this.container.update("");
		this.container.insert(this.table);
		var box = $(this.controller.calid+'_day_content');
		var strackh=$(this.controller.calid+'_dscroll_track_h');
		if(!this.contheight)this.contheight=box.getHeight();
		
			this.slh=new Control.Slider(this.controller.calid+'_dscroll_h',strackh, {
			  range: $R(0, strackh.getWidth()),
			  sliderValue: 0,
			  onSlide: function(value) {
				if(strackh.getWidth()<box.getWidth()){
					var pos=-((box.getWidth()+16-strackh.getWidth())*((value*100)/strackh.getWidth())/100);
					box.setStyle({ left: pos + 'px'});
				}
			  },
			  onChange: function(value) { 
			  	if(strackh.getWidth()<box.getWidth()){
					var pos=-((box.getWidth()+16-strackh.getWidth())*((value*100)/strackh.getWidth())/100);
					box.setStyle({ left: pos + 'px'});
				}
			  }
			});
			this.slh.setValue(strackh.getWidth()/2);
		
		var strackv=$(this.controller.calid+'_dscroll_track_v');
		this.slv=new Control.Slider(this.controller.calid+'_dscroll_v',strackv, {
		  range: $R(0, strackv.getHeight()),
		  axis:'vertical',
		  sliderValue: 0,
		  onSlide: function(value) {
			if(strackv.getHeight()<box.getHeight()){
				var pos=-((box.getHeight()-strackv.getHeight())*((value*100)/strackv.getHeight())/100);
				box.setStyle({ top: pos + 'px'});
			}
		  },
		  onChange: function(value) { 
			if(strackv.getHeight()<box.getHeight()){
				var pos=-((box.getHeight()-strackv.getHeight())*((value*100)/strackv.getHeight())/100);
				box.setStyle({ top: pos + 'px'});
			}
		  }
		});
		if($(this.controller.calid+'_day_content').getWidth()<=$$('#'+this.container.id+' div.daytable_body')[0].getWidth()){
			$(this.controller.calid+'_dscroll_h').style.visibility="hidden";
		}
		if(this.controller.isEditable){
			var date=new Date(this.calendar.date.getTime());
			date.setHours(0);
			date.setMinutes(0);
			var hours=$$('#'+this.container.id+' div.hour');
			hours.each(function(hdiv){
				hdiv.date=new Date(date.getTime());
				var sbmt=new Element('input',{'type':'button','value':DSLang('Save')});
				sbmt.observe("click",function(){
							that.controller.createAppointment($(that.controller.id+'_quick_app_title').value);
				});
				hdiv.observe("mousedown",function(event){
											if(event)
												Event.stop(event);
											that.controller.seldate1=new Date(this.date.getTime());
											that.hoverlays=true;
											that.setHOverlays(this);
											});
				date.setHours(date.getHours()+1);
			});
			var date=new Date(this.calendar.date.getTime());
			date.setHours(0);
			date.setMinutes(0);
			$(this.controller.calid+'_daytable_hd').observe("click",function(event){
				if(event)
					Event.stop(event);
				that.controller.seldate1=new Date(date.getTime());
				that.controller.seldate2=new Date(date.getTime());
				that.controller.seldate2.setHours(23);
				that.controller.seldate2.setMinutes(59);
				that.controller.showQuickForm(event);
			})
		}
	},
	
	
	setDay:function(obj,date,matrix){
		var owner=this.controller.owners[obj.owner_id];
		if(owner && owner.show==1){
			var ld="<div class='side'></div>";
			var sings="";
			if(obj.from_date.toDateString()!=date.toDateString()){
				ld="<div class='side moreleft'></div>";
			}else{
				if(obj.isActive=="Maybe" ||obj.isActive=="Unconfirmed")
					sings="? ";
			};
			var rd="<div class='side'></div>";
			if(obj.to_date.toDateString()!=date.toDateString()){
				rd="<div class='side moreright'></div>";
			};
					
			var div=new Element('div',{"class": "appointment", "style":"position:relative"}).update(ld+"<div class='appointment_title'><div class='text'>"+sings+obj.what+"</div></div>"+rd);
			var that=obj;
			var daytable=$(this.controller.calid+'_daytable_hd');
			var i=0;
			for(i; i<matrix.length;i++){
				if(matrix[i]==null)break;
			};
			div.style.width=daytable.getWidth()-16+"px";
			div.observe('click', function(event){that.show(event)});
			matrix[i]=true;
			daytable.insert(div);
			if(obj.isActive=="Cancelled")
				div.style.textDecoration="line-through";
			div.style.backgroundColor=this.controller.owners[obj.owner_id].color;
		}
	},

	setHour:function(obj,date,matrix){
		var owner=this.controller.owners[obj.owner_id];
		if(owner && owner.show==1){
			var ld="<div class='side'></div>";
			var rd="<div class='side'></div>";
			var sings="";
			if(obj.isActive=="Maybe" ||obj.isActive=="Unconfirmed")
					sings="? ";
			var hourdiv=$(this.controller.calid+'_hour_'+obj.from_date.getHours());
			var div=new Element('div',{"class": "appointment","align":"left"}).update(ld+"<div class='appointment_title'><div class='spacer'></div><div class='text'>"+sings+obj.what+"</div></div>"+rd);
			var that=obj;
			div.observe('click', function(event){that.show(event)});
			var left=hourdiv.positionedOffset()[0];
			var mins=((obj.to_date.getHours()-obj.from_date.getHours())*60)+(obj.to_date.getMinutes()-obj.from_date.getMinutes());
			var mw=hourdiv.getWidth()/60;
			var lm=obj.from_date.getMinutes()*mw;
			var w=Math.ceil(mw*mins);
			var a=Math.ceil(left+lm);
			var e=a+w;
			var pos=0;
			for(var i=0; i<matrix.length;i++){
				var b=false;
				for(var j=0;j<matrix[i].length;j++){
					var a2=matrix[i][j][0];
					var e2=matrix[i][j][1];
					if((a<a2 && e>a2)||
					   (a>a2 && a<e2)||
					   (a==a2)||
					   (e==e2)
					   ){
						pos=i+1;
						b=false;
						break;
					}
					else{
						b=true;
					}
				}
				if(b) break;
			};
			
			if(!matrix[pos])matrix.push(new Array());
			matrix[pos].push([a,e]);
			new Insertion.After(hourdiv,div);
			var top=hourdiv.positionedOffset()[1];
			div.style.top=(top+(16*pos))+"px";
			div.style.width=w+"px";
			div.style.left=a+"px";
			if(obj.isActive=="Cancelled")
				div.style.textDecoration="line-through";
			div.style.backgroundColor=this.controller.owners[obj.owner_id].color;
			var h=top+(16*pos)+div.getHeight();
			if(this.contheight<h)
				$(this.controller.calid+'_day_content').style.height=h+"px";
		}
	},

	initElements:function(){
		this.calendar=this.controller.calendar;
		var date=new Date();
		date.setTime(this.calendar.date.getTime());
		var obj=this.controller.model.appointments_short;
		var matrix=new Array();
		$(this.controller.calid+'_day_content').style.height=this.contheight+"px";
		for(ap in obj){
			if(obj[ap].isEqualsDay(date)){
				this.setHour(obj[ap],date,matrix);
			}
		};
		var hd=$(this.controller.calid+"_hour_0").positionedOffset()[1]+3;
		for (var i=0;i<=23; i++){
			$(this.controller.calid+'_hour_'+i).style.height=$(this.controller.calid+'_day_content').getHeight()-hd+"px";
		};
		var obj=this.controller.model.appointments_long;
		var matrix=new Array();
		for(ap in obj){
			if(obj[ap].isEqualsDay(date)){
				this.setDay(obj[ap],date,matrix);
			}
		}
	},

	show:function(container, controller){
		this.container=container;
		this.controller=controller? controller: null;
		this.calendar=this.controller.calendar;
		this.makeTable();
		this.initElements();
	}
})
// END DayView


// MonthView
var monthView=Class.create({
	container:null,
	controller:null,
	calendar:null,
	divs:null,
	overlays:false,
	sarray:null,

	destroyOverlays:function(){
		try{
			this.ov1.destroy();
			this.ov1=null;
		}catch(e){return}
		try{
			this.ov2.destroy();
			this.ov2=null;
		}catch(e){return}
		try{
			this.ov3.destroy();
			this.ov3=null;
		}catch(e){return}
	},
	setOverlays:function(elm){
		var that=this;
		if(!this.ov1){
			var divmonth=$$('#'+this.container.id+' .div_month')[0];
			this.ov1=new Shirm(null,null,null,null,true);
			this.ov2=new Shirm(null,null,null,null,true);
			this.ov3=new Shirm(null,null,null,null,true);
			document.observe("mousemove",function(e){
				if(!that.overlays)
					return;
				Event.stop(e);
				try{
					var elmleftoffset=that.ov1.element.cumulativeOffset()[0];
					var elmtopoffset=that.ov1.element.cumulativeOffset()[1];
					var contleftoffset=divmonth.cumulativeOffset()[0];
					var conttopoffset=divmonth.cumulativeOffset()[1];
					var contwidth=divmonth.getWidth();
					var contheight=divmonth.getHeight();
					var elmwidth=that.ov1.element.getWidth();
					var xpos=e.pointerX();
					var ypos=e.pointerY();
				}catch(exc){return}
				if(xpos>=contleftoffset && xpos<=contleftoffset+contwidth && ypos>=conttopoffset && ypos<=conttopoffset+contheight){
					if(xpos<=that.ov1.leftoffset)
						that.ov1.left=true;
					else if(xpos>=that.ov1.leftoffset+that.daywidth)
						that.ov1.left=false;
					if(ypos<=that.ov1.topoffset){
						that.ov1.top=true;
						that.ov1.bottom=false;
					}else if(ypos>=that.ov1.topoffset+that.dayheight){
						that.ov1.top=false;
						that.ov1.bottom=true;
					}else{
						that.ov1.top=false;
						that.ov1.bottom=false;
					}
					
					if(that.ov1.bottom || that.ov1.top){
						if(that.ov1.bottom){
							if(elmleftoffset!=that.ov1.leftoffset){
								that.ov1.element.style.left=that.ov1.leftoffset+"px";
								elmleftoffset=that.ov1.leftoffset;
							}
							if(that.ov2.element.visible() && that.ov2.element.cumulativeOffset()[1]<elmtopoffset)
								that.ov2.hide();
							if(that.ov3.element.visible() && that.ov3.element.cumulativeOffset()[1]<elmtopoffset)
								that.ov3.hide();
						}else{
							var diff=(elmleftoffset+elmwidth)-(that.ov1.leftoffset+that.daywidth);
							if(diff>0){
								that.ov1.element.style.width=elmwidth-diff+"px";
								elmwidth=that.ov1.element.getWidth();
							}
							if(that.ov2.element.visible() && that.ov2.element.cumulativeOffset()[1]>elmtopoffset)
								that.ov2.hide();
							if(that.ov3.element.visible() && that.ov3.element.cumulativeOffset()[1]>elmtopoffset)
								that.ov3.hide();
						}
					}else{
						if(!that.ov1.left && that.ov1.leftoffset!=elmleftoffset){
							that.ov1.element.style.left=that.ov1.leftoffset+"px";
							elmleftoffset=that.ov1.leftoffset;
						}else if(that.ov1.left){
							var diff=(elmleftoffset+elmwidth)-(that.ov1.leftoffset+that.daywidth);
							if(diff>0){
								that.ov1.element.style.width=elmwidth-diff+"px";
								elmwidth=that.ov1.element.getWidth();
							}
						}
					}
					if(!that.ov1.top && !that.ov1.bottom){
						that.ov2.hide();
						that.ov3.hide();
						if(xpos<elmleftoffset){
							var offleft=elmleftoffset-that.daywidth;
							if(offleft>=contleftoffset){
								that.ov1.element.style.left=offleft+"px";
								var width=elmwidth+that.daywidth;
								that.ov1.element.style.width=width+"px";
							}
						}else if(xpos>elmleftoffset && that.ov1.left && xpos>elmleftoffset+that.daywidth){
							var width=elmwidth-that.daywidth;
							var offleft=elmleftoffset+that.daywidth;
							if(offleft<contleftoffset+contwidth){
								that.ov1.element.style.left=offleft+"px";
								if(width>=that.daywidth){
									that.ov1.element.style.width=width+"px";
								}
							}
						}else if(xpos>elmleftoffset && xpos>elmleftoffset+elmwidth && !that.ov1.left){
							var width=elmwidth+that.daywidth;
							if(elmleftoffset+width<=contleftoffset+contwidth){
								that.ov1.element.style.width=width+"px";
							}
						}else if(xpos>elmleftoffset && xpos<elmleftoffset+elmwidth && !that.ov1.left){
							if(xpos<=(elmleftoffset+elmwidth-that.daywidth)){
								var width=elmwidth-that.daywidth;
								if(width>=that.daywidth){
									that.ov1.element.style.width=width+"px";
								}
							}
						}
					}else if(that.ov1.top){
						if(!that.ov2.element.visible()){
							if(!that.ov1.left){
								that.ov2.element.style.width=((contleftoffset+contwidth)-(elmleftoffset+elmwidth)+that.daywidth)+"px";
								that.ov2.element.style.left=(elmleftoffset+elmwidth-that.daywidth)+"px";
							}else{
								that.ov2.element.style.width=((contleftoffset+contwidth)-(elmleftoffset))+"px";
								that.ov2.element.style.left=(elmleftoffset)+"px";
							}
							that.ov2.element.style.top=(elmtopoffset-that.dayheight)+"px";
							if(!that.ov1.left){
								that.ov1.element.style.width=that.daywidth+"px";
								elmwidth=that.ov1.element.getWidth();
								that.ov1.element.style.left=that.ov1.leftoffset+"px";
								elmleftoffset=that.ov1.leftoffset;
							}
							that.ov2.show();
							var width=elmleftoffset-contleftoffset+elmwidth;
							if(elmleftoffset>contleftoffset){
								that.ov1.element.style.width=width+"px";
								that.ov1.element.style.left=contleftoffset+"px";
							}
						}else{
							var elm2leftoffset=that.ov2.element.cumulativeOffset()[0];
							var elm2width=that.ov2.element.getWidth();
							var elm2topoffset=that.ov2.element.cumulativeOffset()[1];
							if(ypos<=elm2topoffset && elm2topoffset>=conttopoffset+that.dayheight){
								if(!that.ov3.element.visible()){
									that.ov3.element.style.left=(contleftoffset)+"px";
									that.ov3.element.style.top=(elmtopoffset-that.dayheight)+"px";
									that.ov3.element.style.width=contwidth+"px";
									that.ov3.element.style.height=that.dayheight+"px";
									that.ov3.show();
								}else{
									that.ov3.element.style.height=(that.ov3.element.getHeight()+that.dayheight)+"px";
									that.ov3.element.style.top=(that.ov3.element.cumulativeOffset()[1]-that.dayheight)+"px";
								}
								that.ov2.element.style.top=(elm2topoffset-that.dayheight)+"px";
								elm2topoffset=that.ov2.element.cumulativeOffset()[1];
							}else if(ypos>elm2topoffset+that.dayheight){
								if(elm2topoffset+that.dayheight <= elmtopoffset){
									if(that.ov3.element.visible()){
										if(that.ov3.element.getHeight()-that.dayheight>=that.dayheight){
											that.ov3.element.style.height=(that.ov3.element.getHeight()-that.dayheight)+"px";
											that.ov3.element.style.top=(that.ov3.element.cumulativeOffset()[1]+that.dayheight)+"px";
										}
										else
											that.ov3.hide();
									}
									that.ov2.element.style.top=(elm2topoffset+that.dayheight)+"px";
									elm2topoffset=that.ov2.element.cumulativeOffset()[1];
								}else{
									that.ov2.hide();
									return;
								}
							}
							if(xpos<elm2leftoffset){
								var offleft=elm2leftoffset-that.daywidth;
								if(offleft>=contleftoffset){
									that.ov2.element.style.left=offleft+"px";
									var width=elm2width+that.daywidth;
									that.ov2.element.style.width=width+"px";
								}
							}else if(xpos>elm2leftoffset && xpos>elm2leftoffset+that.daywidth){
								var width=elm2width-that.daywidth;
								var offleft=elm2leftoffset+that.daywidth;
								if(offleft<contleftoffset+contwidth){
									that.ov2.element.style.left=offleft+"px";
									if(width>=that.daywidth){
										that.ov2.element.style.width=width+"px";
									}
								}
							}
						}
					}else if(that.ov1.bottom){
						if(!that.ov2.element.visible() && elmtopoffset+that.dayheight<=conttopoffset+contheight-that.dayheight){
							if(!that.ov1.left)
								that.ov2.element.style.width=((elmleftoffset+elmwidth)-contleftoffset)+"px";
							else
								that.ov2.element.style.width=((elmleftoffset+that.daywidth)-contleftoffset)+"px";
							that.ov2.element.style.left=(contleftoffset)+"px";
							that.ov2.element.style.top=(elmtopoffset+that.dayheight)+"px";
							if(that.ov1.left){
								that.ov1.element.style.width=that.daywidth+"px";
								elmwidth=that.ov1.element.getWidth();
								that.ov1.element.style.left=that.ov1.leftoffset+"px";
								elmleftoffset=that.ov1.leftoffset;
							}
							that.ov2.show();
							var width=contwidth+contleftoffset-elmleftoffset;
							if(elmleftoffset+width<=contleftoffset+contwidth){
								that.ov1.element.style.width=width+"px";
							}
						}else if(that.ov2.element.visible()){
							var elm2leftoffset=that.ov2.element.cumulativeOffset()[0];
							var elm2width=that.ov2.element.getWidth();
							var elm2topoffset=that.ov2.element.cumulativeOffset()[1];
							if(ypos>=elm2topoffset+that.dayheight && elm2topoffset+that.dayheight<=conttopoffset+contheight-that.dayheight){
								if(!that.ov3.element.visible()){
									that.ov3.element.style.left=(contleftoffset)+"px";
									that.ov3.element.style.top=(elmtopoffset+that.dayheight)+"px";
									that.ov3.element.style.width=contwidth+"px";
									that.ov3.element.style.height=that.dayheight+"px";
									that.ov3.show();
								}else{
									that.ov3.element.style.height=(that.ov3.element.getHeight()+that.dayheight)+"px";
								}
								that.ov2.element.style.top=(elm2topoffset+that.dayheight)+"px";
								elm2topoffset=that.ov2.element.cumulativeOffset()[1];
							}else if(ypos<=elm2topoffset){
								if(elm2topoffset-that.dayheight >= elmtopoffset+that.dayheight){
									if(that.ov3.element.visible()){
										if(that.ov3.element.getHeight()-that.dayheight>=that.dayheight)
											that.ov3.element.style.height=(that.ov3.element.getHeight()-that.dayheight)+"px";
										else
											that.ov3.hide();
									}
									that.ov2.element.style.top=(elm2topoffset-that.dayheight)+"px";
									elm2topoffset=that.ov2.element.cumulativeOffset()[1];
								}else{
									that.ov2.hide();
									return;
								}
							}
							if(xpos>elm2leftoffset && xpos>elm2leftoffset+elm2width){
								var width=elm2width+that.daywidth;
								if(elm2leftoffset+width<=contleftoffset+contwidth){
									that.ov2.element.style.width=width+"px";
								}
							}else if(xpos>elm2leftoffset && xpos<elm2leftoffset+elm2width){
								if(xpos<=(elm2leftoffset+elm2width-that.daywidth)){
									var width=elm2width-that.daywidth;
									if(width>=that.daywidth){
										that.ov2.element.style.width=width+"px";
									}
								}
							}
						}
					}
				}
			});
			document.observe("mouseup",function(event){
				if(that.overlays){
					var diff=Math.round(that.ov1.element.getWidth()/that.daywidth)-1;
					if(that.ov2.element.visible())
						diff+=Math.round(that.ov2.element.getWidth()/that.daywidth);
					if(that.ov3.element.visible()){
						diff+=Math.round(that.ov3.element.getWidth()/that.daywidth)*Math.round(that.ov3.element.getHeight()/that.dayheight);
					}
					that.controller.seldate2=new Date(that.controller.seldate1.getTime());
					if(that.ov1.element.cumulativeOffset()[0]>=that.ov1.leftoffset)
						that.controller.seldate2.setDate(that.controller.seldate2.getDate()+diff);
					else if(that.ov1.element.cumulativeOffset()[0]<that.ov1.leftoffset)
						that.controller.seldate2.setDate(that.controller.seldate2.getDate()-diff);
					that.controller.seldate2.setHours(23);
					that.controller.seldate2.setMinutes(59);
					that.controller.showQuickForm(event,function(){that.destroyOverlays()});
					that.overlays=false;
				}
			});
		}
		var date=new Date(this.controller.seldate1.getTime());
		var id=this.controller.calid+'_div_day_'+date.getDate()+"_"+date.getMonth();
		this.ov1.positionOver(id);
		this.ov2.positionOver(id);
		this.ov3.positionOver(id);
		this.ov2.hide();
		this.ov3.hide();
		this.ov1.leftoffset=this.ov1.element.cumulativeOffset()[0];
		this.ov1.topoffset=this.ov1.element.cumulativeOffset()[1];
		this.ov2.leftoffset=this.ov2.element.cumulativeOffset()[0];
		this.ov2.topoffset=this.ov2.element.cumulativeOffset()[1];
		this.ov3.leftoffset=this.ov3.element.cumulativeOffset()[0];
		this.ov3.topoffset=this.ov3.element.cumulativeOffset()[1];
	},
	getElem:function(elem,date,matrix,long,mday){
		var actday=date.getDate();
		var actmonth=date.getMonth();
		var that=this;
		var owner=this.controller.owners[elem.owner_id];
		if(owner && owner.show==1){
			elem.divs[date.getWeekNumber()]=elem.divs[date.getWeekNumber()]? elem.divs[date.getWeekNumber()]: new Object();
			if(elem.divs[date.getWeekNumber()][elem.id]){
				div=elem.divs[date.getWeekNumber()][elem.id][0];
				matrix[mday][elem.divs[date.getWeekNumber()][elem.id][1]]=true;
				div.style.width=(div.getWidth()+this.daywidth)+"px";
				if(elem.to_date.toDateString()==date.toDateString()){
					var rd="<div class='side'></div>";
					div.update(div.innerHTML+rd);
				}
				else if(date.getDay()==0){
					var rd="<div class='side moreright' style='width:"+div.getWidth()+"px'></div>";
					div.update(div.innerHTML+rd);
				}
			}
			else{
				var i=1;
				var maxapp=Math.floor(this.dayheight/17);
				for(i; i<=maxapp;i++){
					if(!matrix[mday][i]){
						matrix[mday][i]=true;
						break;
					}
				};
				var daydiv=$(this.controller.calid+'_div_day_'+actday+'_'+actmonth);
				if (i>maxapp-1){
					if($(this.controller.calid+'_div_day_'+actday+'_'+actmonth+'_more')==null){
						var div=new Element('div',{"id":this.controller.calid+'_div_day_'+actday+'_'+actmonth+'_more',"class":"appointment"}).update("<div class='appointment_title'><div class='text more'>"+DSLang('more')+"</div></div>");
						var dt=new Date(date.getTime());
						var tmpdate=new Date(date.getTime());
						div.observe("click",function(event){
						  that.controller.showAll(tmpdate,event);
						 });
						new Insertion.After($$('#'+this.container.id+' .div_month')[0],div);
						if(IE && IE<7){
							var parent=daydiv.offsetParent;
							var topOffset=$(parent).cumulativeOffset()[1];
							div.style.top=((topOffset)+((i)*16)-3)+"px";
							div.style.left=(daydiv.cumulativeOffset()[0])+"px";
							div.style.width=(daydiv.getWidth())+"px";
						}else{
							div.style.top=((daydiv.cumulativeOffset()[1])+((i)*16)-3)+"px";
							div.style.left=(daydiv.cumulativeOffset()[0])+"px";
							div.style.width=(daydiv.getWidth())+"px";
						}
					}
				}
				else{
					var div=new Element('div',{"class": "appointment"});
					var elm=elem;
					div.observe('click', function(event){elm.show(event)});
					new Insertion.After($$('#'+this.container.id+' .div_month')[0],div);
					if(IE && IE<7){
						var parent=daydiv.offsetParent;
						var topOffset=$(parent).cumulativeOffset()[1];
						div.style.top=((topOffset)+((i)*16)-3)+"px";
						div.style.left=(daydiv.cumulativeOffset()[0])+"px";
						div.style.width=(daydiv.getWidth())+"px";
					}else{
						div.style.top=((daydiv.cumulativeOffset()[1])+((i)*16)-3)+"px";
						div.style.left=(daydiv.cumulativeOffset()[0])+"px";
						div.style.width=(daydiv.getWidth())+"px";
					}
					if(long){
						div.style.backgroundColor=this.controller.owners[elem.owner_id].color;
						var ld="<div class='side'></div>";
						if(elem.from_date.toDateString()!=date.toDateString())
							ld="<div class='side moreleft'></div>";
						if(elm.isActive=="Maybe" ||elm.isActive=="Unconfirmed")
							div.update(ld+"<div class='appointment_title'><div class='text'>? "+elem.what+"</div></div>");
						else
							div.update(ld+"<div class='appointment_title'><div class='text'>"+elem.what+"</div></div>");
					}
					else{
						div.style.color=this.controller.owners[elem.owner_id].color;
						if(elm.isActive=="Maybe" ||elm.isActive=="Unconfirmed")
							div.update("<div class='appointment_title'><div class='text'>? "+elm.from_date.print("%H:%M")+" "+elem.what+"</div></div>");
						else
							div.update("<div class='appointment_title'><div class='text'>"+elm.from_date.print("%H:%M")+" "+elem.what+"</div></div>");
					};
					if(elem.to_date.toDateString()==date.toDateString()){
						var rd="<div class='side'></div>";
						div.update(div.innerHTML+rd);
					}
					else if(date.getDay()==0){
						var rd="<div class='side moreright' style='width:"+div.getWidth()+"px'></div>";
						div.update(div.innerHTML+rd);
					}
					if(elm.isActive=="Cancelled")
						div.style.textDecoration="line-through";
					elem.divs[date.getWeekNumber()][elem.id]=new Array(2);
					elem.divs[date.getWeekNumber()][elem.id][0]=div;
					elem.divs[date.getWeekNumber()][elem.id][1]=i;
					var tmpdate=new Date(date.getTime());
					var j=(mday-(Math.floor(mday/7)*7));
					if(mday==7)j=7;
					if(j==0)j=7;
					var tpmJ=j;
					for(j;j<=7;j++){
						if(tmpdate>elem.to_date)
							break;
						matrix[mday+(j-tpmJ)][elem.divs[date.getWeekNumber()][elem.id][1]]=true;
						tmpdate.setDate(tmpdate.getDate()+1);
					}
				}
			}
		}
	},
	initElements:function(){
		var obj=this.controller.model.appointments_long;
		var matrix=new Array(43);
		for(i=0; i<matrix.length; i++){
			matrix[i]=new Array(Math.floor(this.dayheight/16));
		};
		var date = new Date(this.calendar.date.getTime());
		date=date.setFirstWKDay(this.calendar.firstDayOfWeek);
		date.setHours(0);
		date.setMinutes(0);
		date.setSeconds(0);
		for(d in this.controller.model.appointments){
			this.controller.model.appointments[d].resetDivs();
		};
		
		for(i=1; i<=42; i++){
			for(d in obj){
				if(obj[d].isEqualsDay(date)){
					this.getElem(obj[d],date,matrix,true,i);
				}
			}
			date.setDate(date.getDate()+1);
		};
		
		var obj=this.controller.model.appointments_short;
		date = new Date(this.calendar.date.getTime());
		date.setHours(0);
		date.setMinutes(0);
		date.setSeconds(0);
		date=date.setFirstWKDay(this.calendar.firstDayOfWeek);
		for(i=1; i<=42; i++){
			for(d in obj){
				if(obj[d].from_date.toDateString()==date.toDateString()){
					this.getElem(obj[d],date,matrix,false,i);
				}
			}
			date.setDate(date.getDate()+1);
		};
	},
	
	makeTable:function(){
		var that=this;
		var date = new Date(this.calendar.date.getTime());
		date=date.setFirstWKDay(this.calendar.firstDayOfWeek);
		var cw=this.controller.width-1;
		var ch=this.controller.height;
		var dayw=Math.floor(cw/7);
		var dayh=Math.floor((ch-17)/6);
		this.dayheight=dayh;
		this.daywidth=dayw;
		var fullh=dayh*6;
		var fullw=dayw*7;
		if(IE && IE < 7)
			fullw=fullw+2;
		var dayrows=$(this.controller.calContainer).getElementsByClassName('daysrow');
			var daynames=$(this.controller.calContainer).getElementsByClassName('daynames')[0].childElements();
			var table="<div class='grid' style='width:"+fullw+"px; height:"+(fullh+17)+"px'>";
			for(var i=1; i<=daynames.length-1;i++){
						table+='<div class="dayname" style="width:'+(dayw)+'px;">'+daynames[i].innerHTML+'</div>';
				};
			table+= '<div style="width:'+fullw+'px; height:'+(fullh)+'px;" >';
			for(i=0; i<dayrows.length; i++){
				table+='<div style="width:'+fullw+'px; height:'+(dayh)+'px;">';
				
				for(var j=1; j<=dayrows[i].childElements().length-1;j++){
						table+='<div style="width:'+(dayw)+'px; height:'+(dayh)+'px; float:left;" class="';
						if(dayrows[i].childElements()[j].hasClassName('othermonth')){
							table+='othermonth';
						}
						table+='">';
							table+='<div class="day_number">'+dayrows[i].childElements()[j].innerHTML+'</div>';
						table+='</div>';
				};
				table+='</div>';
			};
			table+='</div>';
			table+='<div class="grid_line_h" style="width:'+fullw+'px; height:1px;left:0px;top:'+((dayh)*0+17)+'px"></div>';
			table+='<div class="grid_line_h" style="width:'+fullw+'px; height:1px;left:0px;top:'+((dayh)*1+17)+'px"></div>';
			table+='<div class="grid_line_h" style="width:'+fullw+'px; height:1px;left:0px;top:'+((dayh)*2+17)+'px"></div>';
			table+='<div class="grid_line_h" style="width:'+fullw+'px; height:1px;left:0px;top:'+((dayh)*3+17)+'px"></div>';
			table+='<div class="grid_line_h" style="width:'+fullw+'px; height:1px;left:0px;top:'+((dayh)*4+17)+'px"></div>';
			table+='<div class="grid_line_h" style="width:'+fullw+'px; height:1px;left:0px;top:'+((dayh)*5+17)+'px"></div>';
			
			table+='<div class="grid_line_v" style="width:1px; height:'+(fullh+17)+'px;left:'+((dayw)*1-1)+'px;top:0px"></div>';
			table+='<div class="grid_line_v" style="width:1px; height:'+(fullh+17)+'px;left:'+((dayw)*2-1)+'px;top:0px"></div>';
			table+='<div class="grid_line_v" style="width:1px; height:'+(fullh+17)+'px;left:'+((dayw)*3-1)+'px;top:0px"></div>';
			table+='<div class="grid_line_v" style="width:1px; height:'+(fullh+17)+'px;left:'+((dayw)*4-1)+'px;top:0px"></div>';
			table+='<div class="grid_line_v" style="width:1px; height:'+(fullh+17)+'px;left:'+((dayw)*5-1)+'px;top:0px"></div>';
			table+='<div class="grid_line_v" style="width:1px; height:'+(fullh+17)+'px;left:'+((dayw)*6-1)+'px;top:0px"></div>';
			/*+'<div class="number" style="height:'+(((ch-15)/6)-16)+'px;"></div>'
									+'<div class="number" style="height:'+(((ch-15)/6)-16)+'px;"></div>'
									+'<div class="number" style="height:'+(((ch-15)/6)-16)+'px;"></div>'
									+'<div class="number" style="height:'+(((ch-15)/6)-16)+'px;"></div>'
									+'<div class="number" style="height:'+(((ch-15)/6)-16)+'px;"></div>'
									+'<div class="number" style="height:'+(((ch-15)/6)-16)+'px;"></div>'*/
			table+="</div>";
			var lft=IE? 0:2;
			table+= '<div class="div_month" style="width:'+fullw+'px; height:'+(ch-17)+'px;top:'+(-fullh)+'px">';
			for(i=0; i<dayrows.length; i++){
				table+='<div class="div_month_row" >';
				for(var j=1; j<=dayrows[i].childElements().length-1;j++){
					table+='<div class="day" style="width:'+(dayw)+'px; height:'+dayh+'px;" id="'+this.controller.calid+'_div_day_'+date.getDate()+"_"+date.getMonth()+'"></div>';
					date.setDate(date.getDate()+1);
				};
				table+='</div>';
			};
			table+='</div>';
			this.container.update("");
			this.container.insert(table);
			if(this.controller.isEditable){
				var days=$$('#'+this.container.id+' .day');
				date = new Date(this.calendar.date.getTime());
				date=date.setFirstWKDay(this.calendar.firstDayOfWeek);
				days.each(function(daydiv){
					daydiv.date=new Date(date.getTime());
					daydiv.observe("mousedown",function(event){
						if(event)
							Event.stop(event);
						that.controller.seldate1=new Date(this.date.getTime());
						that.controller.seldate1.setHours(0);
						that.controller.seldate1.setMinutes(0);
						that.overlays=true;
						that.setOverlays(this);
					});
					date.setDate(date.getDate()+1);
				});
			}
	},

	show:function(container, controller){
		this.container=container;
		this.controller=controller? controller: null;
		this.calendar=this.controller.calendar;
		this.makeTable();
		this.initElements();
		}
});
//this.controller.timer=new Date();
//alert(new Date()-this.controller.timer);
// END MonthView

// WeekView
var weekView=Class.create({
	container:null,
	controller:null,
	calendar:null,
	doverlays:false,
	sarray:null,
	hoverlays:false,
	hwidth:55,

	destroyOverlays:function(){
		if(this.ov1){
			try{
				this.ov1.destroy();
				this.ov1=null;
			}catch(e){return}
		}
		if(this.ov2){
			try{
				this.ov2.destroy();
				this.ov2=null;
			}catch(e){return}
		}
	},
	setHOverlays:function(elm){
		var that=this;
		if(!this.ov1){
			var tweek=$$('.tweek_hours')[0];
			var weekcont=$$('.week_content')[0];
			this.ov1=new Shirm(weekcont,"relative","positioned");
			document.observe("mousemove",function(e){
				if(!that.hoverlays)
					return;
				Event.stop(e);
				try{
					var elmleftoffset=that.ov1.element.cumulativeOffset()[0];
					var elmleftPositionedoffset=that.ov1.element.positionedOffset()[0];
					var elmwidth=that.ov1.element.getWidth();
					var contleftoffset=tweek.cumulativeOffset()[0];
					var contwidth=tweek.getWidth();
					var xpos=e.pointerX();
					var ypos=e.pointerY();
				}catch(exc){return}
				if(xpos<=that.ov1.leftoffset)
					that.ov1.left=true;
				else if(xpos>=that.ov1.leftoffset+that.hwidth)
					that.ov1.left=false;
				if(!that.ov1.left && that.ov1.leftoffset!=elmleftoffset){
					that.ov1.element.style.left=that.ov1.leftPositionedoffset+"px";
					elmleftPositionedoffset=that.ov1.leftPositionedoffset;
					elmleftoffset=that.ov1.leftoffset;
				}else if(that.ov1.left){
					var diff=(elmleftoffset+elmwidth)-(that.ov1.leftoffset+that.hwidth);
					if(diff>0){
						that.ov1.element.style.width=elmwidth-diff+"px";
						elmwidth=that.ov1.element.getWidth();
					}
				}
				if(xpos<elmleftoffset){
					var offleft=elmleftoffset-that.hwidth*(Math.ceil((elmleftoffset-xpos)/that.hwidth));
					var width=elmwidth+that.hwidth*(Math.ceil((elmleftoffset-xpos)/that.hwidth));
					if(offleft>contleftoffset){
						that.ov1.element.style.left=(elmleftPositionedoffset-that.hwidth*(Math.ceil((elmleftoffset-xpos)/that.hwidth)))+"px";
						that.ov1.element.style.width=width+"px";
					}
				}else if(xpos>elmleftoffset && that.ov1.left && xpos>elmleftoffset+that.hwidth){
					var width=elmwidth-that.hwidth*(Math.floor((xpos-elmleftoffset)/that.hwidth));
					var offleft=elmleftoffset+that.hwidth*(Math.floor((xpos-elmleftoffset)/that.hwidth));
					if(offleft<contleftoffset+contwidth){
						that.ov1.element.style.left=(elmleftPositionedoffset+that.hwidth*(Math.floor((xpos-elmleftoffset)/that.hwidth)))+"px";
						if(width>=that.hwidth){
							that.ov1.element.style.width=width+"px";
						}
					}
				}else if(xpos>elmleftoffset && xpos>elmleftoffset+elmwidth && !that.ov1.left){
					var width=elmwidth+that.hwidth*(Math.ceil((xpos-(elmleftoffset+elmwidth))/that.hwidth));
					if(elmleftoffset+width<=contleftoffset+contwidth){
						that.ov1.element.style.width=width+"px";
					}
				}else if(xpos>elmleftoffset && xpos<elmleftoffset+elmwidth && !that.ov1.left){
					if(xpos<=(elmleftoffset+elmwidth-that.hwidth)){
						var width=elmwidth-that.hwidth*(Math.floor(((elmleftoffset+elmwidth)-xpos)/that.hwidth));
						if(width>=that.hwidth){
							that.ov1.element.style.width=width+"px";
						}
					}
				}
			});
			document.observe("mouseup",function(event){
				if(that.hoverlays){
					var diff=Math.round(that.ov1.element.getWidth()/that.hwidth)-1;
					that.controller.seldate2=new Date(that.controller.seldate1.getTime());
					if(that.ov1.element.cumulativeOffset()[0]>=that.ov1.leftoffset)
						that.controller.seldate2.setHours(that.controller.seldate2.getHours()+diff);
					else if(that.ov1.element.cumulativeOffset()[0]<that.ov1.leftoffset)
						that.controller.seldate2.setHours(that.controller.seldate2.getHours()-diff);
					if(that.controller.seldate1>that.controller.seldate2)
						that.controller.seldate1.setMinutes(59);
					else
						that.controller.seldate2.setMinutes(59);
					that.controller.showQuickForm(event,function(){that.destroyOverlays()});
					that.hoverlays=false;
				}
			});
		}
		var date=new Date(this.controller.seldate1.getTime());
		this.ov1.date=date;
		this.ov1.date2=date;
		var id=this.controller.calid+'_day_'+date.getDay()+"_hour_"+date.getHours();
		this.ov1.positionOver(id);
		this.ov1.leftoffset=this.ov1.element.cumulativeOffset()[0];
		this.ov1.leftPositionedoffset=this.ov1.element.positionedOffset()[0];
		this.ov1.element.style.zIndex=5;
	},
	setDOverlays:function(elm){
		var that=this;
		if(!this.ov2){
			var weekdays=$$('.week_days')[0];
			this.ov2=new Shirm(weekdays,"relative","positioned");
			document.observe("mousemove",function(e){
				if(!that.doverlays)
					return;
				Event.stop(e);
				try{
					var elmtopoffset=that.ov2.element.positionedOffset()[1];
					var conttopoffset=weekdays.positionedOffset()[1];
					var elmheight=that.ov2.element.getHeight();
					var contheight=weekdays.getHeight();
					var ypos=e.pointerY();
				}catch(exc){return}

				if(ypos<=that.ov2.topoffset){
					that.ov2.top=true;
				}else{
					that.ov2.top=false;
				}
				if(!that.ov2.top && that.ov2.topoffset!=elmtopoffset){
					that.ov2.element.style.top=that.ov2.topoffset+"px";
					elmtopoffset=that.ov2.topoffset;
				}else if(that.ov2.top){
					var diff=(elmtopoffset+elmheight)-(that.ov2.topoffset+that.dayheight);
					if(diff>0){
						that.ov2.element.style.height=elmheight-diff+"px";
						elmheight=that.ov2.element.getHeight();
					}
				}
				if(that.ov2.top){
					if(ypos<elmtopoffset){
						var offtop=elmtopoffset-that.dayheight;
						if(offtop>=conttopoffset){
							that.ov2.element.style.top=offtop+"px";
							var height=elmheight+that.dayheight;
							that.ov2.element.style.height=height+"px";
						}
					}else if(ypos>elmtopoffset && ypos>elmtopoffset+that.dayheight){
						var height=elmheight-that.dayheight;
						var offtop=elmtopoffset+that.dayheight;
						if(offtop<conttopoffset+contheight){
							that.ov2.element.style.top=offtop+"px";
							if(height>=that.dayheight){
								that.ov2.element.style.height=height+"px";
							}
						}
					}
				}else{
					if(ypos>elmtopoffset && ypos<elmtopoffset-that.dayheight+elmheight){
						var offtop=elmheight-that.dayheight;
						var height=elmheight-that.dayheight;
						that.ov2.element.style.height=height+"px";
					}else if(ypos>elmtopoffset+elmheight){
						var height=elmheight+that.dayheight;
						if(elmtopoffset+height<=conttopoffset+contheight){
							that.ov2.element.style.height=height+"px";
						}
					}
				}
			});
			document.observe("mouseup",function(event){
				if(that.doverlays){
					var diff=Math.round(that.ov2.element.getHeight()/that.dayheight)-1;
					that.controller.seldate2=new Date(that.controller.seldate1.getTime());
					if(that.ov2.element.positionedOffset()[1]>=that.ov2.topoffset)
						that.controller.seldate2.setDate(that.controller.seldate2.getDate()+diff);
					else if(that.ov2.element.positionedOffset()[1]<that.ov2.topoffset)
						that.controller.seldate2.setDate(that.controller.seldate2.getDate()-diff);
					that.controller.seldate2.setHours(23);
					that.controller.seldate2.setMinutes(59);
					that.controller.showQuickForm(event,function(){that.destroyOverlays()});
					that.doverlays=false;
				}
			});
		}
		var date=new Date(this.controller.seldate1.getTime());
		var id=this.controller.calid+'_week_day_'+date.getDay();
		this.ov2.positionOver(id);
		this.ov2.element.style.zIndex=5;
		this.ov2.topoffset=this.ov2.element.positionedOffset()[1];
	},
	initElements:function(){
		for(var w=0;w<7;w++){
			var date=new Date(this.firstdate.getTime()+(24*60*60*1000*w));
			var daynr=date.getDay();
			var obj=this.controller.model.appointments_short;
			var matrix=new Array(Math.floor(this.hourheight/16));
			for(ap in obj){
					if(obj[ap].isEqualsDay(date)){
						if(this.controller.owners[obj[ap].owner_id].show==1){
							this.setHour(obj[ap],daynr,date,matrix);
						}
					}
			}
		};
		for(var w=0;w<7;w++){
			var date=new Date(this.firstdate.getTime()+(24*60*60*1000*w));
			var daynr=date.getDay();
			var obj=this.controller.model.appointments_long;
			var matrix=new Array(Math.floor(this.hourheight/17));
			for(ap in obj){
				if(obj[ap].isEqualsDay(date)){
					this.setDay(obj[ap],daynr,date,matrix);
				}
			}
		}
	},
	setHour:function(obj,daynr,date,matrix){
		var owner=this.controller.owners[obj.owner_id];
		if(owner && owner.show==1){
			var ld="<div class='side'></div>";
			var rd="<div class='side'></div>";
			var sings="";
			if(obj.isActive=="Maybe" ||obj.isActive=="Unconfirmed")
					sings="? ";
			var hourdiv=$(this.controller.calid+'_day_'+daynr+'_hour_'+obj.from_date.getHours());
			var div=new Element('div',{"class": "appointment","align":"left"}).update(ld+"<div class='appointment_title'><div class='spacer'></div><div class='text'>"+sings+obj.what+"</div></div>"+rd);
			var that=obj;
			div.observe('click', function(event){that.show(event)});
			var left=hourdiv.positionedOffset()[0];
			var mins=((obj.to_date.getHours()-obj.from_date.getHours())*60)+(obj.to_date.getMinutes()-obj.from_date.getMinutes());
			var mw=hourdiv.getWidth()/60;
			var lm=obj.from_date.getMinutes()*mw;
			var w=Math.ceil(mw*mins);
			var a=Math.ceil(left+lm);
			var e=a+w;
			var pos=0;
			for(var i=0; i<matrix.length;i++){
				var b=false;
				if(!matrix[i])
					matrix[i]=new Array();
				for(var j=0;j<matrix[i].length;j++){
					var a2=matrix[i][j][0];
					var e2=matrix[i][j][1];
					if((a<a2 && e>a2)||
					   (a>a2 && a<e2)||
					   (a==a2)||
					   (e==e2)
					   ){
						pos=i+1;
						b=false;
						break;
					}
					else{
						b=true;
					}
				}
				if(b) break;
			};
			if(pos!=matrix.length){
				matrix[pos].push([a,e]);
				new Insertion.After(hourdiv,div);
				 var top=hourdiv.positionedOffset()[1];
				div.style.top=(top+(16*pos))+"px";
				div.style.width=w+"px";
				div.style.left=a+"px";
				if(obj.isActive=="Cancelled")
					div.style.textDecoration="line-through";
				div.style.backgroundColor=this.controller.owners[obj.owner_id].color;
			}
			else 
				this.setMoreDay(daynr,date);
		}
	},

	setDay:function(obj,daynr,date,matrix){
		var owner=this.controller.owners[obj.owner_id];
		if(owner && owner.show==1){
			var daytable=$(this.controller.calid+'_week_day_'+daynr);
			var i=0;
			for(i; i<=matrix.length;i++){
				if(matrix[i]==null)break;
			};
			if(i!=matrix.length){
				var ld="<div class='side'></div>";
				var sings="";
				if(obj.from_date.toDateString()!=date.toDateString()){
					ld="<div class='side moreleft'></div>";
				}else{
					if(obj.isActive=="Maybe" ||obj.isActive=="Unconfirmed")
						sings="? ";
				};
				var rd="<div class='side'>&nbsp;</div>";
				if(obj.to_date.toDateString()!=date.toDateString()){
					rd="<div class='side moreright'></div>";
				};
				var div=new Element('div',{"class": "appointment", "style":"position:absolute"}).update(ld+"<div class='appointment_title'><div class='text'>"+obj.what+"</div></div>"+rd);
				var that=obj;
				div.style.width=daytable.getWidth()-1+"px";
				div.observe('click', function(event){that.show(event)});
				matrix[i]=true;
				new Insertion.After(daytable,div);
				var top=daytable.positionedOffset()[1];
				div.style.top=(top+(16*i))+"px";
				if(obj.isActive=="Cancelled")
					div.style.textDecoration="line-through";
				div.style.backgroundColor=this.controller.owners[obj.owner_id].color;
			}
			else{
				if(!$(this.controller.calid+"_week_more_"+date.getDay())){
					var div=new Element('div',{"id":this.controller.calid+'_week_more_'+date.getDay(),"class": "more", "style":"position:absolute"}).update(DSLang("more"));
					new Insertion.After(daytable,div);
					div.style.width=daytable.getWidth()-1+"px";
					var top=daytable.positionedOffset()[1];
					div.style.top=(top+(16*i))+"px";
					this.setMore(daynr,date);
				}
			}
		}
	},
	setMoreDay:function(daynr,date){
			var t=this;
			var m=$(this.controller.calid+'_week_more_'+daynr+'_2');
			m.show();
			var dtemp=new Date(date.getTime());
			m.onclick=function(event){
				  t.controller.showAll(dtemp,event);
			};
	},
	setMore:function(daynr,date){
			var t=this;
			var m=$(this.controller.calid+'_week_more_'+daynr);
			var dtemp=new Date(date.getTime());
			m.observe("click",function(event){
				t.controller.showAll(dtemp,event);
			});
	},
	makeTable:function(){
		//try{
		var actdate=this.controller.calendar.date;
		var actday=actdate.getDay();
		if(actday==0)actday=7;
		var that=this;
		var firstdate=new Date(actdate.getTime()-(24*60*60*1000*(actday-1)));
		var lastdate=new Date(firstdate.getTime()+(24*60*60*1000*6));
		this.firstdate=firstdate;
		this.lastdate=lastdate;
		var from=firstdate.print("%a, %d. %b %Y");
		var to=lastdate.print("%a, %d. %b %Y");
		var cw=this.controller.width-1;
		var ch=this.controller.height;
		var hh=Math.floor((ch-36-8)/7);
		this.hourheight=hh;
		this.dayheight=hh+1;
		var table='<div class="tweek_days" style="height:'+ch+'px">';
			table+='<div class="week_nr" style="width:'+((cw-45)*0.2+42)+'px">'+from+'<br/>'+to+'</div>';
			table+='<div class="week_names">';
			for(var i=0;i<7;i++){
				var col="";
				var tmpdate=new Date(firstdate.getTime()+(24*60*60*1000*i));
				if(tmpdate.getDay()==0||tmpdate.getDay()==6)col="week_name_red";
				table+='<div class="week_name '+col+'"  style="height:'+hh+'px">'+Calendar._SDN[tmpdate.getDay()]+'</div>';
			};
			table+='</div>';
			table+='<div class="week_days">';
			for(var i=0;i<7;i++){
				var tmpdate=new Date(firstdate.getTime()+(24*60*60*1000*i));
				table+='<div id="'+this.controller.calid+'_week_day_'+tmpdate.getDay()+'" class="week_day"  style="height:'+hh+'px;width:'+(cw-45)*0.2+'px"></div>'
			
			};
			table+='</div>';
			table+='<div class="week_more">';
			for(var i=0;i<7;i++){
				var tmpdate=new Date(firstdate.getTime()+(24*60*60*1000*i));
				var moretext=DSLang('more').toArray();
				var mt="";
				moretext.each(function(e){
					mt+=e+"<br/>";
				});
				table+='<div class="week_daymore"  style="height:'+hh+'px"><div id="'+this.controller.calid+'_week_more_'+tmpdate.getDay()+'_2" style="display:none;height:'+hh+'px" class="moretext">'+mt+'</div></div>';
			};
			table+='</div>';
		table+='</div>';
		table+='<div class="tweek_hours" style="height:'+(hh*7+36+8)+'px;width:'+(cw-45)*0.8+'px">';
			table+='<div class="hours_scroll_h" align="left" id="'+this.controller.calid+'_wscroll_track"><div id="'+this.controller.calid+'_wscroll" class="scroll_h"><div class="side moreleft">&nbsp;</div><div class="side moreright">&nbsp;</div></div></div>';
			table+='<div class="tweek_hours2"  style="height:'+(ch-17)+'px;width:'+(cw-45)*0.8+'px">';
				table+='<div id="'+this.controller.calid+'_week_content" class="week_content">';
					table+='<div class="hours">';
					for(var i=0;i<24;i++){
						table+='<div class="hournr">'+i+':00</div>';
					};
					table+='</div>';
					for(var w=0;w<7;w++){
						table+='<div class="hours">';
						var tmpdate=new Date(firstdate.getTime()+(24*60*60*1000*w));
						for(var i=0;i<24;i++){
							table+='<div class="hour hour_w" id="'+this.controller.calid+'_day_'+tmpdate.getDay()+'_hour_'+i+'"  style="height:'+hh+'px"></div>';
						};
						table+='</div>';
					}
				table+='</div>';
			table+='</div>';
		table+='</div>'
		this.container.update("");
		this.container.insert(table);
		var box = $(this.controller.calid+'_week_content');
		var strack=$(this.controller.calid+'_wscroll_track');
		var sl=new Control.Slider(this.controller.calid+'_wscroll',strack, {
		  range: $R(0, strack.getWidth()),
		  sliderValue: 0,
		  onSlide: function(value) {
			var pos=-((box.getWidth()-strack.getWidth())*((value*100)/strack.getWidth())/100);
			box.setStyle({ left: pos + 'px'});
		  },
		  onChange: function(value) { 
		   var pos=-((box.getWidth()-strack.getWidth())*((value*100)/strack.getWidth())/100);
			box.setStyle({ left: pos + 'px'});
		  }
		});
		sl.setValue(strack.getWidth()/2);
		if(this.controller.isEditable){
			var date=new Date(firstdate.getTime());
			date.setHours(0);
			date.setMinutes(0);
			var hours=$$('#'+this.container.id+' div.hour');
			hours.each(function(hdiv){
				hdiv.date=new Date(date.getTime());
				var sbmt=new Element('input',{'type':'button','value':DSLang('Save')});
				sbmt.observe("click",function(){
							that.controller.createAppointment($(that.controller.id+'_quick_app_title').value);
				});
				hdiv.observe("mousedown",function(event){
											if(event)
												Event.stop(event);
											that.controller.seldate1=new Date(this.date.getTime());
											that.hoverlays=true;
											that.setHOverlays(this);
											});
				date.setHours(date.getHours()+1);
			});
			var date=new Date(firstdate.getTime());
			date.setHours(0);
			date.setMinutes(0);
			var days=$$('div.week_day');
			days.each(function(wddiv){
				wddiv.date=new Date(date.getTime());
				var sbmt=new Element('input',{'type':'button','value':DSLang('Save')});
				sbmt.observe("click",function(){
							that.controller.createAppointment($(that.controller.id+'_quick_app_title').value);
				});
				wddiv.observe("mousedown",function(event){
											if(event)
												Event.stop(event);
											that.controller.seldate1=new Date(this.date.getTime());
											that.controller.seldate1.setHours(0);
											that.controller.seldate1.setMinutes(0);
											that.doverlays=true;
											that.setDOverlays(this);
											});
				date.setDate(date.getDate()+1);
			});
		}
		//}catch(e){alert(e)};
		
	},

	show:function(container, controller){
		this.container=container;
		this.controller=controller? controller: null;
		this.calendar=this.controller.calendar;
		this.makeTable();
		//this.controller.timer=new Date();
		this.initElements();
		//alert(new Date()-this.controller.timer);
	}
});
// END WeekView

// Agendaview
var agendaView=Class.create({
	container:null,
	controller:null,
	calendar:null,

	initElements:function(){
		var cw=this.controller.width-1;
		var ch=this.controller.height;
		var date=new Date(this.calendar.date.getTime());
		var i=0;
		var maxcont=0;
		while(maxcont<42){
			if(i>=35)
				break;
			var obj=this.controller.model.appointments_long;
			var isexists=false;
			for(ap in obj){
					if(obj[ap].isEqualsDay(date)){
						if(this.controller.owners[obj[ap].owner_id].show==1){
							if(!isexists){
								var divcontainer=new Element('div',{'class':'agenda_day'}).update("\
									<div id='"+this.controller.calid+"_agenda_right_"+date.getDate()+"_"+date.getMonth()+"' class='agenda_right' style='width:"+(cw*0.2)+"px'></div>\
									<div id='"+this.controller.calid+"_agenda_left_"+date.getDate()+"_"+date.getMonth()+"' class='agenda_left' style='width:"+(cw*0.8)+"px'></div>");
								$(this.controller.calid+'_agenda_grid').insert(divcontainer);
								$(this.controller.calid+"_agenda_right_"+date.getDate()+"_"+date.getMonth()).update(obj[ap].from_date.print("%a %d.%m.%Y"));
								isexists=true;
							};
							this.setApp(obj[ap],date,true);
							i++;
						}
					}
			}
			var obj=this.controller.model.appointments_short;
			for(ap in obj){
					if(obj[ap].isEqualsDay(date)){
						if(this.controller.owners[obj[ap].owner_id].show==1){
							if(!isexists){
								var divcontainer=new Element('div',{'class':'agenda_day'}).update("\
									<div id='"+this.controller.calid+"_agenda_right_"+date.getDate()+"_"+date.getMonth()+"' class='agenda_right' style='width:"+(cw*0.2)+"px'></div>\
									<div id='"+this.controller.calid+"_agenda_left_"+date.getDate()+"_"+date.getMonth()+"' class='agenda_left' style='width:"+(cw*0.8)+"px'></div>");
								$(this.controller.calid+'_agenda_grid').insert(divcontainer);
								$(this.controller.calid+"_agenda_right_"+date.getDate()+"_"+date.getMonth()).update(obj[ap].from_date.print("%a %d.%m.%Y"));
								isexists=true;
							};
							this.setApp(obj[ap],date,false);
							i++;
						}
					}
			}
			maxcont++;
			date.setDate(date.getDate()+1);
		}
		if($(this.controller.calid+'_agenda_grid').innerHTML=="")
			$(this.controller.calid+'_agenda_grid').update("<h3 class='noevent'>"+DSLang("MessageNoEvents")+"</h3>");
	},
	setApp:function(obj,date,long){
		var ld="<div class='side'></div>";
		var rd="<div class='side'></div>";
		var that=obj;
		if(obj.isActive=="Maybe" ||obj.isActive=="Unconfirmed")
			sings="? ";
		var div=new Element('div',{"class": "appointment","align":"left", 'style':'position:static;margin-top:-1px;'});
		div.style.width=$(this.controller.calid+"_agenda_left_"+date.getDate()+"_"+date.getMonth()).getWidth()-1+"px";
		div.observe('click', function(event){that.show(event)});
		$(this.controller.calid+"_agenda_left_"+date.getDate()+"_"+date.getMonth()).insert(div);
		if(obj.isActive=="Cancelled")
				div.style.textDecoration="line-through";
		if(!long){
			div.update("<div class='appointment_title' style='position:static'><div class='text'>"+date.print("%H:%M")+" "+obj.what+"</div></div>");
			div.style.color=this.controller.owners[obj.owner_id].color;
		}
		else{
			div.update("<div class='appointment_title' style='position:static'><div class='text'>"+obj.what+"</div></div>");
			div.style.backgroundColor=this.controller.owners[obj.owner_id].color;
		}
	},
	makeTable:function(){
		var cw=this.container.getWidth();
		var ch=this.container.getHeight();
		var grid="<div id='"+this.controller.calid+"_agenda_grid' class='agenda_grid'  style='width:"+cw+"px;height:"+ch+"px'></div>";
		this.container.update("");
		this.container.insert(grid);
	},
	show:function(container, controller){
		this.container=container;
		this.controller=controller? controller: null;
		this.calendar=this.controller.calendar;
		this.makeTable();
		this.initElements();
	}
});
// END Agendaview

// CalendarView
var CalendarView=Class.create({
	
	container:null,
	controller:null,
	calendar:null,

	initialize:function(rcontainer, controller,container){
		this.container=rcontainer;
		this.controller=controller? controller: null;
		this.monthView=new monthView();
		this.dayView=new dayView();
		this.weekView=new weekView();
		this.agendaView=new agendaView();
		var that=this;
		var bool=false
		var linkdiv=new Element("div");
		if(!$(container+"_getdaylink")){
			linkdiv.insert("<a href='#' id='"+container+"_getdaylink"+"'>"+DSLang("Day")+"</a>&nbsp;&nbsp;");
			bool=true;
		}
		if(!$(container+"_getweeklink")){
			linkdiv.insert("<a href='#' id='"+container+"_getweeklink"+"'>"+DSLang("Week")+"</a>&nbsp;&nbsp;");
			bool=true;
		}
		if(!$(container+"_getmonthlink")){
			linkdiv.insert("<a href='#' id='"+container+"_getmonthlink"+"'>"+DSLang("Month")+"</a>&nbsp;&nbsp;");
			bool=true;
		}
		if(!$(container+"_getagendalink")){
			linkdiv.insert("<a href='#' id='"+container+"_getagendalink"+"'>"+DSLang("Agenda")+"</a>&nbsp;&nbsp;");
			bool=true;
		}
		if(!$(container+"_setdateminus")){
			linkdiv.insert("<a href='#' id='"+container+"_setdateminus"+"'>"+DSLang("back")+"</a>&nbsp;&nbsp;");
			bool=true;
		}
		if(!$(container+"_setdateplus")){
			linkdiv.insert("<a href='#' id='"+container+"_setdateplus"+"'>"+DSLang("next")+"</a>&nbsp;&nbsp;");
			bool=true;
		}
		if(!$(container+"_datetime")){
			linkdiv.insert("<span id='"+container+"_datetime"+"'></span>&nbsp;&nbsp;");
			bool=true;
		}
		if(bool=true){
			new Insertion.Before($(container),linkdiv);
			this.container.style.height=this.container.getHeight()-linkdiv.getHeight()+"px";
		}
		$(container+"_getdaylink").observe("click",function(event){
			 Event.stop(event);
			 that.controller.actAction=that.controller.GETFORDAY;
			 that.controller.refresh=true;
			 this.addClassName("selectedview");
			 $(container+"_getmonthlink").removeClassName("selectedview");
			 $(container+"_getagendalink").removeClassName("selectedview");
			 $(container+"_getweeklink").removeClassName("selectedview");
			 that.controller.showAppointments()
		 });
		$(container+"_getweeklink").observe("click",function(event){
			 Event.stop(event);
			 that.controller.actAction=that.controller.GETFORWEEK;
			 that.controller.refresh=true;
			 this.addClassName("selectedview");
			 $(container+"_getmonthlink").removeClassName("selectedview");
			 $(container+"_getagendalink").removeClassName("selectedview");
			 $(container+"_getdaylink").removeClassName("selectedview");
			 that.controller.showAppointments()
		 });
		$(container+"_getmonthlink").observe("click",function(event){
			 Event.stop(event);
			 that.controller.actAction=that.controller.GETFORMONTH;
			 that.controller.refresh=true;
			 this.addClassName("selectedview");
			 $(container+"_getagendalink").removeClassName("selectedview");
			 $(container+"_getweeklink").removeClassName("selectedview");
			 $(container+"_getdaylink").removeClassName("selectedview");
			 that.controller.showAppointments()
		 });
		$(container+"_getagendalink").observe("click",function(event){
			 Event.stop(event);
			 that.controller.actAction=that.controller.GETAGENDA;
			 that.controller.refresh=true;
			 this.addClassName("selectedview");
			 $(container+"_getmonthlink").removeClassName("selectedview");
			 $(container+"_getweeklink").removeClassName("selectedview");
			 $(container+"_getdaylink").removeClassName("selectedview");
			 that.controller.showAppointments()
		 });
		$(container+"_getmonthlink").addClassName("selectedview");
		$(container+"_getagendalink").removeClassName("selectedview");
		$(container+"_getweeklink").removeClassName("selectedview");
		$(container+"_getdaylink").removeClassName("selectedview");
		
		$(container+"_setdateminus").observe("click",function(event){
			 Event.stop(event);
			 that.controller.changeDate(-1);
		 });
		$(container+"_setdateplus").observe("click",function(event){
			 Event.stop(event);
			 that.controller.changeDate(1)
		 });
	},
	
	showForMonth:function(){
		this.monthView.show(this.container,this.controller);
	},
	
	showForDay:function(){
		this.dayView.show(this.container,this.controller);
		
	},
	showForWeek:function(){
		this.weekView.show(this.container,this.controller);
	},
	showAgenda:function(){
		this.agendaView.show(this.container,this.controller);
	}
});
// END CalendarView

// Appointment
var Appointment=Class.create({
							 
	id:null,
	what:null,
	where:null,
	owner_id:null,
	description:null,
	from_date: null,
	to_date:null,
	divs:null,
	isEditable: false,
	controller:null,
	contentWin:null,
	
	initialize: function(obj,controller) {
		this.id=obj.id;
		this.what=obj.what;
		this.owner_id=obj.owner_id;
		this.description=obj.description.split("\\n").join("\n");
		this.to_date=obj.to_date;
		this.isEditable=obj.isEditable;
		this.from_date=obj.from_date;
		this.isActive=obj.isActive;
		this.controller=controller;
		this.url=obj.url;
		this.divs=new Object();
	},
	
	isEqualsDay: function(date){
		var ftemp=new Date();
		ftemp.setTime(this.from_date.getTime());
		ftemp.setHours(0);
		ftemp.setMinutes(0);
		ftemp.setSeconds(0);
		ftemp.setMilliseconds(0);
		var ttemp=new Date();
		ttemp.setTime(this.to_date.getTime());
		ttemp.setHours(23);
		ttemp.setMinutes(59);
		ttemp.setSeconds(59);
		ttemp.setMilliseconds(999);
		var a=date.getTime();
		var f=ftemp.getTime();
		var t=ttemp.getTime();
		if(( a> f && a < t) || (a == t || a ==f)){
			return true;
		}
		return false;
	},
	
	resetDivs:function(){
		this.divs=new Object();
	},
	
	isEqualsHours:function(date){
		var ftemp=new Date();
		ftemp.setTime(this.from_date.getTime());
		var ttemp=new Date();
		ttemp.setTime(this.to_date.getTime());
		ftemp.setMinutes(0);
		ttemp.setMinutes(59);
		ttemp.setSeconds(59);
		ttemp.setMilliseconds(999);
		date.setHours(0);
		date.setMinutes(0);
		date.setSeconds(0);
		date.setMilliseconds(0);
		var a1=date.getTime();
		date.setHours(23);
		date.setMinutes(59);
		date.setSeconds(59);
		date.setMilliseconds(999);
		var a2=date.getTime();
		var f=ftemp.getTime();
		var t=ttemp.getTime();
		if(a1<= f && a2 >= t){
			return true;
		}
		return false;
	},
	isEqualsHour:function(date){
		var ftemp=new Date();
		ftemp.setTime(this.from_date.getTime());
		var ttemp=new Date();
		ttemp.setTime(this.to_date.getTime());
		ftemp.setMinutes(0);
		ttemp.setMinutes(59);
		ttemp.setSeconds(59);
		ttemp.setMilliseconds(999);
		var a=date.getTime();
		var f=ftemp.getTime();
		var t=ttemp.getTime();
		if(( a> f && a < t) || (a == t || a ==f)){
			return true;
		}
		return false;
	},
	
	showDetails:function(){
		/*if(this.details){
			$('adf_datails_'+this.id).innerHTML=DSLang('Details')+" "+DSLang('Close');
			Dialog.setMsg("<div style='padding:5px;'>"+this.msg_long+"</div>");
		}else{
			$('adf_datails_'+this.id).innerHTML=DSLang('Details');
			Dialog.setMsg("<div style='padding:5px;'>"+this.msg+"</div>");
		}*/
	},
	_getMsg:function(msg,event){
		what=this.what;
		var that =this;
		if(this.url)
			what="<a href='"+this.url+"' target='_blank' style='text-decoration:none;color:"+this.controller.owners[this.owner_id].color+"'>"+this.what+"</a>";
		if(!this.msg){
			this.msg="<h3 class='title' style='color:"+this.controller.owners[this.owner_id].color+"'>"+what+"</h3>\
			<div>"+msg+"</div>";
		}
		if(this.isEditable && this.controller.isEditable){
			Dialog.setFooter('<a href="#" id="adf_datails_'+this.id+'"></a>&nbsp;&nbsp;\
								  <a href="#" id="adf_delete_'+this.id+'">'+DSLang('delete')+'</a>&nbsp;&nbsp;\
								  <a href="#" id="adf_edit_'+this.id+'">'+DSLang('edit')+'</a>');
			$('adf_delete_'+this.id).observe("click",function(event){
									 Event.stop(event);
									 that.remove();									 
			});
			$('adf_edit_'+this.id).observe("click",function(event){
										 that.controller.editAppointment(that);
										 Dialog.close();
										 Event.stop(event);
			});
		}else{
			Dialog.setFooter('<a href="#" id="adf_datails_'+this.id+'"></a>&nbsp;&nbsp;');
		}
		this.details=false;
		$('adf_datails_'+this.id).observe("click",function(event){
										 //that.details=(that.details)? false:true;
										 Dialog.close();
										 Event.stop(event);
										 that.controller.showDetails(that);
										});
		$('adf_datails_'+this.id).innerHTML=DSLang('Details');
		Dialog.setMsg("<div style='padding:5px;'>"+this.msg+"</div>");
		Dialog.info(event);
	},
	show:function(event){
		if(event)
			Event.stop(event);
		var that=this;
		new Ajax.Request(that.controller.URL.quickview+that.id+"&owner_id="+that.owner_id,{
		  method: 'post',
		  evalScripts: true,
		  onComplete: function(transport) {
			that._getMsg(transport.responseText,event);
		  } 
		});
		/*var that=this;
		var fromstr="";
		var tostring="";
		if(this.from_date.print("%d.%m.%Y")!=this.to_date.print("%d.%m.%Y")){
			if(this.from_date.print("%H:%M")!="00:00" && this.to_date.print("%H:%M")!="23:59"){
				fromstr=this.from_date.print("%d.%m.%Y %H:%M");
				tostr=this.to_date.print(" - %d.%m.%Y %H:%M");
			}else{
				fromstr=this.from_date.print("%d.%m.%Y");
				tostr=this.to_date.print(" - %d.%m.%Y %H:%M");
			}
		}else if(this.from_date.print("%H:%M")!="00:00" && this.to_date.print("%H:%M")!="23:59"){
			fromstr=this.from_date.print("%d.%m.%Y %H:%M");
			tostr=this.to_date.print("- %H:%M");
		}else{
			fromstr=this.from_date.print("%d.%m.%Y");
			tostr="";
		}
		what=this.what;
		if(this.url)
			what="<a href='"+this.url+"' target='_blank' style='text-decoration:none;color:"+this.controller.owners[this.owner_id].color+"'>"+this.what+"</a>";
		if(!this.msg){
			this.msg="<h3 class='title' style='color:"+this.controller.owners[this.owner_id].color+"'>"+what+"</h3>\
				<div>"+fromstr+tostr+"</div>\
				<div>"+this.description+"</div>";
			}
		/*if(!this.msg_long){
			this.msg_long=this.msg+"<br/>"+this.description;
			}*/
		
		//this.showDetails();
	},
	
	remove:function(){
		var that=this;
		Dialog.setFooter('<a href="#" id="adf_delete_'+this.id+'">'+DSLang('delete')+'</a>&nbsp;&nbsp;\
								  <a href="#" id="adf_cancel_'+this.id+'">'+DSLang('Cancel')+'</a>&nbsp;&nbsp;');
		
		$("adf_delete_"+this.id).observe("click",function(e){
							Event.stop(e);
							that.controller.removeAppointment(that);
							Dialog.close();
							
		});
		$("adf_cancel_"+this.id).observe("click",function(event){
							Event.stop(event);
							that.show();
							
		});
		Dialog.setMsg(DSLang("alertdeleteevent"));
		Dialog.info();
	}
})
// END Appointment


// ColorPicker
var colorPickerClass=Class.create({
	
	onClickCallBack:null,
	event_elm:null,
	color_web:new Array(			
		'000000','000000','000000',  '000000','003300','006600','009900','00CC00','00FF00',  '330000','333300','336600','339900','33CC00','33FF00', '660000','663300','666600','669900','66CC00','66FF00',        
		'000000','333333','000000',  '000033','003333','006633','009933','00CC33','00FF33',  '330033','333333','336633','339933','33CC33','33FF33', '660033','663333','666633','669933','66CC33','66FF33',
		'000000','666666','000000',  '000066','003366','006666','009966','00CC66','00FF66',  '330066','333366','336666','339966','33CC66','33FF66', '660066','663366','666666','669966','66CC66','66FF66',
		'000000','999999','000000',  '000099','003399','006699','009999','00CC99','00FF99',  '330099','333399','336699','339999','33CC99','33FF99', '660099','663399','666699','669999','66CC99','66FF99',
		'000000','CCCCCC','000000',  '0000CC','0033CC','0066CC','0099CC','00CCCC','00FFCC',  '3300CC','3333CC','3366CC','3399CC','33CCCC','33FFCC', '6600CC','6633CC','6666CC','6699CC','66CCCC','66FFCC',
		'000000','FFFFFF','000000',  '0000FF','0033FF','0066FF','0099FF','00CCFF','00FFFF',  '3300FF','3333FF','3366FF','3399FF','33CCFF','33FFFF', '6600FF','6633FF','6666FF','6699FF','66CCFF','66FFFF',
		
		'000000','FFFFFF','000000',  '990000','993300','996600','999900','99CC00','99FF00',  'CC0000','CC3300','CC6600','CC9900','CCCC00','CCFF00', 'FF0000','FF3300','FF6600','FF9900','FFCC00','FFFF00',
		'000000','FF0000','000000',  '990033','993333','996633','999933','99CC33','99FF33',  'CC0033','CC3333','CC6633','CC9933','CCCC33','CCFF33', 'FF0033','FF3333','FF6633','FF9933','FFCC33','FFFF33',
		'000000','00FF00','000000',  '990066','993366','996666','999966','99CC66','99FF66',  'CC0066','CC3366','CC6666','CC9966','CCCC66','CCFF66', 'FF0066','FF3366','FF6666','FF9966','FFCC66','FFFF66',
		'000000','0000FF','000000',  '990099','993399','996699','999999','99CC99','99FF99',  'CC0099','CC3399','CC6699','CC9999','CCCC99','CCFF99', 'FF0099','FF3399','FF6699','FF9999','FFCC99','FFFF99',
		'000000','FFFF00','000000',  '9900CC','9933CC','9966CC','9999CC','99CCCC','99FFCC',  'CC00CC','CC33CC','CC66CC','CC99CC','CCCCCC','CCFFCC', 'FF00CC','FF33CC','FF66CC','FF99CC','FFCCCC','FFFFCC',
		'000000','00FFFF','000000',  '9900FF','9933FF','9966FF','9999FF','99CCFF','99FFFF',  'CC00FF','CC33FF','CC66FF','CC99FF','CCCCFF','CCFFFF', 'FF00FF','FF33FF','FF66FF','FF99FF','FFCCFF','FFFFFF'
	),
	color_calendar: new Array(
		'CC3333','DD4477','994499','6633CC','336699','3366CC','22AA99',
		'329262','109618','66AA00','AAAA11','D6AE00','EE8800','DD5511',
		'A87070','8C6D8C','627487','7083A8','5C8D87','898951','B08B59'
	),
	
	popup_cont:null,
	popup:null,
	
	initialize: function(params){
		var that=this;
		this.params=Object.extend({
		    container:null,
			useColor:"color_calendar",
			popupClass:'cp_container'
		}, params);
		this.popup_cont=new Element("div",{'style':'position:absolute;', 'id':'cp_container','class':that.params.popupClass});
		this.popup_cont.update("<div class='header'><a href='javascript: colorPicker.closePicker()'><img style='text-decoration:none;border:none' src='"+DSGlobalPath+"image/close1.png'></a><div>");
		var params=params? params: {};
		this.colors=eval("this."+this.params.useColor);
		this.popup=this.params.container? $(this.params.container):this.popup_cont;
		this.popup.appendChild(this.color_table());
		this.popup.hide();
		var that=this;
		document.body.appendChild(this.popup);
		document.observe("mousedown",function(e){
			if(that.popup.visible()){
				if(!$(Event.element(e)).up('#'+that.popup.id))
					that.popup.hide();  
			}
		});
	},
		
	select_color:function(color){
		this.closePicker();
		if(this.onClickCallBack){
			this.onClickCallBack(this.event_elm,color);
		}
		else {
			return false;
		}
	},
	closePicker:function(){
		this.popup.hide();
	},
	showPicker:function(event, callBack){
		this.onClickCallBack=callBack? callBack: this.onClickCallBack;
		this.event_elm=Event.element(event);
		this.popup.show();
		var left=Event.pointerX(event);
		var top=Event.pointerY(event);
		this.popup.style.left=left+"px";
		this.popup.style.top=top+"px";
		var clickX=event.clientX;
		var clickY=event.clientY;
		var contWidth=this.popup.getWidth();
		var contHeight=this.popup.getHeight();
		var viewWidth=document.viewport.getWidth();
		var viewHeight=document.viewport.getHeight();
		if(clickX+contWidth>=viewWidth)
			left=left-(contWidth-(viewWidth-clickX))-10;
		if(clickY+contHeight>=viewHeight)
			top=top-(contHeight-(viewHeight-clickY))-10;
		this.popup.style.left=left+"px";
		this.popup.style.top=top+"px";
		var s="";
	},
	color_table:function(){
		var tbl=new Element("div",{});
		var that=this;
		var tbl=new Element("div",{'id':'cp_colortable'});
		for (var i=0; i<this.colors.length;i++){
			var color = this.colors[i];//this.value[k] + this.value[l] + this.value[m];
				var td=new Element('div',{'class':'cp_td'});
				td.style.backgroundColor='#'+color;
				td.observe('click',function(){that.select_color(this.style.backgroundColor)});
				tbl.appendChild(td);
		}
		return tbl;
	}
});
var colorPicker;
Event.observe(window,'load',function(){
									 colorPicker=new colorPickerClass();
									 });

// END ColorPicker

Date.prototype.equalsToDay = function(date) {
	return ((this.getFullYear() == date.getFullYear()) &&
		(this.getMonth() == date.getMonth()) &&
		(this.getDate() == date.getDate()));
};
Date.prototype.setFirstWKDay = function(firstDay) {
	var firstDay=firstDay?firstDay:0;
	this.setDate(1);
	var thisday=this.getDay();
	thisday=thisday==0?7:thisday;
	var setDay=(-thisday)+firstDay;
	this.setDate(this.getDate()+setDay);
	return this;
};
DSSelectCalendar=Class.create({
	initialize:function(opt,isExtend){
		var that=this;
		var start_date=new Date();
		start_date.setMinutes(start_date.getMinutes()>=30?30:0);
		this.options=Object.extend({
		    start_date:start_date,
			field: "start_date",
			onSelect:function (calendar,date){
						if (calendar.dateClicked){calendar.callCloseHandler();}
						that.date.setDateOnly(calendar.date);
						if(that.options.empty)
							that.checkEmpty(calendar.date,that.options.field);
						else
							that.setValues();
						},
			disable:false,
			format:"%d.%m.%Y"		
		}, opt);
		this.field=$(this.options.field+"_view");
		this.date=this.options.start_date;
		this.initCalendar();
		if(!isExtend){
			this.field.observe("change",function(){that.valueChanged()});
			this.setValues(true);
			if(this.options.disable)
				this.switcher(true);
		}
	},
	valueChanged:function(){
		this.date=Date.parseDate(this.field.value,this.options.format);
		this.setValues();
	},
	switcher:function(init){
		if(!init){
			if(this.field.disabled){
				this.field.disabled=false;
			}else{
				this.field.disabled=true;
			}
		}
	},
	setValues:function(init){
		if(!init){
			this.field.value = this.date.print(this.options.format);
		}
		$(this.options.field).value = this.date.print("%Y-%m-%d");
	},
	initCalendar:function(){
		var field=$(this.options.field+"_view");
		var onClose=function(){field.blur()};
		this.getCalendar(this.options.field+"_view",this.options.start_date,this.options.format,this.options.empty,this.options.onSelect,onClose);
	},
	onEnterHandler:function(){
		//alert(window.calendar.element.id);
	},
	checkEmpty:function(date,field){
		var that=this;
		var tmp=Date.parseDate("1.1.1901","%d.%m.%Y");
		var actfiled=$(field+"_view");
		actfiled.value=date.print(this.options.format);
		this.date=date;
		this.setValues();
		if(tmp.equalsToDay(date)){
			actfiled.value=DSLang("nodate");
		}
	},
	getCalendar:function(field,date,format,empty,onselect, onclose){
		var f=$(field);
		f.isActive=false;
		var that=this;
		var tmp=Date.parseDate("1.1.1901","%d.%m.%Y");
		if(tmp.equalsToDay(date))
			date=new Date();
		Calendar.setup({
			inputField :  field,
			ifFormat :   format,
			"range": [1900, 2100],
			firstDay  : 1,
			eventName: 'focus',
			onClose: onclose,
			onSelect: onselect?function(calendar,date){
									f.isActive?(f.isActive=false):onselect(calendar,date);
								}:null,
			'date': date,
			showOthers: true,
			isPopup: true,
			zIndex: 5001,
			empty: empty,
			enableFirstDayChange: false
		 });
		f.observe('keypress',function(e){
			switch(e.keyCode){
				case  Event.KEY_UP: // KEY up
					this.isActive=false;	break;
				case Event.KEY_DOWN: // KEY down
					this.isActive=false;	break;
				case Event.KEY_RETURN: // KEY down
					this.isActive? that.onEnterHandler():null;
					this.isActive=false;	break;
				default:
					this.isActive=true;
			}
		});
		f.observe('blur',function(e){
			try{
				if(window.calendar){
					window.calendar.callCloseHandler();
					window.calendar.destroy();
					window.calendar=null;
				}
			}catch(e){}
		 });
		f.observe('mousedown',function(e){
			f.blur()
		});
		f.observe('mouseup',function(e){
			f.focus()
		});
		/*f.observe('click',function(e){
			alert("test");
		});*/
	}
});
DSSelectCalendar.Time=Class.create({
	initialize:function(){
		this.overflow=null;
		this.elpos=0;
		this.actElm=null;
		this.options=Object.extend({
		    callHandler:null,
			handlerOpt:null,
			ContClass:"DSSCTimeContainer",
			OptionClass:"DSSCOption",
			SelectedClass:"DSSCSelected",
			IntervalClass:"DSSCInterval",
			field:null
		},arguments[0]);
		var that=this;
		this.valuefield=this.options.field;
		this.options.field=$(this.options.field.id+"_view");
		this.options.field.observe("focus",function(e){that.show()});
		this.options.field.observe("keydown",function(e){that.keypress(e)});
		this.options.field.observe("keydown",function(e){that.keypress(e)});
		this.options.field.observe('blur',function(e){that.actElm.click();that.closeHandler(e)});
		this.options.field.observe('mouseup',function(e){
			try{
			this.focus();
			}catch(e){return}
		});
		document.observe("click",function(e){that.closeHandler(e)});
		this.getSelect();
	},
	_remove:function(){
		this.overflow?this.overflow.remove():null;
	},
	_init:function(overflow){
		this._remove();
		this.overflow=overflow;
	},
	show:function(){
		this.overflow.show();
		var that=this;
		this.elpos=-1;
		this.overflow.childElements()[0].childElements().find(function(s) {
					that.elpos++;
					return s.hasClassName(that.options.SelectedClass);
				});
		this.actElm.getHeight();
		this.t=this.actElm.getHeight();
		var p=(this.elpos<this.overflow.childElements()[0].childElements().length-3)?this.elpos-2:this.elpos;
		this.overflow.scrollTop=p*this.t;
	},
	setActive:function(elm){
		this.actElm? this.actElm.removeClassName(this.options.SelectedClass):null;
		elm.addClassName(this.options.SelectedClass);
		this.actElm=elm;
	},
	keypress:function(e){
		switch(e.keyCode){
			case  Event.KEY_UP: // KEY up
				this.overflow.show();
				this.elpos=this.elpos==0?this.elpos:this.elpos-1;
				var p=(this.elpos<this.overflow.childElements()[0].childElements().length-3)?this.elpos-2:this.elpos;
				this.overflow.scrollTop=p*this.t;
				this.setActive(this.overflow.childElements()[0].childElements()[this.elpos]);
				break;
			case Event.KEY_DOWN: // KEY down
				this.overflow.show();
				this.elpos=(this.elpos==(this.overflow.childElements()[0].childElements().length-1))?this.elpos:this.elpos+1;
				var p=(this.elpos>2)?this.elpos-2:0;
				this.overflow.scrollTop=p*this.t;
				this.setActive(this.overflow.childElements()[0].childElements()[this.elpos]);
				break;
			case Event.KEY_RETURN: // KEY down
				this.actElm.click();
				this.overflow.hide();
				break;
			default:
				this.overflow.hide();
		}
	},
	closeHandler:function(e){
		try{
			var tar=e.element();
			if(this.options.field!=tar){
				this.overflow.hide();
			}
		}catch(e){}
	},
	getSelect:function(){
		var overflow=new Element('div',{'class':this.options.ContClass});
		var div=new Element("div");
		var tmpdate=new Date();
		tmpdate.setHours(0);
		tmpdate.setMinutes(0);
		var that=this;
		for(var i=0; i<=47;i++){
			var e=new Element('div',{'class':this.options.OptionClass}).update(tmpdate.print("%H:%M"));
			var tmp=tmpdate.print("%H:%M");
			var tmp2=Date.parseDate("01.01.1901 "+this.options.field.value,"%d.%m.%Y %H:%M");
			tmp2.setMinutes(tmp2.getMinutes()>=30?30:0);
			tmp2=tmp2.print("%H:%M");
			tmp2==tmp?this.setActive(e):null;
			tmpdate.setMinutes(tmpdate.getMinutes()+30);
			e.click=function(){
				var h=that.options.field.value.substring(0,2);
				var m=that.options.field.value.substring(2,4);
				that.options.field.value=that.options.field.value.include(":")?that.options.field.value:h+":"+m;
				var tmp=Date.parseDate("01.01.1901 "+that.options.field.value,"%d.%m.%Y %H:%M");
				that.options.field.value=tmp.print("%H:%M");
				that.options.field.value=overflow.visible()?this.innerHTML:that.options.field.value;
				that.valuefield.value=that.options.field.value;
				that.options.callHandler? that.options.callHandler(that.options.handlerOpt):null;
			};
			e.observe("click",function(e){
				this.click();
				});
			e.observe("mouseover",function(){
				that.setActive(this);
				});
			div.insert(e);
		}
		overflow.insert(div);
		$$('body')[0].insert(overflow);
		overflow.style.left=this.options.field.cumulativeOffset()[0]-(overflow.getWidth()-this.options.field.getWidth())+"px";
		overflow.style.top=this.options.field.cumulativeOffset()[1]+this.options.field.getHeight()+"px";
		overflow.hide();
		this._init(overflow);
	},
	getInterval:function(date){
		var that=this;
		var overflow=new Element('div',{'class':this.options.ContClass+" "+this.options.IntervalClass});
		var div=new Element("div");
		var tmpdate=new Date(date.getTime());
		var h=tmpdate.getHours();
		t=new Array();
		for(var i=0; i<=47;i++){
			var e=new Element('div',{'class':'option'}).update(tmpdate.print("%H:%M")+" ("+(i/2)+" h)");
			e.time=tmpdate.print("%H:%M");
			var tmp=tmpdate.print("%H:%M");
			this.options.field.value==tmp?this.setActive(e):null;
			tmpdate.setMinutes(tmpdate.getMinutes()+30);
			e.click=function(){
				var h=that.options.field.value.substring(0,2);
				var m=that.options.field.value.substring(2,4);
				that.options.field.value=that.options.field.value.include(":")?that.options.field.value:h+":"+m;
				var tmp=Date.parseDate("01.01.1901 "+that.options.field.value,"%d.%m.%Y %H:%M");
				that.options.field.value=tmp.print("%H:%M");
				that.options.field.value=overflow.visible()?this.innerHTML.substring(0,5):that.options.field.value;
				that.valuefield.value=that.options.field.value;
				that.options.callHandler? that.options.callHandler(that.options.handlerOpt):null;
			};
			e.observe("click",function(e){
								this.click();
								});
			e.observe("mouseover",function(){
									that.setActive(this);
									});
			div.insert(e);
		}
		overflow.insert(div);
		$$('body')[0].insert(overflow);
		overflow.style.left=this.options.field.cumulativeOffset()[0]-(overflow.getWidth()-this.options.field.getWidth())+"px";
		overflow.style.top=this.options.field.cumulativeOffset()[1]+this.options.field.getHeight()+"px";
		overflow.hide();
		this._init(overflow);
	}
});
DSSelectCalendar.withTime=Class.create(DSSelectCalendar,{

	initialize:function($super,opt,isExtend){
		var that=this;
		this.time_select=null;
		$super(opt,true);
		this.options=Object.extend(this.options,{
		    time_field:"start_time",
			time_opt:null
		});
		this.options=Object.extend(this.options, arguments[1]);
		this.time=$(this.options.time_field);
		this.time_view=$(this.options.time_field+"_view");
		this.time_view.observe("change",this.setValues());
		if(!isExtend){
			this.setValues(true);
			if(this.options.disable)
				this.switcher(true);
		}
		var timeopt=Object.extend({field:this.time},this.options.time_opt);
		this.time_select=new DSSelectCalendar.Time(timeopt);
	},
	switcher:function($super,init){
		$super(init);
		if(!init){
			if(!$("disabled_"+this.options.time)){
				var e=new Element("input",{"type":"text","class":this.time.className,"id":"disabled_"+this.options.time});
				new Insertion.After(this.time,e);
				e.disable();
				e.hide();
			}
			e=$("disabled_"+this.options.time);
			if(!e.visible()){
				e.value=this.time.value;
				e.show();
				this.time.hide();
			}else{
				e.hide();
				this.time.show();
			}
		}
	},
	setValues:function($super,init){
		$super(init);
		this.date.setHours(this.time_view.value.substring(0,2));
		this.date.setMinutes(this.time_view.value.substring(3,5));
		this.time.value=this.time_view.value;
	}
});
DSSelectCalendar.Double=Class.create({
	initialize:function(obj,isExtend){
		var that=this;
		this.options=Object.extend({
			start_date:new Date(),
			field: "start_date",
			format:"%d.%m.%Y",
			errorClass: "DSSCError",
			end_date:new Date(),
			field_to: "end_date",
			empty2:false,
			disable_to:false,
			intervalDay: 0,
			errorHandler: 1
		},obj);
		obj.empty=that.options.empty;
		obj.onSelect=function (calendar,date){
						that.from.date.setDateOnly(calendar.date);
						if (calendar.dateClicked){calendar.callCloseHandler();}
						that.dateChanged("from")
						};
		this.from=new DSSelectCalendar(obj,true);
		var obj_to={
		    start_date:that.options.end_date,
			field: obj.field_to,
			empty: that.options.empty2,
			onSelect:function (calendar,date){
						that.to.date.setDateOnly(calendar.date);
						if (calendar.dateClicked){calendar.callCloseHandler();}
						that.dateChanged("to")
						},
			disable:that.options.disable_to,
			format:that.options.format		
		};
		this.to=new DSSelectCalendar(obj_to,true);
		this.field=$(this.options.field+"_view");
		this.field_to=$(this.options.field_to+"_view");
		this.field.observe("change",function(){that.valuesChanged("from");});
		this.field_to.observe("change",function(){that.valuesChanged("to")});
		this.errorcorrecter=this.options.errorHandler==1? this.correct1:this.correct2;
		if(!isExtend){
			this.setValues(true);
			if(this.options.disable){
				this.errorcorrecter=this.correct3;
				this.switcher(true);
			}
		}
	},
	checkEmpty:function(date,field){
		var that=this;
		var tmp=Date.parseDate("1.1.1901","%d.%m.%Y");
		var actfiled=$(field);
		actfiled.value=date.print("%Y-%m-%d");
		$(field+"_view").value=date.print(this.options.format);
		if(tmp.equalsToDay(date)){
			if(field==this.options.field)
				this.from.date=date;
			else
				this.to.date=date;
			$(field+"_view").value=DSLang("nodate");
			return true;
		}else{
			return false;
		}
	},
	switcher:function(init){
		this.from.switcher(init);
		if(this.options.disable_to)
			this.to.switcher(init);
	},
	setValues:function(init){
		this.from.setValues(init);
		this.to.setValues(init);
		
	},
	valuesChanged:function(f){
		this.from.date=Date.parseDate(this.field.value,this.options.format);
		this.to.date=Date.parseDate(this.field_to.value,this.options.format);
		this.dateChanged(f);
	},
	dateChanged:function(f) {
		if(f=="from"){
			var actfield=this.options.field;
			var actdate=this.from.date;
			var emptyCheck=this.options.empty;
		}
		else{
			var actfield=this.options.field_to;
			var actdate=this.to.date;
			var emptyCheck=this.options.empty2;
		}
		if(emptyCheck){
			if(!this.checkEmpty(actdate,actfield)){
				var tmp=Date.parseDate("1.1.1901","%d.%m.%Y");
				if(!tmp.equalsToDay(this.from.date) && !tmp.equalsToDay(this.to.date)){
					if(f=="from" && this.options.intervalDay!=0){
						this.to.date.setFullYear(this.from.date.getFullYear());
						this.to.date.setMonth(this.from.date.getMonth());
						this.to.date.setDate(this.from.date.getDate()+this.options.intervalDay);
					};
					this.setValues();
					this.errorcorrecter(f);
				}
			}else{
				this.field.removeClassName(this.options.errorClass);
				this.field_to.removeClassName(this.options.errorClass);
			}
		}else{
			if(f=="from" && this.options.intervalDay!=0){
				this.to.date.setFullYear(this.from.date.getFullYear());
				this.to.date.setMonth(this.from.date.getMonth());
				this.to.date.setDate(this.from.date.getDate()+this.options.intervalDay);
			};
			this.setValues();
			this.errorcorrecter(f);
		}
	},
	correct1:function (f){
		this.field_to.removeClassName(this.options.errorClass);
		this.field.removeClassName(this.options.errorClass);
		if(f=="from"){
			if(this.from.date>this.to.date){
				this.field_to.addClassName(this.options.errorClass);
			}
		}else{
			if(this.from.date>this.to.date){
				this.field.addClassName(this.options.errorClass);
			}
		}
		if((this.from.date.print(this.options.format)==this.field.value)
			||(this.to.date.print(this.options.format)==this.field_to.value))
			this.setValues();
	},
	correct2:function(f){
			if(!this.from.date.equalsTo(this.to.date)){
				if(f=="from"){
					if(this.from.date>this.to.date){
							this.to.date=new Date(this.from.date.getTime());
					}
				}else{
					if(this.from.date>this.to.date){
						this.from.date=new Date(this.to.date.getTime());
					}
				}
			}
			this.setValues();
	},
	correct3:function(f){
			if(!this.from.date.equalsTo(this.to.date)){
					if(this.from.date>this.to.date){
							this.to.date=new Date(this.from.date.getTime());
					}
			}
			this.setValues();
	}
});
DSSelectCalendar.DoubleWithTime=Class.create(DSSelectCalendar.Double,{
	
	initialize:function($super){
		$super(arguments[1],true);
		this.tmphours=-1;
		this.options=Object.extend(this.options,{
			time_field:"start_time",
			time_to_field:"end_time",
			time_opt1:null,
			empty2:false,
			time_opt2:null,
			interval:60,
			errorHandler: 1
		});
		this.options=Object.extend(this.options, arguments[1]);
		this.interval=this.options.interval;
		this.time=$(this.options.time_field);
		this.time_view=$(this.options.time_field+"_view");
		this.time_to=$(this.options.time_to_field);
		this.time_to_view=$(this.options.time_to_field+"_view");
		var that=this;
		this.time.observe("change",function(){that.valuesChanged("from")});
		this.time_to.observe("change",function(){that.valuesChanged("to")});
		this.errorcorrecter=this.options.errorHandler==1? this.correct1:this.correct2;
		this.setValues(true);
		this.initSelect();
		if(this.options.disable)
		{
			this.errorcorrecter=this.correct3;
			this.switcher(true);
		}
	},
	switcher:function($super,init){
		$super(init);
		if(!init){
			if(!$("disabled_"+this.options.time_field)){
				var e=new Element("input",{"type":"text","class":this.time.className,"id":"disabled_"+this.options.time_field});
				new Insertion.After(this.time,e);
				e.disable();
				e.hide();
			}
			e=$("disabled_"+this.options.time_field);
			if(!e.visible()){
				e.value=this.time.value;
				e.show();
				this.time.hide();
			}else{
				e.hide();
				this.time.show();
			};
			if(this.options.disable_to){
				if(!$("disabled_"+this.options.time_to_field)){
					var e=new Element("input",{"type":"text","class":this.time_to.className,"id":"disabled_"+this.options.time_to_field});
					new Insertion.After(this.time_to,e);
					e.disable();
					e.hide();
				}
				e=$("disabled_"+this.options.time_to_field);
				if(!e.visible()){
					e.value=this.time_to.value;
					e.show();
					this.time_to.hide();
				}else{
					e.hide();
					this.time_to.show();
				};
			}
		}
	},
	setValues:function($super,init){
		$super(init);
		this.time.value=this.from.date.print("%H:%M");
		this.time_to.value=this.to.date.print("%H:%M");
		this.time_view==this.from.date.print("%H:%M");
		this.time_to_view.value=this.to.date.print("%H:%M");
	},
	correct1:function (f){
		this.field_to.removeClassName(this.options.errorClass);
		this.field.removeClassName(this.options.errorClass);
		this.time.removeClassName(this.options.errorClass);
		this.time_to.removeClassName(this.options.errorClass);
		if(f=="from"){
			if(this.from.date>this.to.date){
				this.time.addClassName(this.options.errorClass);
				this.field.addClassName(this.options.errorClass);
			}
		}else{
			if(this.from.date>this.to.date){
				this.time_to.addClassName(this.options.errorClass);
				this.field_to.addClassName(this.options.errorClass);
			}
		}
		if((this.from.date.print(this.options.format)==this.field.value)
			||(this.to.date.print(this.options.format)==this.field_to.value))
			this.setValues();
	},
	correct2:function(f){
			if(!this.from.date.equalsTo(this.to.date)){
				if(f=="from"){
					if(this.from.date>this.to.date){
							this.to.date=new Date(this.from.date.getTime());
							if(this.interval!=false)
								this.to.date.setMinutes(this.interval<0?(this.to.date.getMinutes()-this.interval):(this.to.date.getMinutes()+this.interval));
					}
				}else{
					if(this.from.date>this.to.date){
						this.from.date=new Date(this.to.date.getTime());
						if(this.interval!=false)
							this.from.date.setMinutes(this.interval<0?(this.from.date.getMinutes()+this.interval):(this.from.date.getMinutes()-this.interval));
					}
				}
			}
			this.setValues();
			this.reinitSelect();
	},
	correct3:function(f){
			if(!this.from.date.equalsTo(this.to.date)){
					if(this.from.date>this.to.date){
							this.to.date=new Date(this.from.date.getTime());
							if(this.interval!=false)
								this.to.date.setMinutes(this.interval<0?(this.to.date.getMinutes()-this.interval):(this.to.date.getMinutes()+this.interval));
					}
			}
			this.setValues();
			this.reinitSelect();
	},
	setInterval:function(){
		if(this.interval!=false){
			var int=((this.to.date.getHours()-this.from.date.getHours())*60)+(this.to.date.getMinutes()-this.from.date.getMinutes());
			this.interval=int;
		}
	},
	initSelect:function(){
		var that=this;
		var timeopt1=Object.extend({
									field:this.time,
									callHandler:function(opt){that.valuesChanged(opt)},
									handlerOpt:"from"
									},this.options.time_opt1);
		var dst=new DSSelectCalendar.Time(timeopt1);
		this.time_select=dst;
		var timeopt2=Object.extend({
									field:this.time_to,
									date:this.from.date,
									callHandler:function(opt){
										var tmpdate=new Date(that.to.date.getTime());
										var tmptime=Date.parseDate(tmpdate.print(that.options.format)+" "+that.time_to.value,that.options.format+" %H:%M");
										tmpdate.setHours(tmptime.getHours());
										tmpdate.setMinutes(tmptime.getMinutes());
										if(that.from.date>tmpdate){
											tmpdate.setDate(tmpdate.getDate()+1);
											that.to.date=new Date(tmpdate.getTime());
											that.setValues();
										}
										that.valuesChanged(opt)},
									handlerOpt:"to"
									},this.options.time_opt2);
		var dst2=new DSSelectCalendar.Time(timeopt2);
		if(this.interval!=false){
			if(this.from.date.equalsToDay(this.to.date))
				dst2.getInterval(this.from.date);
		}
		this.time_select_to=dst2;
	},
	reinitSelect:function(){
		if(this.from.date.equalsToDay(this.to.date) && this.interval!=false){
			this.time_select_to.getInterval(this.from.date);
		}else{
			this.time_select_to.getSelect();
		}
		this.time_select.getSelect();
	},
	valuesChanged:function(f){
		var tmp=this.date;
		var tmpdate=Date.parseDate(this.field.value,this.options.format);
		var tmptime=Date.parseDate(tmpdate.print(this.options.format)+" "+this.time.value,this.options.format+" %H:%M");
		tmpdate.setHours(tmptime.getHours());
		tmpdate.setMinutes(tmptime.getMinutes());
		this.from.date=new Date(tmpdate.getTime());
		if(f=="from"){
			if(this.interval!=false){
				this.to.date.setHours(this.from.date.getHours());
				this.to.date.setMinutes(this.from.date.getMinutes()+this.interval);
			}
		}else{
			tmpdate=Date.parseDate(this.field_to.value,this.options.format);
			tmptime=Date.parseDate(tmpdate.print(this.options.format)+" "+this.time_to.value,this.options.format+" %H:%M");
			tmpdate.setHours(tmptime.getHours());
			tmpdate.setMinutes(tmptime.getMinutes());
			this.to.date=new Date(tmpdate.getTime());
		}
		if(f=="from" && this.options.intervalDay!=0){
			this.to.date.setFullYear(this.from.date.getFullYear());
			this.to.date.setMonth(this.from.date.getMonth());
			this.to.date.setDate(this.from.date.getDate()+this.options.intervalDay);
		};
		if(f=="from"){
			var actfield=this.options.field;
			var actdate=this.from.date;
			var emptyCheck=this.options.empty;
		}
		else{
			var actfield=this.options.field_to;
			var actdate=this.to.date;
			var emptyCheck=this.options.empty2;
		}
		if(emptyCheck){
			if(!this.checkEmpty(actdate,actfield)){
				var tmp=Date.parseDate("1.1.1901","%d.%m.%Y");
				if(!tmp.equalsToDay(this.from.date) && !tmp.equalsToDay(this.to.date)){
					this.errorcorrecter(f);
				}
			}else{
				if(f=="from"){
					this.time.value="00:00";
					this.time_view.value="00:00";
				}
				else{
					this.time_to.value="00:00";
					this.time_to_view.value="00:00";
				}
				this.time.removeClassName(this.options.errorClass);
				this.field.removeClassName(this.options.errorClass);
			}
		}else{
			this.errorcorrecter(f);
		}
		this.reinitSelect();
		this.setInterval();
	},
	dateChanged:function(f) {
		if(f=="from"){
			var actfield=this.options.field;
			var actdate=this.from.date;
			var emptyCheck=this.options.empty;
		}
		else{
			var actfield=this.options.field_to;
			var actdate=this.to.date;
			var emptyCheck=this.options.empty2;
		}
		if(emptyCheck){
			if(!this.checkEmpty(actdate,actfield)){
				var tmp=Date.parseDate("1.1.1901","%d.%m.%Y");
				if(!tmp.equalsToDay(this.from.date) && !tmp.equalsToDay(this.to.date)){
					if(f=="from" && this.options.intervalDay!=0){
						this.to.date.setFullYear(this.from.date.getFullYear());
						this.to.date.setMonth(this.from.date.getMonth());
						this.to.date.setDate(this.from.date.getDate()+this.options.intervalDay);
					};
					this.setValues();
					this.errorcorrecter(f);
				}
			}else{
				if(f=="from"){
					this.time.value="00:00";
					this.time_view.value="00:00";
				}
				else{
					this.time_to.value="00:00";
					this.time_to_view.value="00:00";
				}
				this.time.removeClassName(this.options.errorClass);
				this.field.removeClassName(this.options.errorClass);
			}
		}else{
			if(f=="from" && this.options.intervalDay!=0){
				this.to.date.setFullYear(this.from.date.getFullYear());
				this.to.date.setMonth(this.from.date.getMonth());
				this.to.date.setDate(this.from.date.getDate()+this.options.intervalDay);
			};
			this.setValues();
			this.errorcorrecter(f);
		}
		this.reinitSelect();
		this.setInterval();
	},
	setFullDay:function(bool){
		if(this.options.disable||this.options.disable_to)
			return;
		if(bool){
			this.tmphours=this.from.date.getHours();
			this.tmpmin=this.from.date.getMinutes();
			this.tmphoursto=this.to.date.getHours();
			this.tmpminto=this.to.date.getMinutes();
			this.from.date.setHours(0);
			this.from.date.setMinutes(0);
			this.to.date.setHours(23);
			this.to.date.setMinutes(59);
			this.setValues();
			$(this.time.id+'_view').hide();
			$(this.time_to.id+'_view').hide();
		}else{
			if(this.tmphours==-1){
				this.tmphours=this.from.date.getHours();
				this.tmpmin=this.from.date.getMinutes();
				this.tmphoursto=this.to.date.getHours();
				this.tmpminto=this.to.date.getMinutes();
			}
			this.from.date.setHours(this.tmphours);
			this.from.date.setMinutes(this.tmpmin);
			this.to.date.setHours(this.tmphoursto);
			this.to.date.setMinutes(this.tmpminto);
			this.setValues();
			$(this.time.id+'_view').show();
			$(this.time_to.id+'_view').show();
			this.reinitSelect();
		}
	}
});
var CalendarURL=Class.create({
									
	initialize:function(urls,params){
		this.options=Object.extend({
			container:"urllist",
			itemname:"linklistitem_",
			textfield:"linktext",
			titlefield:"linkurltitle",
			urlfield:"linkurl",
			targetfield:"linktarget",
			linksort:"linksort",
			linkcount:"linkcount",
			classfirst:"dslist1",
			classsecond:"dslist2",
			classhandle:"sortablehandle",
			addbutton:"linklistadd"
		},params);
		this.linktext=$(this.options.textfield);
		this.url=$(this.options.urlfield);
		this.target=$(this.options.targetfield);
		this.linktitle=$(this.options.titlefield);
		this.linksort=$(this.options.linksort);
		this.linkcount=$(this.options.linkcount);
		this.addbutton=$(this.options.addbutton);
		var that=this;
		this.addbutton.observe("click",function(){that.addLink()});
		this.container=$(this.options.container);
		this.calUrlList=[];
		if(typeof(urls)!="undefined" && urls.length!=0){
			this.calUrlList=urls;
			for(var i=1;i<=this.calUrlList.length;i++){
				var str='<li class="'+this.options.classhandle+' '+this.options.classfirst+' menuselector" id="'+this.options.itemname+i+'">\
				<div class=" ds_3column_1">'+this.calUrlList[i-1].text+'</div>\
				<div class="ds_3column_2">'+this.calUrlList[i-1].url+'</div>\
				<div class="ds_3column_3">'+this.calUrlList[i-1].target+'</div>\
				<input type="hidden" id="'+this.options.itemname+i+'_text" name="'+this.options.itemname+i+'_text" value="'+this.calUrlList[i-1].text+'">\
				<input type="hidden" id="'+this.options.itemname+i+'_title" name="'+this.options.itemname+i+'_title" value="'+this.calUrlList[i-1].title+'">\
				<input type="hidden" id="'+this.options.itemname+i+'_url" name="'+this.options.itemname+i+'_url" value="'+this.calUrlList[i-1].url+'">\
				<input type="hidden" id="'+this.options.itemname+i+'_target" name="'+this.options.itemname+i+'_target" value="'+this.calUrlList[i-1].target+'">\
				</li>';
				this.container.insert(str);
				new Proto.Menu({selector: '.menuselector',className: 'menu desktop',menuItems: 'calendarlinklist_actions' ,mouseevent:'contextmenu'});
			}
		};
		this.calUrlActPos=1;
		this.calUrlEdit=false;
		this.updateLinkList();
	},
	sortLinks:function(){
		var i=1;
		var linksort="";
		var that=this;
		$$("#"+that.options.container+" li").each(function(handleEml){
			handleEml.removeClassName(that.options.classsecond);
			handleEml.removeClassName(that.options.classfirst);
			if(Math.round(i/2)!=(i/2))
				handleEml.addClassName(that.options.classfirst);
			else
				handleEml.addClassName(that.options.classsecond);
			i++;
			linksort+=linksort.length? ","+handleEml.id:handleEml.id;												
		});
		this.linksort.value=linksort;
		this.linkcount.value=i;
	},
	addLink:function(){
		if(!this.validateLink())
			return;
		var newLink=new Object();
		newLink.text=this.linktext.value;
		newLink.title=this.linktitle.value;
		newLink.url=this.url.value;
		newLink.target=this.target.value;
		this.calUrlList.push(newLink);
		var str='<li class="'+this.options.classfirst+' menuselector" id="'+this.options.itemname+this.calUrlList.length+'">\
			<div class=" ds_3column_1">'+this.linktext.value+'</div>\
			<div class="ds_3column_2">'+this.url.value+'</div>\
			<div class="ds_3column_3">'+this.target.value+'</div>\
			<input type="hidden" id="'+this.options.itemname+this.calUrlList.length+'_text" name="'+this.options.itemname+this.calUrlList.length+'_text" value="'+this.linktext.value+'">\
			<input type="hidden" id="'+this.options.itemname+this.calUrlList.length+'_title" name="'+this.options.itemname+this.calUrlList.length+'_title" value="'+this.linktitle.value+'">\
			<input type="hidden" id="'+this.options.itemname+this.calUrlList.length+'_url" name="'+this.options.itemname+this.calUrlList.length+'_url" value="'+this.url.value+'">\
			<input type="hidden" id="'+this.options.itemname+this.calUrlList.length+'_target" name="'+this.options.itemname+this.calUrlList.length+'_target" value="'+this.target.value+'">\
			</li>';
		this.linktext.value="";
		this.target.selectedIndex=0;
		this.url.value="";
		this.linktitle.value="";
		this.container.insert(str);
		new Proto.Menu({selector: '.menuselector',className: 'menu desktop',menuItems: 'calendarlinklist_actions' ,mouseevent:'contextmenu'});
		this.updateLinkList();
	},
	removeLink:function(elmid){
		var position=elmid.slice(this.options.itemname.length);
		this.calUrlList[position-1]=null;
		if(this.calUrlEdit){
			if(position==this.calUrlActPos){
				this.linktext.value="";
				this.target.selectedIndex=0;
				this.url.value="";
				this.linktitle.value="";
				var that=this;
				this.addbutton.stopObserving("click");
				this.addbutton.observe("click",function(){that.addLink();});
				this.calUrlEdit=false;
				this.addbutton.value=DSLang('add');
			}
		}
		$(this.options.itemname+position).remove();
		this.updateLinkList();
	},
	updateLink:function(){
		if(!this.validateLink())
			return;
		var position=this.calUrlActPos;
		var newLink=new Object();
		newLink.text=this.linktext.value;
		newLink.title=this.linktitle.value;
		newLink.url=this.url.value;
		newLink.target=this.target.value;
		this.calUrlList[position-1]=newLink;
		var str='<div class=" ds_3column_1">'+this.linktext.value+'</div>\
			<div class="ds_3column_2">'+this.url.value+'</div>\
			<div class="ds_3column_3">'+this.target.value+'</div>\
			<input type="hidden" id="'+this.options.itemname+position+'_text" name="'+this.options.itemname+position+'_text" value="'+this.linktext.value+'">\
			<input type="hidden" id="'+this.options.itemname+position+'_title" name="'+this.options.itemname+position+'_title" value="'+this.linktitle.value+'">\
			<input type="hidden" id="'+this.options.itemname+position+'_url" name="'+this.options.itemname+position+'_url" value="'+this.url.value+'">\
			<input type="hidden" id="'+this.options.itemname+position+'_target" name="'+this.options.itemname+position+'_target" value="'+this.target.value+'">\
			';
		var that=this;
		this.addbutton.stopObserving("click");
		this.addbutton.observe("click",function(){that.addLink();});
		this.linktext.value="";
		this.target.selectedIndex=0;
		this.url.value="";
		this.linktitle.value="";
		$(this.options.itemname+position).update(str);
		this.addbutton.value=DSLang('add');
		this.calUrlEdit=false;
		
	},
	editLink:function(elmid){
		var position=elmid.slice(this.options.itemname.length);
		this.linktitle.value=this.calUrlList[position-1].title;
		this.url.value=this.calUrlList[position-1].url;
		this.target.value=this.calUrlList[position-1].target;
		this.linktext.value=this.calUrlList[position-1].text;
		var that=this;
		this.addbutton.stopObserving("click");
		this.addbutton.observe("click",function(){that.updateLink();});
		this.addbutton.value=DSLang('save');
		this.calUrlActPos=position;
		this.calUrlEdit=true;
	},
	validateLink:function(){
		var msg="";
		if(this.linktext.value=="")
			msg=DSLang('linktext')+": "+DSLang("alerttexturlnotempty");
		if(this.url.value=="")
			msg=DSLang('linkurl')+": "+DSLang("alerttexturlnotempty");
		if(msg!="")alert(msg);
		if(msg!="")
			return false;
		else
			return true;
	},
	updateLinkList:function(){
		var that=this;
		Sortable.create(that.options.container,{ghosting:false,constraint:false,onUpdate:function(){that.sortLinks()}});
		this.sortLinks();
		DSPopUpResize();
	}
});
function initSelectCalendar(type,params,fullday,elm){
	params=params.evalJSON();
	switch(type){
		case "DoubleWithTime":
			$(params.field+"_view").onfocus=null;
			$(params.field_to+"_view").onfocus=null;
			$(params.time_field+"_view").onfocus=null;
			$(params.time_to_field+"_view").onfocus=null;
			$(params.field+"_view").dsselectcalendar=new DSSelectCalendar.DoubleWithTime(params);
			if(fullday){
				var clickstr="$('"+params.field+"_view').dsselectcalendar.setFullDay(this.checked)";
				$(fullday).onclick=function(){
							eval(clickstr);
						};
				if(elm.id==fullday)
					$(params.field+"_view").dsselectcalendar.setFullDay($(fullday).checked);
			}
			break;
		case "Double":
			$(params.field+"_view").onfocus=null;
			$(params.field_to+"_view").onfocus=null;
			$(params.field+"_view").dsselectcalendar=new DSSelectCalendar.Double(params);
			break;
		case "withTime":
			$(params.field+"_view").onfocus=null;
			$(params.time_field+"_view").onfocus=null;
			$(params.field+"_view").dsselectcalendar=new DSSelectCalendar.withTime(params);
			break;
		case "Date":
			$(params.field+"_view").onfocus=null;
			$(params.field+"_view").dsselectcalendar=new DSSelectCalendar(params);
			break;
	}
	if(elm.id!=fullday){
		elm.blur();
		elm.click();
	}
};
/* Functions */
function event_chk_form(caller){
	// 2006-10-22 [AP] Arguement Caller hinzugefügt, wenn ein Task vom Artikel gespeichert wird
	start_date=Date.parseDate($('start_date').value+" "+$('start_time').value,"%Y-%m-%d %H:%M");		
	end_date=Date.parseDate($('end_date').value+" "+$('end_time').value,"%Y-%m-%d %H:%M");	
	recurrence_end_date=Date.parseDate($('recurrence_end_date').value,"%Y-%m-%d");
	recurrence_end_date.setHours(23);
	recurrence_end_date.setMinutes(59);
	d_diff=DSDateDiff('d',start_date,end_date);
	msg=''; 
	period=$('period');


	DSCal=eval('top.DSCal_'+$('dscalid').value);
	if (DSCal!=null && $('CalendarCurrDate')!=null){
		//alert(document.getElementById('dscalid').value);
		this_currdate=DSCal.calendar_currentdate;
		//alert(this_currdate.toString())
		thisvar=this_currdate.getFullYear()+'-'+DSInt(this_currdate.getMonth()+1)+'-'+this_currdate.getDate();
		$('CalendarCurrDate').value=thisvar;
	}	
	
	if (DSTrim($('title').value)=='')
		msg+=DSLang('alertcalsubject');
	if ((end_date.getFullYear()==1901 || end_date.getFullYear()==2500) && end_date.getMonth()==0 && end_date.getDate()==1){
		msg+='';
	}
	else if (period!=null && period.value=='wholeday')
		msg+='';
	else if (start_date >end_date)
		msg+=DSLang('alertstartforenddate');
	
	if ($('recurrence_type').selectedIndex!=0){
		if ($('recurrence_type').selectedIndex==1){ //daily
			if (document.getElementsByName('daily_type')[0].checked){
				day_step=$('day_step').value;
				if (!DSIsNum(day_step)) {
					msg+=DSLang('alertnovalidinterval');
					msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",day_step);
				}
				else{
					day_step=DSInt(day_step);
					if (d_diff >= day_step) {
						msg+=DSLang('alertintervaldailyrepeat');
						msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",day_step);
						msg=DSJS.ReplaceNoCase(msg,"@@replace2@@",d_diff);
					}
				}
			}
			else{
				if (d_diff > 0)
					msg+=DSLang('alertrepeatworkdays');
			}
		}
		else if($('recurrence_type').selectedIndex==2){ // weekly
			if (!DSIsNum($('week_step').value)) {
				msg+=DSLang('alertnotavlidnumber');
				msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",$('week_step').value)
			}
			else{
				wd=document.getElementsByName('weekdays');
				start_date_wd_found=0;
				this_wd=new Array();
				for(i=0; i<wd.length; i++){
					if (wd[i].checked){
						this_wd[this_wd.length]=i
						if (start_date.getDay()==eval(wd[i].value-1))
							start_date_wd_found=1;	
					}
				}
				if (this_wd.length==0)
					msg+=DSLang('alertrepeatweekdays');
				else{
					if (this_wd.length==1)
						chk_days=6;
					else{
						start_diff=this_wd[0]-0;
						end_diff=6-this_wd[this_wd.length-1];
						chk_days=start_diff+end_diff;
						for(i=1; i<this_wd.length; i++){
							this_diff=this_wd[i]-this_wd[i-1]-1;
							if (this_diff<chk_days)
								chk_days=this_diff;
						}
					}
					if (d_diff>=$('week_step').value*7){
						msg+=DSLang('alerttimeperiodinterval');
						msg=DSJS.ReplaceNoCase(msg,"@@replace2@@",eval(DSInt(d_diff/7)+1),"All");
					}
					else if (d_diff >=7 && this_wd.length!=1)
						msg+=DSLang('alertrepeatoneweekday');
					else if (d_diff > chk_days)
						msg+=DSLang('alerttimeperiodrepeatweekday');
					if (start_date_wd_found==0) {
						msg+=DSLang('alertrepeatweeklyacitve');
						msg=DSJS.ReplaceNoCase(msg,"@@replace3@@",DayNames[start_date.getDay()],"All");
					}
					msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",d_diff,"All");
					
					
				}
			}
		}
	}
	if(start_date>recurrence_end_date && $('end_type_3').checked){
		msg+=DSLang('alertendolderbeginn');
		msg=DSJS.ReplaceNoCase(msg,"@@replace1@@",DSDateTimeFormat('date',end_date),"All");
		msg=DSJS.ReplaceNoCase(msg,"@@replace2@@",DSDateTimeFormat('date',recurrence_end_date),"All");
	}
	if (msg=='') {
		if (caller!=null && caller=='article')
			submitform=1;
		else 
			dsform_submit();
	}
	else{
		alert(msg);
		$('dsbutton_submit').disabled=false;
	}
 }	
 
