﻿var rootUri;
var enableAjax;

var shoutboxInterval = 20000;

function noop() {

}

var cursorPos;

function Point(x, y) {
	this.x = x;
	this.y = y;
}

// Deny iFrame Wrapping
var topIsForeign = true;
try {
	if (top.location.href.substr(0, rootUri.length) == rootUri)
		topIsForeign = false;
} catch(Exception) {}
if (top.location != self.location && topIsForeign)
	top.location = self.location.href;

// Shoutbox
function shoutboxCheckForNews() {
	var frame = window.frames.shoutboxFrame;
	if (frame == null) return;
	
	if (shoutboxPage == 1 && frame.window.pageYOffset < 15) {
		AJAXRequest("./shoutbox/newest", function(req) {
			newShoutboxTime = req.responseText;       
			if (newShoutboxTime > frame.shoutboxTime)     
				shoutboxUpdate();
		});
	}
	
	clearTimeout(shoutboxTimeout);
	shoutboxTimeout = setTimeout("shoutboxCheckForNews();", shoutboxInterval);
}

if (enableAjax)
	var shoutboxTimeout = setTimeout("shoutboxCheckForNews();", shoutboxInterval);
var shoutboxPage = 1;   

function shoutboxUpdateButtons() {	
	if (document.getElementById('shoutToNow') == null)
		return;

	if (shoutboxPage == 1) {
		document.getElementById('shoutToNow').innerHTML = 'Aktualisieren';
		document.getElementById('shoutBack').setAttribute('disabled', 'disabled');           
		document.getElementById('shoutToNow').setAttribute('title', 'Lädt die Shoutbox neu');
	} else {                                                            
		document.getElementById('shoutToNow').innerHTML = 'Neuste anzeigen';
		document.getElementById('shoutBack').removeAttribute('disabled');    
		document.getElementById('shoutToNow').setAttribute('title', 'Zur normalen Shoutbox-Ansicht wechseln');
	}
}
 
function shoutboxUpdate() {
	if (shoutboxPage < 1)
		shoutboxPage = 1;
		
	shoutboxFrame.location.href = './shoutbox'+
		(shoutboxPage > 1 ? '/page/'+shoutboxPage : '');
		
	shoutboxUpdateButtons();
}

function shoutboxForward() {
	shoutboxPage++;
	shoutboxUpdate();     
}   

function shoutboxBack() {
	shoutboxPage--;
	shoutboxUpdate();   
}                

function shoutboxToNow() {
	shoutboxPage = 1;
	shoutboxUpdate();
}        

setTimeout("shoutboxUpdateButtons();", 100); 

// Viewonline
var viewonlineTimeout;
var viewonlineInterval = 60000;

function updateViewonline() {
	var wrap = document.getElementById('viewonlineWrap');
	
	AJAXRequest("./viewonline/mini", function(req) {
		var existingHtml = wrap.innerHTML;
		var newHtml = req.responseText;
		if (existingHtml != newHtml)
			wrap.innerHTML = newHtml;
	});
	
	clearTimeout(viewonlineTimeout);
	viewonlineTimeout = setTimeout("updateViewonline();", viewonlineInterval);
}

if (enableAjax)
	var viewonlineTimeout = setTimeout("updateViewonline();", viewonlineInterval);

// Calendar  
var calYear;       
var calMonth; 
var calCurrentYear;
var calCurrentMonth;

function calendarMakeTitle() {
	var monthStr = new Array(
		"Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August",
		"September", "Oktober", "November", "Dezember");
		
	return monthStr[calMonth-1] + ' ' + calYear;
}

function calendarUpdate() {
	while (calMonth > 12) {
		calMonth -= 12;
		calYear++;
	}          
	while (calMonth < 1) {
		calMonth += 12;
		calYear--;
	}

	AJAXRequest("./calendar/mini/"+calYear+"/"+calMonth, function(req) {
		var wrap = document.getElementById('calWrap');
		var title = document.getElementById('calTitle');

		wrap.innerHTML = req.responseText;
		title.innerHTML = calendarMakeTitle();
	});
}

function calendarForward() {
	calMonth++;
	calendarUpdate();
}   

function calendarBack() {
	calMonth--;
	calendarUpdate();
}                   

function calendarToNow() {
	calMonth = calCurrentMonth;
	calYear = calCurrentYear;
	calendarUpdate();
}   

function updateEventVisibility() { 
	var inp = document.getElementById('Event_visibility');
	var label = document.getElementById('Event_visibilityHint');
	
	if (inp == null || label == null)
		return;

	var type = inp.value;
	var hint = 'Privat: Nur du und die eingeladenen Benutzer; Projektintern: Alle Projektmitglieder; Öffentlich: Auch Gäste dieser Seite sehen den Termin';
	
	switch (type) {
		case 'public':
			hint = 'Alle Besucher dieser Webseite, also auch unangemeldete Gäste, werden diesen Termin sehen.';
		break;
		
		case 'internal':
			hint = 'Nur Projektmitglieder werden diesen Termin sehen.';
		break;
		                    
		case 'private':
			hint = 'Nur du und alle eingeladenen Benutzer werden diesen Termin sehen.';
	}
	
	label.innerHTML = hint;		
	
	inp.style.setProperty('background-color',
		inp.options[inp.options.selectedIndex].style.backgroundColor, '');
}          

function updateStatusHint() { 
	var status = document.getElementById('status').value;
	var hint = 'Unbekannt: Ich weiß noch nicht, ob ich kommen kann; Zusage: Ich werde kommen; Absage: Ich werde nicht kommen (Begründung / Ausweichtermine unten eintragen)';
	
	switch (status) {
		case 'unknown':
			hint = 'Ich weiß noch nicht, ob ich kommen kann.';
		break;
		
		case 'positive':
			hint = 'Ich werde kommen.';
		break;
		                    
		case 'negative':
			hint = 'Ich werde nicht kommen (Bitte schreibe eine Begründung und Ausweichtermine in das Feld unten)';
	}
	
	document.getElementById('eventStatusHint').innerHTML = hint;		
}      

function submitStatus(url, status, message, isSidebar) {
	var params = '';
	
	if (isSidebar)
		prefix = 'EventNotifySidebar_';
	else
		prefix = 'Event_';
	
	if (status != null) {
		if (params != '')
			params += '&';
		params += 'Event_status=' + encodeURIComponent(status); 
	}
	
	if (message != null) {
		if (params != '')
			params += '&';
		params += 'Event_message=' + encodeURIComponent(message); 
	}
	       
	if (isSidebar)
		document.getElementById('eventNotifyLoader').removeAttribute('style');
		
	AJAXRequest(url, function(req) {
	
		var list = document.getElementById('guestList');      
		var positiveButton = document.getElementById(prefix+'positiveStatus'); 
		var negativeButton = document.getElementById(prefix+'negativeStatus');
		var textarea = document.getElementById(prefix+'message');
		if (positiveButton == null || negativeButton == null || textarea == null)
			return;     
					
		if (message != null) {
			textarea.value = message;
			/*var escapedMessage = message.replace('&', '&amp;').replace('<', '&lt;').
				replace('>', '&gt;').replace('"', '&quot;');
			textarea.innerHTML = escapedMessage;*/
		}	
			
		if (list != null)
			list.innerHTML = req.responseText;
			
		if (isSidebar) {
			document.getElementById('EventNotifySidebar_closeButton').removeAttribute('style');
			document.getElementById('eventMessageForm').removeAttribute('style');   
			document.getElementById('eventNotifyLoader').setAttribute('style', 'display: none;');
		}
			
		if (status == 'positive') {
			positiveButton.setAttribute('class',
				'icon large toolLargePositive selected');
			negativeButton.setAttribute('class', 'icon large toolLargeNegative');          
			positiveButton.setAttribute('title',
				'Du hast für diesen Termin zugesagt');      
			negativeButton.setAttribute('title',
				'Klicke hier, wenn du keine Zeit hast, also nicht kommen kannst'); 
		} else if (status == 'negative') {
			positiveButton.setAttribute('class', 'icon large toolLargePositive');
			negativeButton.setAttribute('class',
				'icon large toolLargeNegative selected');          
			positiveButton.setAttribute('title',
				'Klicke hier, wenn du Zeit hast, also zu diesem Termin kommen kannst');     
			negativeButton.setAttribute('title',
				'Du hast für diesen Termin abgesagt'); 
		}	     
			
	}, function(req) {
		alert('Die Änderungen konnten nicht gespeichert werden.');	
		
		if (isSidebar) {
			document.getElementById('eventNotifyLoader').setAttribute('style', 'display: none;');
		}
	}, params); 
}                      

// Newest Articles (Sidebar) 
var postPage = 1; 
var postIsLastPage = false;     

function postUpdateButtons() {	
	if (postPage == 1)
		document.getElementById('postBack').setAttribute('disabled', 'disabled');                         
	else 
		document.getElementById('postBack').removeAttribute('disabled');    
		
	if (postIsLastPage)
		document.getElementById('postForward').setAttribute('disabled', 'disabled');                         
	else 
		document.getElementById('postForward').removeAttribute('disabled'); 
}
 
function postUpdate(increment) {
	if (increment != null)
		dest = postPage + increment;
	else
		dest = postPage;
		
	if (dest < 1)
		dest = 1;

	AJAXRequest("./articles/newest/"+dest, function(req) {
		var wrap = document.getElementById('postWrap');
		if (wrap == null) return;
		
		if (req.responseText == '' && increment > 0) {
			postIsLastPage = true;
			postUpdateButtons();
		} else {
			postPage = dest;     
			if (increment != null)
				postIsLastPage = false;
			wrap.innerHTML = req.responseText;
			postUpdateButtons();
		}
	});
}

function postForward() {
	postUpdate(1);
}   

function postBack() {
	postUpdate(-1);
}        

// Posting
function updateAttachmentVisibilityHint(attachmentId) {   
	var input = document.getElementById('Article_attachmentVisibility' + attachmentId);
	var label = document.getElementById('Article_attachmentVisibilityHint' + attachmentId);
	
	if (input == null || label == null)
		return;   

	var type = input.value;
	var hint = 'Projektintern: Alle Projektmiglieder; Öffentlich: Alle Besuche können diesen Dateianhang sehen.';
	
	switch (type) {
		case 'public':
			hint = 'Alle Besucher dieser Webseite, also auch unangemeldete Gäste, werden diesen Dateianhang sehen.';
		break;
		
		case 'internal':
			hint = 'Nur Projektmitglieder werden diesen Dateianhang sehen.';       
   	break;
	}
	
	label.innerHTML = hint;
}

var editedFields = new Array();

function updateIncorrect(node, defaultClass) {
	if (node == null)
 		return;     
		
	var isEdited = false;
	for (field in editedFields) {
		if (field == node.id) {
			isEdited = true;
			break;		                   
		}                              
	}                                                    

  if (node.value) {
		node.setAttribute('class', defaultClass);
		if (!isEdited)
			editedFields.push(node.id);
	} else if (isEdited)
		node.setAttribute('class', defaultClass+' incorrect');	
}

function createDeleteButtons(id) {     
	var input = document.getElementById('attachmentForm' + id);
	      
	if (input == null || input.children.length < 1)
		return;   

	var dt = input.children[0]; 

	if (dt == null|| dt.children.length < 2)
 		return;                                             

	var ul = dt.children[1];     

	if (ul == null)
 		return;      

	var li = ul.children[ul.children.length-1];
 	if (li != null) 
  	li.setAttribute('class', 'space-after');
 
	li = document.createElement('span');
	li.setAttribute('id', 'attachmentDelete'+id);
	ul.appendChild(li);

	var a = document.createElement('a');
	a.setAttribute('onmousedown', 'deleteAttachment('+id+');return false;');
	a.setAttribute('class', 'toolDelete');       
	a.setAttribute('href', '#');    
	a.setAttribute('title', 'Klicke hier, um diesen Dateianhang beim Absenden des Formulars zu löschen.');
	li.appendChild(a);

	var text = document.createTextNode('Löschen');
	a.appendChild(text);	 

	li = document.createElement('span');
	li.setAttribute('id', 'attachmentUndoDelete'+id);  
	li.style.setProperty('display', 'none', ''); 
	ul.appendChild(li);

	a = document.createElement('a');   
	a.setAttribute('onmousedown', 'undoDeleteAttachment('+id+');return false;');
	a.setAttribute('class', 'toolUndoDelete');              
	a.setAttribute('href', '#');           
	a.setAttribute('title', 'Klicke hier, damit dieser Dateianhang nicht gelöscht wird.');
	li.appendChild(a);

	text = document.createTextNode('Wiederherstellen');
	a.appendChild(text);
}

function deleteAttachment(id) {
	var input = document.getElementById('attachmentForm' + id);
	      
	if (input == null || input.children.length < 2)
		return;   

	var dt = input.children[0];
	var dd = input.children[1];    

	if (dt == null || dd == null || dt.children.length < 2)
 		return;                                             

	var span = dt.children[0];
	var ul = dt.children[1];     

	if (span == null || ul == null)
 		return;  

	var originalText = span.getAttribute('originalText');
	if (!originalText) {
 		originalText = span.textContent;
		span.setAttribute('originalText', originalText);
	} 		
	span.textContent = originalText + ' (Gelöscht)';

	for (var i = 0; i < ul.children.length; i++) {
 		var li = ul.children[i]; 
   	if (li == null)    
    	continue;    

		li.style.setProperty('display', 'none', '');
	}	    

	for (var i = 0; i < dd.children.length; i++) {
 		var node = dd.children[i]; 
   	if (node == null)    
    	continue;    

		node.style.setProperty('display', 'none', '');
	}

	input = document.getElementById('Article_attachmentDelete'+id);
 	if (input == null) 
  	return;  
	input.setAttribute('checked', 'checked');
                                    
	document.getElementById('attachmentUndoDelete'+id).style.setProperty('display', 'block', '');
	document.getElementById('attachmentDelete'+id).style.setProperty('display', 'none', '');
}

function undoDeleteAttachment(id) {
	var input = document.getElementById('attachmentForm' + id);
	      
	if (input == null || input.children.length < 2)
		return;   

	var dt = input.children[0];
	var dd = input.children[1];    

	if (dt == null || dd == null || dt.children.length < 2)
 		return;                                             

	var span = dt.children[0];
	var ul = dt.children[1];     

	if (span == null || ul == null)
 		return;  

	var originalText = span.getAttribute('originalText');
	span.textContent = originalText;

	for (var i = 0; i < ul.children.length; i++) {
 		var li = ul.children[i]; 
   	if (li == null)    
    	continue;    

		li.style.setProperty('display', 'block', '');
	}	    

	for (var i = 0; i < dd.children.length; i++) {
 		var node = dd.children[i]; 
   	if (node == null)    
    	continue;    

		node.style.setProperty('display', 'block', '');
	}  

	input = document.getElementById('Article_attachmentDelete'+id);
 	if (input == null) 
  	return;  
	input.removeAttribute('checked');
                                    
	document.getElementById('attachmentUndoDelete'+id).style.setProperty('display', 'none', '');
	document.getElementById('attachmentDelete'+id).style.setProperty('display', 'block', '');
}

// Benutzer

function updateIsBot() {
	var checkBox = document.getElementById('User_isBot');
 	var passwordField1 = document.getElementById('passwordField1');  
 	var passwordField2 = document.getElementById('passwordField2');
 	var botField = document.getElementById('botField');

	if (checkBox == null)
 		return;     

	var c = checkBox.checked;
	
 	if (passwordField1 != null)
		passwordField1.style.setProperty('display', c ? 'none' : 'block', '');
  
 	if (passwordField2 != null)
		passwordField2.style.setProperty('display', c ? 'none' : 'block', '');
  
 	if (botField != null)
		botField.style.setProperty('display', c ? 'block' : 'none', ''); 
}   

function updateProfileField(field) {
	if (field == null)
 		return;    

	field.style.setProperty('background-color',
		field.options[field.options.selectedIndex].style.backgroundColor, '');
}

// Pages

var pages;

function showPage(pageName, doHash) {
	var i, page, tab

	for (i = 0; i < pages.length; i++) {
		page = document.getElementById(pages[i]+'-page');
		if (!page)
			continue;
			
		c = page.getAttribute('class');
		if (c != null && c.indexOf('large-tab') != -1)
			c = 'large-tab ';
		else
			c = '';

		if (pages[i] == pageName)
			c += 'active ';
			
		c = c.trim();
		
		if (c != '')
			page.setAttribute('class', c);
		else
			page.removeAttribute('class');
	}

	if (doHash) {
		location.hash = pageName;
	}                           
  	                            
	var form = document.forms['posting'];
	if (form != null)  
		form.setAttribute('action', form.getAttribute('action').split('#', 1) +   
			(pageName != pages[0] ? '#' + pageName : ''));
}

function initPages(pagesName) {
	pageName = pages[0];
	
	var pagesList = document.getElementById(pagesName+'-pages');
	if (pagesList == null)
		return;
	
	pagesList.setAttribute('class', 'dynamic pages');
 
	for (i = 0; i < pages.length; i++) {			
		if (location.hash == '#'+pages[i])
			pageName = location.hash.substr(1);  
	}

  showPage(pageName, false);
}

// User Options     
var optionValues = new Array();
function updateUserOption(id, defaultValue) {
	var input = document.getElementById('User_option'+id);
	var checkbox = document.getElementById('User_option'+id+'IsOverwritten');
	input.disabled = !checkbox.checked;
	
	if (checkbox.checked && optionValues[id] != undefined) {
		if (input.nodeName.toLowerCase() == 'select')
			input.selectedIndex = optionValues[id] ? 1 : 0;
		else			
			input.value = optionValues[id];
	} else if (!checkbox.checked) {
		if (input.nodeName.toLowerCase() == 'select') {  
			optionValues[id] = input.selectedIndex == 1;
			input.selectedIndex = parseInt(defaultValue);
		}
		else {			              
			optionValues[id] = input.value;
			input.value = defaultValue;
		}
	}
}

/* ================================ Tools ================================ */

function intToLetters(value) {
	var result = '';
	        
	if (value < 1)
		value = 1;
	value--;

	while (value >= 0) {
		var number = value % 26;             
		result = String.fromCharCode(number + 'A'.charCodeAt(0)) + result;
		value = Math.floor(value / 26)-1;
	}
	
	if (result == '')
		result = 'A';
	
	return result;
}

function lettersToInt(value) {
	var result = 0;
	value = value.toUpperCase();	

	for(var i = 0; i < value.length; i++) {
		var letter = value[i];
		var number = letter.charCodeAt(0)-'A'.charCodeAt(0);
		if (number >= 0 && number <= 25)
			result = result * 26 + number+1;		
	} 
	
	return result;
}

// Lists
var items = new Array();
function addListItem(element) {
	items.length++;
	items[items.length-1] = element;
}

function selectAllItems(element) {
	var checked = element.checked; 

	for (var i = 0; i < items.length; i++) {
		items[i].checked	= checked;
	}
}

// Cookies
function setCookie(name, value, expires) {
	var str = cookiePrefix + name + '=' + value;
	if (expires != null) {
		var date = new Date(new Date().getTime() + expires);
		str += '; expires=' + date.toGMTString()+';';
	}
	document.cookie = str;
}

function getCookie(name) {
	var cookie = document.cookie;
	var res = '';
	while(cookie != '') {
		var thisName = cookie.substring(0, cookie.search('=')).trim();
		if (thisName == cookiePrefix + name) {
			var end = cookie.search(';');
			if (end < 0)
				end = cookie.length;
			return cookie.substring(cookie.search('=') + 1, end);
		}

		var index = cookie.search(';') + 1;
		if(index == 0) index = cookie.length;
		cookie = cookie.substring(index, cookie.length);
 	}
	return null;
}

function deleteCookie(name) {
	document.cookie = cookiePrefix + name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
} 
