// SLP

window.onload = function() {
	// initFormularCheck(); ... abgestellt, weil sonst "return true" und keine weitere verarbeitung bei onsubmit mehr möglich 
	initListBrowser();
	// if(Calendar) Calendar.Load();
}

var myTimer = "";
var myContent = "";

function loadTiny() {
	a = document.createElement('script');
	a.setAttribute('type','text/javascript');
	a.setAttribute('src','/javascript/tiny_mce/tiny_mce.js');
	document.getElementsByTagName('head')[0].appendChild(a);
}

function checkTinyChars(editor,myLength,infofield) {
	
	var text = tinymce.get(editor).getContent();
	text = text.replace("<br />", "");
	text = text.replace("&amp;", "&");
	text = text.replace("&copy;", "C");
	text = text.replace("&euro;", "E");
	text = text.replace("&nbsp;", " ");
	if (text.length > myLength){
		tinymce.activeEditor.setContent(myContent);
	} else {
		myContent = tinymce.get(editor).getContent();
		$(infofield).innerHTML =myLength-text.length;
	}
		myTimer = setTimeout("initCheckChars()",500);	
}


/*
 * TinyMCE Loader
 *
 * Daniel Wannewitz
 * 01.04.2011
 */
function initTiny(id,mode) {
	
	if(id.length == 0)
		return false;
	
	if(mode == 'mini') {
		var buttons = "bold,italic";
		var location = "top";
		tinyMCE.init({
			language : 'de',
		    theme : "advanced",
		    mode: "exact",
		    plugins : "paste",
		    oninit: "initCheckChars",
		    elements : id,
		    forced_root_block : false,
		    force_br_newlines : true,
		    force_p_newlines : false,
	        paste_auto_cleanup_on_paste : true,
		    theme_advanced_toolbar_align : "left",
		    theme_advanced_toolbar_location : location,
		    theme_advanced_buttons1 : buttons,
		    theme_advanced_buttons2 : false,
		    theme_advanced_buttons3 : false
		});
	}
	else if(mode == 'miniXnl') {
		var buttons = "bold,italic";
		var location = "top";
		tinyMCE.init({
			language : 'de',
		    theme : "advanced",
		    mode: "exact",
		    plugins : "paste",
		    oninit: "initCheckChars",
		    elements : id,
		    forced_root_block : false,
		    force_br_newlines : true,
		    force_p_newlines : false,
	        paste_auto_cleanup_on_paste : true,
		    theme_advanced_toolbar_align : "left",
		    theme_advanced_toolbar_location : location,
		    theme_advanced_buttons1 : buttons,
		    theme_advanced_buttons2 : false,
		    theme_advanced_buttons3 : false,
		    setup : function(ed) {
	  	  		ed.onKeyPress.addToTop(function(ed, e) {
				    if ((e.charCode == 13 || e.keyCode == 13)) {
				        return tinymce.dom.Event.cancel(e);
				    }
	  	  		});
			}
		});
	}
	else {
		var buttons = false;
		var location = false;
		tinyMCE.init({
			language : 'de',
		    theme : "advanced",
		    mode: "exact",
		    oninit: "initCheckChars",
		    elements : id,
		    forced_root_block : false,
		    force_br_newlines : true,
		    force_p_newlines : false,
	        paste_auto_cleanup_on_paste : true,
		    theme_advanced_toolbar_align : "left",
		    theme_advanced_toolbar_location : location,
		    theme_advanced_buttons1 : buttons,
		    theme_advanced_buttons2 : false,
		    theme_advanced_buttons3 : false,
		    setup : function(ed) {
	  	  		ed.onKeyPress.addToTop(function(ed, e) {
				    if ((e.charCode == 13 || e.keyCode == 13)) {
				        return tinymce.dom.Event.cancel(e);
				    }
	  	  		});
			}
		});
	}
}


/*
 * POPUPSCRIPT
 *
 * Sebastian Lübke
 * 07.07.2008
 */
function popup(params) {
	//$('loading').show();
	if($('popup'))
		popup_reset();
	
	if(!$('popup')) {
		TheBlinder				= document.createElement('div');
		ThePopup 				= document.createElement('div');
		PopupMargin 			= document.createElement('div');
		PopupContent 			= document.createElement('div');

		TheBlinder.setAttribute('id', 'popup_blinder');
		TheBlinder.style.height = $('page_margins').getHeight() +'px';

		ThePopup.setAttribute('id', 'popup');
		PopupMargin.setAttribute('id', 'popup_margin');
		PopupContent.setAttribute('id', 'popup_cont');

		$('page_margins').appendChild(TheBlinder);
		$('page_margins').appendChild(ThePopup);
		$('popup').appendChild(PopupMargin);
		$('popup_margin').appendChild(PopupContent);
		toggleSelectTags('hidden');
		
		new Ajax.Updater(
			'popup_cont',
			'/', {
				evalScripts	: true,
				parameters	: params,
				onFailure		: popup_reset,
				onComplete	: function() { 
					$('loading').hide();
					$('page').scrollTo(); 

					if($('page_margins').getHeight() < $('popup').getHeight() && $('scrollme')) {
						$('scrollme').style.height = ($('page_margins').getHeight()-370) +'px';
						$('scrollme').style.overflow = 'auto';					
					}
				}
			}
		);
	}
}
function popup_reset() {
	toggleSelectTags('visible');
	$('page_margins').removeChild(ThePopup);	
	$('page_margins').removeChild(TheBlinder);
}
function toggleSelectTags(status) {
	var status = status;
	$A(document.getElementsByTagName('select')).each(
		function(element) {
			element.style.visibility = status;
		}
	);
}


/*
 * LISTBROWSER
 *
 * Sebastian Lübke
 * 08.07.2008
 */
var ListBrowser = Class.create();
ListBrowser.prototype = {
	initialize: function(args) {
		this.listID 	= args.listID;
		this.prevID 	= args.prevID;
		this.nextID 	= args.nextID;
		this.counterID= args.counterID;
		this.li 		= $(this.listID).getElementsByTagName('li');								
		this.total 		= this.li.length;
		this.current 	= 0;
		
		$(this.prevID).onclick = this.prev.bindAsEventListener(this);
		$(this.nextID).onclick = this.next.bindAsEventListener(this);
		
		this.count();
	},

	next	: function() {
		this.liToggle(false);
		this.current = this.current < (this.total -1) ? this.current +1 : 0;
		this.count();
		return false;
	},
	
	prev	: function() {
		this.liToggle(false);
		this.current = this.current > 0 ? this.current -1 : this.total -1;
		this.count();
		return false;
	},
	
	count	: function() {
		this.liToggle(true);
		if($(this.counterID))
			$(this.counterID).innerHTML = (this.current +1) +'/'+ this.total;
	},
	
	liToggle : function(bool) {
		if(bool)
			$(this.li[this.current]).style.display = 'block';
		else
			$(this.li[this.current]).style.display = 'none';
	}
};
function initListBrowser() {
	$A(document.getElementsByClassName('listbrowser')).each(
		function(element) {
			new ListBrowser({
				listID		: element.id,
				nextID 		: element.id +'-next',
				prevID 		: element.id +'-prev',
				counterID	: element.id +'-counter'
			});
		}
	);
}


/*
 * Unterkategorien ein-/ausklappen
 *
 * Sebastian Lübke
 * 18.07.2008
 */
function toggleElement(toggleLink, elm) {
	if($(elm).style.display == 'none') {
		toggleLink.className = 'icon seeless';
		$(elm).show();
	}
	else if($(elm).style.display != 'none') {
		toggleLink.className = 'icon seemore';
		$(elm).hide();
	}	
}



/*
 * FORMULARVALIDIERUNG
 *
 * Sebastian Lübke
 * 08.07.2008
 */
var FormularCheck = Class.create();
FormularCheck.prototype = {
	initialize : function(Formular) {
		this.Form = $(Formular);
	},
	
	check : function () {
		sendForm = true;
		input = this.Form.getElementsByClassName('req');
		for(i = 0; i < input.length; i++)
		{
		    if((input[i].value == '' && input[i].type == 'text') || 
				 (input[i].value == '' && input[i].tagName == 'SELECT') ||
				 (input[i].value == '' && input[i].tagName == 'TEXTAREA')
				 ) {
				// alert(input[i].title +'\nDieses Feld darf nicht leer sein.');
				input[i].addClassName('invalid');					
				input[i].focus();
				sendForm = false;
			} else
				input[i].removeClassName('invalid');

			if( input[i].type == 'checkbox') {
			    	
			    	
			    
				if( input[i].checked == false ) {
					$(input[i].parentNode).addClassName('invalid_label');
					input[i].focus();
					sendForm = false;
				} else {
					$(input[i].parentNode).removeClassName('invalid_label');
				}
			}
		}
		
		input = this.Form.getElementsByClassName('num');
		for(i = 0; i < input.length; i++) {
			if(isNaN(input[i].value)) {
				// alert(input[i].title +'\nNur Zahlen sind erlaubt.');
				input[i].addClassName('invalid');
				input[i].focus();
				sendForm = false;
			} else
				input[i].removeClassName('invalid');
		}

		input = this.Form.getElementsByClassName('string');
		for(i = 0; i < input.length; i++) {
			if(input[i].value.search(/[a-zA-Z]/) != -1 && input[i].value.search(/\d/) == -1)
				input[i].removeClassName('invalid');
			else {
				// alert(input[i].title +'\nNur Buchstaben sind erlaubt.');
				input[i].addClassName('invalid');
				input[i].focus();
				sendForm = false;
			}
		}
		
		input = this.Form.getElementsByClassName('date');
		for(i = 0; i < input.length; i++) {
			time = new Date();
			inpt = input[i].value.split('.');
			if((inpt.length == 3 
				&& parseInt(inpt[0]) <= 31 
				&& parseInt(inpt[1]) <= 12
				&& parseInt(inpt[2]) <= time.getFullYear()
				&& input[i].value.length == 10
				&& isNaN(input[i].value.replace('.','')) == false)
				|| input[i].value.length == 0) {
				input[i].removeClassName('invalid');
			}
			else {
				d = time.getDate();
				d = d < 10 ? '0'+d : d;
				m = time.getMonth();
				m = m < 10 ? '0'+m : m;
				y = time.getFullYear();
				alert(input[i].title +'\nDas Format ist fehlerhaft. Bitte geben Sie ein Datum wie folgt ein:\n'+d+'.'+m+'.'+y);
				input[i].addClassName('invalid');
				input[i].focus();
				sendForm = false;
			}
		}
		
		input = this.Form.getElementsByClassName('mail');
 		reg = new RegExp('^([a-zA-Z0-9\-\.\_]+)'+
	   	               '(\@)([a-zA-Z0-9\-\.]+)'+
               	 		 '(\.)([a-zA-Z]{2,4})$');
		for(i = 0; i < input.length; i++) {
 			if(reg.test(input[i].value))
 				input[i].removeClassName('invalid');
 			else {
				// alert(input[i].title +'\nNur Buchstaben sind erlaubt.');
				input[i].addClassName('invalid');
				input[i].focus();
				sendForm = false;
 			} 				
		}
		return sendForm;
	}
}

function FormCheck(element) {
	Form = new FormularCheck(element);
	return Form.check();
}

function Output (where, what) {
    $(where).innerHTML = what;
    $(where).show();
}

/*
function initFormularCheck() {
	$A(document.getElementsByTagName('form')).each(
		function(element) {
			element.onsubmit = function() {
				Form = new FormularCheck(this);
				return Form.check();
			}
		}
	);
}
*/
/*
 * EINGABELÄNGE VON TEASERN PRÜFEN
 *
 * Sebastian Lübke
 * 24.09.2008
 */
function checkTeaser(elm, display, Max) {
	if(Max == undefined)
		Max = 200;
	Is = elm.value.length;
	if(Max - Is > 0)
		$(display).innerHTML = Max - elm.value.length;
	else {
		$(display).innerHTML = '0';
		elm.value = elm.value.substr(0, Max);
	}
}

/*
 * Kommentar schreiben und via AJAX speichern
 * Verstoß melden und via AJAX speichern
 *
 * Sebastian Lübke
 * 17.10.2008
 */
function reportAbuse() {
	$('loading').show();
	new Ajax.Request(
		'/', {
			parameters	: { 
				'AJAX' 		: true, 
				'template' 	: $('ReportAbuse').template.value,
				'warn_detail'	: $('ReportAbuse').warn_grund.value,
				'api'		: $('ReportAbuse').api.value,
				'id'		: $('ReportAbuse').id.value
			},
			onComplete	: function(r) {
				$('loading').hide();
				if($('ReportAbuseAjax'))
					$('ReportAbuseAjax').hide();
				if($('popup'))
					popup_reset();
				popup({
					'AJAX' 			: true,
					'template'		: 'ok.abuse'
				});
			}
		}
	);
}

function writeComment() {
	$('loading').show();
	new Ajax.Request(
		'/', {
			parameters	: { 
				'AJAX' 		: true, 
				'template' 	: $('WriteComment').template.value,
				'titel'		: $('WriteComment').titel.value,
				'content'	: $('WriteComment').content.value,
				'api'		: $('WriteComment').api.value,
				'id'		: $('WriteComment').id.value
			},
			onComplete : function(transport) {

				if(transport.responseText != 'false')
				{
        			    	$('loading').hide();
        			    	$('KommentarBetreff').value = '';
        			    	$('KommentarContent').value = '';        			    	
        			    	$('KommentareZumArtikelAjax').hide();
        			    	// AT.DetailView();
        				this.KommentarListeAJAX($('WriteComment').id.value, 'kommentar.' + $('WriteComment').api.value, 0, 5);
				} else {
        			    	popup({
        					'AJAX' 		: true,
        					'template'	: 'relogin'
        				});
				}
			}			
		}
	);
}

function updateComment(id) {
	
	$('loading').show();
	new Ajax.Request(
		'/', {
			parameters	: { 
				'AJAX' 		: true, 
				'template' 	: $('UpdateComment_' + id).template.value,
				'titel'		: $('UpdateComment_' + id).titel.value,
				'content'	: $('UpdateComment_' + id).content.value,
				'comment_id': $('UpdateComment_' + id).comment_id.value
			},
			onComplete : function(transport) {

				if(transport.responseText != 'false')
				{
					r = transport.responseText.evalJSON();
        			window.location.href = r.referer;
				} else {
        			    	popup({
        					'AJAX' 		: true,
        					'template'	: 'relogin'
        				});
				}
			}			
		}
	);
}

function KommentarListeAJAX(id, template, start, amount)
{
    new Ajax.Updater(
		'KommentareAjaxBox',
		'/', {
			parameters	: 
			{
				'AJAX'		: true,
				'template'	: template,
				'id' 		: id,
				'start'		: start,
				'np'		: amount
			}
		}
	);
}


function doLogin(element) {
		element = $(element);
    	popup({
		'AJAX' 			: true,
		'template'		: 'login',
		'loginname'		: element.loginname.value || false,
		'passwort'		: element.passwort.value || false
	});
}






/*
 * Nachrichtensystem
 *
 * Sebastian Lübke
 * 07.11.2008
 */

function newMessage(to, id, ava, portalid) {
	popup({
		'AJAX' 			: true,
		'template'		: 'schreiben.post',
		'empfaenger'		: to,
		'empfaengerid'		: id,
		'empfaengerportal'	: portalid,
		'avatar'		: ava
	});
}


function sendMessage(form) {
	var f = form;
	new Ajax.Request(
		'/', {
			parameters : {
				'AJAX' 			: true,
				'template'		: 'new.post',
				'empfaenger'		: f.empfaenger_id.value,
				'empfaengerportal'	: f.empfaenger_portal.value,
				'inhalt'		: f.inhalt.value,
				'betreff'		: f.betreff.value
			},
			onComplete : function() {
				if(f.id.length > 0)
					showPostContent(f.id.substr(4, (f.id.length-4)));
				popup({
					'AJAX' 			: true,
					'template'	: 'ok.post',
					'recipient'	: f.empfaenger_alias.value
				});
			}
		}
	);
}

function userInvite(form) {
	var f = form;
	new Ajax.Request(
		'/', {
			parameters : {
				'AJAX'				: true,
				'template'		: 'new.invitation',
				'email'				: f.email.value,
				'name'				: f.name.value
			},
			onComplete : function(r) {
				popup({
					'AJAX'			: true,
					'template'	: 'ok.invitation',
					'error'			: r.responseText
				});
			}
		}
	);
}

function lostPassword(form) {
	var f = form;
	new Ajax.Request(
		'/', {
			parameters : {
				'AJAX'				: true,
				'template'		: 'new.password',
				'name'				: f.name.value,
				'email'				: f.email.value
			},
			onComplete : function(r) {
				popup({
					'AJAX'			: true,
					'template'	: 'ok.password',
					'error'			: r.responseText
				});
			}
		}
	);
}

function switchPostStatus(ID) {
	Status = ($('Status'+ID).hasClassName('read')) ? 1 : 2;
	if(Status == 1) {
		$('ToggleStatus'+ID).innerHTML = 'gelesen';
		$('Status'+ID).removeClassName('read');
		$('Subject'+ID).addClassName('b');
		$('Status'+ID).addClassName('unread');
	} else {
		$('ToggleStatus'+ID).innerHTML = 'ungelesen';
		$('Status'+ID).removeClassName('unread');
		$('Subject'+ID).removeClassName('b');
		$('Status'+ID).addClassName('read');
	}
	new Ajax.Request(
		'/', {
			parameters	: { 
				'AJAX' 			: true, 
				'template' 	: 'poststatus',
				'box'				: 1,
				'Status'		: (Status==1)?1:2,
				'id'				: $('PostID'+ID).value
			}
		}
	);
}

function offerFriendship(friendId, friendAlias) {
	new Ajax.Request(
			'/', {
				parameters	: { 
					'AJAX' 		: true, 
					'template' 	: 'offer.friendship',
					'id'		: friendId,
					'name'		: friendAlias
				},
				onComplete : function(r) {
					popup({
						'AJAX'			: true,
						'template'		: 'ok.friendship',
						'result'		: r.responseText
					});
				}
			}
		);	
}

function deletePost(ID) {
	popup({
		'AJAX' 				: true,
		'template'		: 'delete.post',
		'id'					: $('PostID'+ID).value,
		'box'					: 1,
		'titel'				: $('Subject'+ID).innerHTML
	});
}


function showPostContent(ID, form) {
	if($('Post'+ID).style.display != 'none' && form != true)
		ID = -1;		
	Posts = document.getElementsByClassName('postfield');
	for(i = 0; i < Posts.length; i++) {
		if(i == ID) {
			if($('Status'+ID).hasClassName('unread')) {
				switchPostStatus(ID, 2);			
				$('Status'+ID).removeClassName('unread');
				$('Subject'+ID).removeClassName('b');
				$('Status'+ID).addClassName('read');
			}
			$('Subject'+i).blur();
			$('Post'+i).show();
			$('Post'+i).parentNode.className = 'blue';
			$('Post'+i).parentNode.parentNode.className = 'blue';
			if(form)
				$('Form'+i).show();
			else
				$('Form'+i).hide();
		} else {
			$('Post'+i).hide();
			$('Subject'+i).blur();
			$('Post'+i).parentNode.className = '';
			$('Post'+i).parentNode.parentNode.className = '';
			$('Form'+i).hide();
		}
	}
}

function hint(id) {
	popup({
		'AJAX'			:	true,
		'template'	: 'alert',
		'id'				:	id
	});
}


function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
	 for(var item in arr) {
	  var value = arr[item];
	 
	  if(typeof(value) == 'object') { //If it is an array,
	   dumped_text += level_padding + "'" + item + "' ...\n";
	   dumped_text += dump(value,level+1);
	  } else {
	   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
	  }
	 }
	} else { //Stings/Chars/Numbers etc.
	 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
	} 
