function require(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
}

var newPrototype = ((typeof Prototype != 'undefined') || convertVersionString(Prototype.Version) < convertVersionString('1.6.0'))

function createListener(id,method){
//declaring the class
alert(id+ ' ' + method);
var CheckboxWatcher = Class.create();

//defining the rest of the class implementation
CheckboxWatcher.prototype = {

  initialize: function(chkBox, message) {
    this.chkBox = $(chkBox);
    this.message = message;
    //assigning our method to the event

    this.chkBox.onclick = this.showMessage.bindAsEventListener(this);
  },

  showMessage: function(evt) {
    alert(this.message + ' (' + evt.type + ')');
  }
};

var watcher = new CheckboxWatcher(id, method);
}

/**
@param string rowid the id o fthe row you want to make disappear
@param oject  opts  Effect options such as {duration:3}
*/
function fadeTableRow(rowid,opts){
	element = $(rowid);
	if(!opts){
	    opts = {};
	}
	if(Element.visible(element)) {	

	    var row  = $(rowid);
	    var cells= row.childNodes;
	    for(i=0;i<cells.length;i++){
	        if(cells[i].tagName == 'TD'){
	            new Effect.Fade(cells[i],opts);
	        }
	    }
	    new Effect.Fade(row,opts);
	} else {

	    var row  = $(rowid);
	    var cells= row.childNodes;
	    for(i=0;i<cells.length;i++){
	        if(cells[i].tagName == 'TD'){
	            new Effect.Appear(cells[i],opts);
	        }
	    }
	    new Effect.Appear(row,opts);
	}
}

/**
@param string rowid the id o fthe row you want to make disappear
@param oject  opts  Effect options such as {duration:3}
*/
function SlideUpAndDownSet(id,opts){
	element = $(id);
	if(Element.visible(element)) {	
	    if(!opts){
	        opts = {};
	    }
	    var row  = $(id);
	    var cells= row.childNodes;
	    for(i=0;i<cells.length;i++){
	        if(cells[i].tagName == 'TD'){
	            new Effect.SlideUp(cells[i],opts);
	        }
	    }
	    new Effect.SlideUp(row,opts);
	} else {
		if(!opts){
	        opts = {};
	    }
	    var row  = $(id);
	    var cells= row.childNodes;
	    for(i=0;i<cells.length;i++){
	        if(cells[i].tagName == 'TD'){
	            new Effect.SlideDown(cells[i],opts);
	        }
	    }
	    new Effect.SlideDown(row,opts);
	}
}


function switchBtnText(id,visibleText,invisibleText){
	element = $(id);
	
	testtext=visibleText.toLowerCase();
	if (element.innerHTML.toLowerCase() == testtext.toLowerCase()){
		element.innerHTML = invisibleText;
	} else {
		element.innerHTML = visibleText;
	}
	
}


function updateCheckbox(formname,values) {

    var what = formname;
	var i=0;
alert(what);
	alert("Length: "+what.length);
alert("Length1: "+values.length);
alert("Length1: "+values);
    for (i=0; i<what.length; i++) {
		alert("what["+i+"]: "+what[i].value);

    }
}


function replaceChars(text,search_str,replace_str) {
	var result = text;
	var count=result.length;
	var search = search_str.split(",");
	var replace = replace_str.split(",");
	for (i=0;i<search.length;i++){
		search[i] = new RegExp(search[i]);
		for (j=0;j<count;j++){
			result = result.replace(search[i],replace[i]);
		}		
	}	
	return result;
}


// SORTABLES

	function createNewSection(name,parentid) {
		//var name = $F('sectionName');
		if (name != '') {
			var newDiv = Builder.node('div', {id: 'group' + (sections.length + 1), className: 'section', style: 'display:none;' }, [
				Builder.node('h3', {className: 'handle'}, name)
			]);

			sections.push(newDiv.id);
			$(parentid).appendChild(newDiv);
			Effect.Appear(newDiv.id);
			destroyLineItemSortables();
			createLineItemSortables();
			createGroupSortable();
		}
	}

	function createLineItemSortables() {
		for(var i = 0; i < sections.length; i++) {
			Sortable.create(sections[i],{tag:'div',dropOnEmpty: true, containment: sections,only:'lineitem'});
		}
	}

	function destroyLineItemSortables() {
		for(var i = 0; i < sections.length; i++) {
			Sortable.destroy(sections[i]);
		}
	}

	function createGroupSortable() {
		Sortable.create('page',{tag:'div',only:'section',handle:'handle'});
	}
	
/** **/
var myGlobalHandlers = {
	onCreate: function(){
		//Element.show('systemWorking');
		if ($('systemWorking') != null) new Effect.Appear('systemWorking',{ duration: 0.5 });
	},
	onComplete: function() {
		if(Ajax.activeRequestCount == 0){
		//	Element.hide('systemWorking');
		if ($('systemWorking') != null) new Effect.Fade('systemWorking', { duration: 0.5 });
		}
	}
};
Ajax.Responders.register(myGlobalHandlers);	


 
 function elementNameToArray(element){
	if (typeof element == 'string') element = $(element);	
	if (!element || !element.getElementsByTagName){ return; }
	result = '';
	var inputs = element.getElementsByTagName('input');
	// loop through all input  tags
	var textAreas = element.getElementsByTagName('textarea');
	// loop through all input  tags
	for (var i=0; i<inputs.length; i++){
		var single_element = inputs[i];
		
		if ( single_element.name.substr( single_element.name.length-2,2) != '[]') single_element.name = single_element.name + '[]';
	}
	for (var i=0; i<textAreas.length; i++){
		var single_element = textAreas[i];
		
		if ( single_element.name.substr( single_element.name.length-2,2) != '[]') single_element.name = single_element.name + '[]';
	}
	
 }
 
 

function myCloneNodeNeu(source){
	if (typeof source == 'string') source = $(source);	
	if (!source) return null;
	if (source.getAttribute && source.getAttribute('name')) alert(source.getAttribute('name'));
	var tmpNode = source.cloneNode(true);	
	
	if (source.hasChildNodes()){
		for (i=0;i<source.childNodes.length;i++){
			test = myCloneNodeNeu(source.childNodes[i]);
			tmpNode.appendChild(test);
		}
	}
	return tmpNode;
}


function myCloneNode(node,index,id,source){
	var i;	
	node = Element.cleanWhitespace(node);
	if (node == null) return;	
	var MyRegExp = new RegExp('_function');	
	if (node.value) node.value = '';
	if (node.getAttribute){
		if (node.getAttribute('onclick') && String(node.getAttribute('onclick')).search(MyRegExp) != -1) 
			node.setAttribute('onClick',String(node.getAttribute('onclick')).replace(MyRegExp, id+'_'+index));
			node.setAttribute('onClick',String(node.getAttribute('onclick')).replace(MyRegExp, id+'_'+index));
		if (node.getAttribute('onclick') && String(node.getAttribute('onClick')).search(MyRegExp) != -1) 
			node.setAttribute('onClick',String(node.getAttribute('onClick')).replace(MyRegExp, id+'_'+index));
			node.setAttribute('onClick',String(node.getAttribute('onclick')).replace(MyRegExp, id+'_'+index));
		if (node.getAttribute('name')) node.setAttribute('name',node.name);
		
		if (node.getAttribute('id')) node.setAttribute('id',node.id+'_'+index);
	}
	if (node.hasChildNodes()){
		for (i=0;i<node.childNodes.length;i++){
			myCloneNode(node.childNodes[i],index,id);
		}
	}
	return node
}

function request (	url,			// request url
					id,				// id of container where the output is rendered into
					params,			// Ajax.Request parameter hash
					collect,		// ?
					enctype,		// ?
					success_extra,	// extra javascript code that is evaluated on success (string)
					attach,			// ?
					fade,			// ?
					blind,			// ?
					update,			// ?
					show_error_id,	// ?
					show_error_container_id // ?
					) {
	url = (url.search('index') < 0)?'/index.php?action='+url:url;
	id = (id == undefined || id.length <= 0)?'column2_right_main_without_teaser':id;
	if ((show_error_container_id == undefined || show_error_container_id.length <= 0) && (show_error_id != undefined && show_error_id.length > 0)) show_error_container_id = show_error_id+'_container';
	show_error_id = (show_error_id == undefined || show_error_id.length <= 0)?'global_error_stack_output':show_error_id;	
	show_error_container_id = (show_error_container_id == undefined || show_error_container_id.length <= 0)?'global_error_stack_output_container':show_error_container_id;
	show_error_element = (show_error_id == undefined || show_error_id.length <= 0 || !show_error_id || $(show_error_id) == null)?false:$(show_error_id);
	show_error_element_container = (show_error_container_id == undefined || show_error_container_id.length <= 0 || !show_error_container_id || $(show_error_container_id) == null)?false:$(show_error_container_id);
	attach = (attach == undefined || attach.length <= 0 || attach == 0 || attach == false)?false:true;
	fade = (fade == 0 || fade == false)?false:true;
	update = (update == 0 || update == false)?false:true;
	blind = (blind == 0 || blind == false || blind == undefined)?false:true;
	collect = (collect == undefined)?false:collect;
	enctype = (enctype == undefined || enctype.length <= 0)?'multipart/form-data':enctype;
	element = $(id);
	var formParams = (collect)?getFormParams(document,true):'';
	var post = (formParams != '')?formParams:'';
	if (params != '' && params != undefined && params != null){

		if (typeof post == 'object' || typeof params == 'object'){
			if (typeof post != 'object') post = new Object();
			if (typeof params == 'string') params = params.toQueryParams();
			Object.extend(post,params);
		} else {
			post += (post != '')?'&':'';
			post += (params);
		}
	}
	if (url.search('index') < 0){
		Object.extend(post,{'action' : url});
	}
//	var postObj = post.toQueryParams();
	if (typeof post == 'object' ) post = (post.toQueryString)?post.toQueryString():$H(post).toQueryString() ;
	
	
	var opt = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: post,	
		// Encoding
		encoding: 'ISO-8859-1',	
		 // Handle successful response
		onSuccess: function(t) {
			var new_content = unescape(t.responseText);
			// *#*#*#*#*#*#* ersetzen...
			if (new_content.search(/\*#\*#\*#\*#\*#\*#\*/g) >= 0){
				new_content = new_content.replace(/\*#\*#\*#\*#\*#\*#\*/g, '\\');
			} else {
				new_content = new_content;
			}
			
			//alert(new_content);
			
			// Error Handling...
			if (new_content.indexOf('error;') == 0){
				if (show_error_element != false){
					var errormessage = new_content.replace(/error;/,'');					
					Element.update(show_error_element,errormessage);
					new Effect.Appear(show_error_element_container,{queue:'end'});
					new Effect.Fade(show_error_element_container,{queue:'end',delay:10});
				}
			} else {
				
				if (update){
					
					if (new_content != 'kb_error' && (element != null || id == '')){
						if (id != ''){
							new_content = (attach)? element.innerHTML + new_content : new_content;
							Element.update(element,new_content.getInnerHtmlById(id));
						}
						if (success_extra != undefined && success_extra.length > 0 && new_content.indexOf('error;') != 0){
							//alert('executing success_extra!');
							eval(success_extra);
						}
						
					} else {
						//alert('an error occurred!');
						if (element == null) alert('Das Element mit der id '+id+' existiert nicht !!!');
						if (new_content == 'kb_error') alert('interner Fehler !!!');
						
					}
					if (blind && element != null && (!element.visible() || element.style.opacity <= 0.5))  new Effect.BlindDown(id,{ duration: 1.0, queue: 'end' });
					if ((!is_ie6) && fade && element != null && (!element.visible() || element.style.opacity <= 0.5))  new Effect.Opacity(id,{ duration: 1.0,transition: Effect.Transitions.linear,from: 0.01, to: 1.0, queue: 'end' });
				} else {
					if (success_extra != undefined && success_extra.length > 0){
						eval(success_extra);
					}
				}
				
			}
		},
		// Handle 404
		on404: function(t) {
			alert('Error 404: location "' + t.statusText + '" was not found.');
		},		

		// Handle other errors
		onFailure: function(t) {
			alert('Error ' + t.status + ' -- ' + t.statusText);
		}
	}

	if (update){
		if (blind && element != null && (element.visible() || element.style.opacity > 0.5))  new Effect.BlindUp(id,{ duration: 1.0});
		if ((!is_ie6) && fade && element != null && (element.visible() || element.style.opacity > 0.5))  new Effect.Opacity(id,{ duration: 0.5,transition: Effect.Transitions.linear,from: 1.0, to: 0.01 });
	}
	new Ajax.Request(url, opt);
}

function kb_request(options){
	var url 	= (options && options.url)?options.url : '/index.php';
	var action 	= (options && options.action)? $H({ action: options.action}) : $H({});
	var id  	= (options && options.id )?options.id : 'column2_right_main_without_teaser';
	var params  = (options && options.params )?options.params : null;
	var collect = (options && options.collect != undefined )?options.collect : false;
	var attach  = (options && options.attach != undefined )?options.attach : false;
	var fade  	= (options && options.fade != undefined )?options.fade : true;
	var blind  	= (options && options.blind != undefined )?options.blind : false;
	var update 	= (options && options.update != undefined )?options.update : true;
	var success_extra = (options && options.onComplete )?options.onComplete : '';
	var show_error_id = (options && options.errorId )?options.errorId : 'global_error_stack_output';
	var show_error_container_id = (options && options.errorContainerId )?options.errorContainerId : 'global_error_stack_output_container';
	var element = $(id);
	
	show_error_element = (show_error_id == undefined || show_error_id.length <= 0 || !show_error_id || $(show_error_id) == null)?false:$(show_error_id);
	show_error_element_container = (show_error_container_id == undefined || show_error_container_id.length <= 0 || !show_error_container_id || $(show_error_container_id) == null)?false:$(show_error_container_id);

	var formParams = (collect)?getFormParams($(collect),true):'';	
	var post = (formParams != '') ? formParams:'';
	
	var destId = (formParams && formParams.get)?formParams.get('destId'):'';
	destId = (Object.isString(destId))?destId : (destId[0])?destId[0] : '';
	if (!element && destId){
		element =  $(destId);
		id = destId;
	}
	
	if (params != '' && params != undefined && params != null){
		if (typeof post == 'object' || typeof params == 'object'){
			if (typeof post != 'object') post = new Object();
			if (typeof params == 'string') params = params.toQueryParams();
			Object.extend(post,params);
		} else {
			post += (post != '')?'&':'';
			post += (params);
		}
	}

	post = $H(post).merge(action);
	
	if (typeof post == 'object' ) post = (post.toQueryString)?post.toQueryString():$H(post).toQueryString() ;
	
	var opt = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: post,	
		// Encoding
		encoding: 'ISO-8859-1',	
		 // Handle successful response
		onSuccess: function(t) {
			var new_content = unescape(t.responseText);
			// *#*#*#*#*#*#* ersetzen...
			if (new_content.search(/\*#\*#\*#\*#\*#\*#\*/g) >= 0){
				new_content = new_content.replace(/\*#\*#\*#\*#\*#\*#\*/g, '\\');
			} else {
				new_content = new_content;
			}
			
			// Error Handling...
			if (show_error_element != false && new_content.indexOf('error;') == 0){
				var errormessage = new_content.replace(/error;/,'');
				
				Element.update(show_error_element,errormessage);
				new Effect.Appear(show_error_element_container,{queue:'end'});
	//			new Effect.Opacity(show_error_element,{ duration: 0.5,transition: Effect.Transitions.linear,from: 0.001, to: 1.0 ,queue:'end'});
				new Effect.Fade(show_error_element_container,{queue:'end',delay:10});
	//			new Effect.Opacity(show_error_element,{ duration: 0.5,transition: Effect.Transitions.linear,from: 1.0, to: 0.001 ,queue:'end',delay:5});
			} else {
				
				if (update){
					
					if (new_content != 'kb_error' && (element != null || id == '')){
						if (id != ''){
							new_content = (attach)? element.innerHTML + new_content : new_content;
							Element.update(element,new_content.getInnerHtmlById(id));
						}
						if (success_extra != undefined && success_extra.length > 0 && new_content.indexOf('error;') != 0){
							eval(success_extra);
						}
						
					} else {
						if (element == null) alert('Das Element mit der id '+id+' existiert nicht !!!');
						if (new_content == 'kb_error') alert('interner Fehler !!!');
						
					}
					if (blind && element != null && (!element.visible() || element.style.opacity <= 0.5))  new Effect.BlindDown(id,{ duration: 1.0, queue: 'end' });
					if ((!is_ie6) && fade && element != null && (!element.visible() || element.style.opacity <= 0.5))  new Effect.Opacity(id,{ duration: 1.0,transition: Effect.Transitions.linear,from: 0.01, to: 1.0, queue: 'end' });
				} else {
					if (success_extra != undefined && success_extra.length > 0){
						eval(success_extra);
					}
				}
				
			}
		},
		// Handle 404
		on404: function(t) {
			alert('Error 404: location "' + t.statusText + '" was not found.');
		},		

		// Handle other errors
		onFailure: function(t) {
			alert('Error ' + t.status + ' -- ' + t.statusText);
		}
	}

	if (update){
		if (blind && element != null && (element.visible() || element.style.opacity > 0.5))  new Effect.BlindUp(id,{ duration: 1.0});
		if ((!is_ie6) && fade && element != null && (element.visible() || element.style.opacity > 0.5))  new Effect.Opacity(id,{ duration: 0.5,transition: Effect.Transitions.linear,from: 1.0, to: 0.01 });
	}
	new Ajax.Request(url, opt);
}

function upload(){
// hide old iframe
    var par = window.parent.document;
    var num = par.getElementsByTagName('iframe').length - 1;
    var iframe = par.getElementsByTagName('iframe')[num];
    iframe.className = 'hidden';

    // create new iframe
    var new_iframe = par.createElement('iframe');
    new_iframe.src = 'data/upload.php';
    new_iframe.frameBorder = '0';
    par.getElementById('iframe').appendChild(new_iframe);

    // add image progress
    var list = par.getElementById('list');
    var new_div = par.createElement('div');
    var new_img = par.createElement('img');
    new_img.src = '/img/lightbox/loading.gif';
    new_img.className = 'load';
    new_div.appendChild(new_img);
    list.appendChild(new_div);

    // send
    var imgnum = list.getElementsByTagName('div').length - 1;
    document.iform.imgnum.value = imgnum;
    document.iform.submit();
}





function startCallback(){
	//alert('start');
	
	if ($('systemWorking') != null) new Effect.Appear('systemWorking',{ duration: 0.5 });
	if ((!is_ie6)){
		new Effect.Opacity('album_fotos_id',
	    { duration: 1.0, 
	      transition: Effect.Transitions.linear, 
	      from: 1.0, to: 0.2 });
		 new Effect.Opacity('group_new_pictures_id',
	    { duration: 1.0, 
	      transition: Effect.Transitions.linear, 
	      from: 1.0, to: 0.2 });
	}
	return true;
}

function completeCallback(response,error){
	//alert('complete');
	if ($('systemWorking') != null) new Effect.Fade('systemWorking',{ duration: 0.5 });
	
	response =	unescape(response);
	error = response.indexOf('error;') == 0;
	var errormessage = response.replace(/error;/,'');
				
	if (!error){
		$('album_fotos_id').innerHTML += unescape(errormessage);		
	} else {
		Element.update('global_error_stack_output',unescape(errormessage));

		new Effect.Appear('global_error_stack_output_container',{queue:'end'});
		new Effect.Fade('global_error_stack_output_container',{queue:'end',delay:10});
		
	
	}
	if ((!is_ie6)){
		new Effect.Opacity('album_fotos_id',
	    { duration: 1.0, 
	      transition: Effect.Transitions.linear, 
	      from: 0.2, to: 1.0 });
		new Effect.Opacity('group_new_pictures_id',
	    { duration: 1.0, 
	      transition: Effect.Transitions.linear, 
	      from: 0.2, to: 1.0 })  
	}
	/* 
	  $template_output = '<!-- ERROR: Falsches Format -->';
			$template_output.= '<script>'."\n";
			$template_output.= "\t".'var elem = $(\'photoalbum_file_submit_error\');'."\n";
			$template_output.= "\t".'Element.update(elem,\'blablabla\');'."\n";
			$template_output.= '</script>'."\n";*/
	clearFormParams('group_new_pictures_id');
}

function switchElements(element1,element2,fade){
	fade = (fade == 1 || fade == true)?true:false;
	element1 = $(element1);
	element2 = $(element2);
	hide = ((element2.style.display == 'none' || !element2.visible) || !(element1.style.display == 'none' || !element1.visible))?element1:element2;
	show = ((element2.style.display == 'none' || !element2.visible) || !(element1.style.display == 'none' || !element1.visible))?element2:element1;	
//	new Effect.Opacity(hide,{ duration: 0.5,transition: Effect.Transitions.linear,from: 1.0, to: 0.001 });
//	new Effect.Opacity(show,{ duration: 0.5,transition: Effect.Transitions.linear,from: 0.001, to: 1.0, queue: 'end' });
	if (!is_ie6 && fade && false){
		new Effect.Fade(hide, {duration:0.1});
		new Effect.Appear(show,{ queue: 'end', duration:0.1});	
	} else {
		Element.hide(hide);
		Element.show(show);
	}
}


function numVal(element) {
	var num = element.value.charAt(element.value.length-1);
	var ValidChars = "0123456789";
	if (ValidChars.indexOf(num) == -1) {
		element.value = element.value.substring(0, element.value.length-1);
	}
	//alert(element.value + ' -> '+num);
	
}

// 
function getInnerHtmlById(n) {
	secure = 400; /* SicherheitsZähler der zur Not die schleife abbricht... */

	typeExpr = new RegExp("<([a-zA-Z]*)[^>]*id=."+n+"[^>]*>");
	if ((n.length == 0) || (this.indexOf(n) == -1) || this.search(typeExpr)  == -1) return this;
	
	
	type = this.match(typeExpr)[1];	
	
	var front = ''
	var end = ''		
	if (type == null || type == undefined) return false;
	startExpression = new RegExp("<"+type+"[^>]*id=."+n+"[^>]*>");	
	startDivExp = new RegExp("<"+type+"[^>]*>");	
	endDivExp =  new RegExp("</"+type+">");
	
	startTag = new String(this.match(startExpression));
	startIndex = this.search(startTag) + startTag.length;

	var txt = new String(this.substr(startIndex)).replace(/<!--.*-->/,'');
	endMatch = txt.match(endDivExp);
	endIndex = 6 + txt.search(endDivExp);
	
	front = txt.substr(0,endIndex);
	end = txt.substr(endIndex);
	var lastIndex = endIndex;
	startMatch = front.split('<'+type);
	frontCount = 0;
	if (startMatch != null){
			startMatch = startMatch.uniq();
			frontCount += startMatch.length-1;
	}
	
	while (frontCount > 0 && --secure){
		endMatch = end.match(endDivExp);
		endIndex = 6 + end.search(endDivExp);
		lastIndex += endIndex;
		front = end.substr(0,endIndex);
		end = end.substr(endIndex);
	
		startMatch = front.split('<'+type);
		if (startMatch != null){
			startMatch = startMatch.uniq();
			frontCount += startMatch.length-1;
		}		
		frontCount--;
	}
	result = txt.substr(0,lastIndex-6);
	//alert(result);
	return result;
}

String.prototype.getInnerHtmlById = getInnerHtmlById
 

var AjaxQueue = {
	batchSize: 1, //No.of simultaneous AJAX requests allowed, Default : 1
	urlQueue: [], //Request URLs will be pushed into this array
	elementsQueue: [], //Element IDs of elements to be updated on completion of a request ( as in Ajax.Updater )
	optionsQueue: [], //Request options will be pushed into this array
	setBatchSize: function(bSize){ //Method to set a different batch size. Recommended: Set batchSize before making requests
		this.batchSize = bSize;
	},
	push: function(url, options, elementID){ //Push the request in the queue. elementID is optional and required only for Ajax.Updater calls
		this.urlQueue.push(url);
		this.optionsQueue.push(options);
		if(elementID!=null){
			this.elementsQueue.push(elementID);
		} else {
			this.elementsQueue.push("NOTSPECIFIED");
		}

		this._processNext();
	},
	_processNext: function() { // Method for processing the requests in the queue. Private method. Don't call it explicitly
		if(Ajax.activeRequestCount < AjaxQueue.batchSize) // Check if the currently processing request count is less than batch size
		{	
			if(AjaxQueue.elementsQueue.first()=="NOTSPECIFIED") { //Check if an elementID was specified
				// Call Ajax.Request if no ElementID specified
				//Call Ajax.Request on the first item in the queue and remove it from the queue
				new Ajax.Request(AjaxQueue.urlQueue.shift(), AjaxQueue.optionsQueue.shift()); 
				
				var junk = AjaxQueue.elementsQueue.shift();
			} else {
				// Call Ajax.Updater if an ElementID was specified.
				//Call Ajax.Updater on the first item in the queue and remove it from the queue
				new Ajax.Updater(AjaxQueue.elementsQueue.shift(), AjaxQueue.urlQueue.shift(), AjaxQueue.optionsQueue.shift());				
			}		
		}
	}
};
Ajax.Responders.register({
  //Call AjaxQueue._processNext on completion ( success / failure) of any AJAX call.
  onComplete: AjaxQueue._processNext
});


setPrevLink = function(current){
	var link = $('photobox_prev_link');	
	var imgNext = $('photobox_next_img');
	var imgPrev = $('photobox_prev_img');	
	if (current == 1){
		imgPrev.src = '/tmpl/onefamily/img/photobox_prev.gif';
	//	alert(imgPrev.src);
	} else if (current == 2) {
		imgPrev.src = '/tmpl/onefamily/img/photobox_prev_active.gif';
	//	alert(imgPrev.src);
	}

}

setNextLink = function(current){
	var link = $('photobox_next_link');
	var imgNext = $('photobox_next_img');
	var imgPrev = $('photobox_prev_img');	
	if (current == pages){
		imgNext.src = '/tmpl/onefamily/img/photobox_next.gif';
	//	alert(imgNext.src);
	} else if (current == pages-1) {
		imgNext.src = '/tmpl/onefamily/img/photobox_next_active.gif';
	//	alert(imgNext.src);
	}
}

setNaviLinks = function(current){
//	alert(current);
	setPrevLink(current);
	setNextLink(current);
}
			

		

function increaseIndexRec(node,options){
	if (!node) return;
	if (!node.getAttribute) return;
	if (!node.getAttribute('id')) return; 
	
	var regexpr = (options && options.regexpr)?options.regexpr:'';
	regexpr = (regexpr.length > 0)?new RegExp(regexpr):'';
	
	node = Element.cleanWhitespace(node);
	
	if (node.hasChildNodes && node.hasChildNodes()){
		for (var i=0;i<node.childNodes.length;i++){
			increaseIndexRec(node.childNodes[i],options);			
		}
	}
	
	if (regexpr.length == 0 || node.id.search(regexpr) != -1 ) {
		var index = new Number(node.id.match(/\d+/));
		new_index = index + 1;
//	if (new_index == id) new_index = ++index;
		new_id = node.id.replace(/\d+/,new_index);
		node.id = new_id;
	} else {
		var index = new Number(node.id.match(regexpr));
		new_index = index + 1;
//	if (new_index == id) new_index = ++index;
		new_id = node.id.replace(/\d+/,new_index);
		node.id = new_id;
	}
}

function increaseNameRec(node,options){
	if (!node) return;


	var regexpr = (options && options.regexpr)?options.regexpr:'';
	var index = (options && options.index)?options.index:new Number(node.id.match(/\d+/));
	
	if (!options){
		options = new Object();
		options.index = index;
	} else {
		options.index = index;
	}
	regexpr = (regexpr.length > 0)?new RegExp(regexpr):'';
	
	node = Element.cleanWhitespace(node);
	
	if (node.hasChildNodes && node.hasChildNodes()){
		for (var i=0;i<node.childNodes.length;i++){
			increaseNameRec(node.childNodes[i],options);			
		}
	}
		
	if (!node.getAttribute) return;
	if (!node.getAttribute('name')) return;
	
		
	//if (regexpr.length == 0 || node.id.search(regexpr) != -1 ) {
		//var index = new Number(node.id.match(/\d+/));
		new_index = index;
		new_name = node.name.replace(/\d+/,new_index);
		node.name = new_name;
//	} else {
//		var index = new Number(node.name.match(regexpr));
//		new_index = index + 1;
//	if (new_index == id) new_index = ++index;
//		new_name = node.name.replace(regexpr,new_index);
//		node.name = new_name;
//	}
}


setFunctionIds = function (node,options){
	if (!node) return;	
	var targetattribute = (options && options.attribute)?options.targetattribute:'onclick';
	var sourceattribute = (options && options.sourceattribute)?options.sourceattribute:'rel';
	var jFunction = (options && options.jFunction)?options.jFunction:'';
	var regexpr = (options && options.regexpr)?options.regexpr:'';
	var replace = (options && options.replace)?options.replace:'';
	var newValue = '';
	var myregexpr = (regexpr.length > 0 && typeof regexpr == 'string' )?new RegExp(regexpr):regexpr;
	
	node = Element.cleanWhitespace(node);
	
	if (node.hasChildNodes && node.hasChildNodes()){
		for (var i=0;i<node.childNodes.length;i++){
			setFunctionIds(node.childNodes[i],options);			
		}
	}
	

	
	if (node.getAttribute && node.getAttribute(sourceattribute)){
		var value = new String(node[sourceattribute]);
	//	alert(value );
		if (jFunction.length > 0){
			var oldFuncRegExp = new RegExp(jFunction+'\([^\)]*\)');
			var oldFunc = value.match(oldFuncRegExp);
			var newFunc = (regexpr.length > 0 && oldFunc.search(regexpr) > -1)?oldFunc.replace(regexpr,replace):oldFunc;
			newValue = value.replace(oldFuncRegExp,newFunc);
		} else {
			newValue = (regexpr.length > 0 && value.search(myregexpr) > -1)?value.replace(myregexpr,replace):value;			
		}
		
		evalString = 'node[\''+targetattribute+'\'] = function(){'+newValue+'return false;}';
		eval(evalString);
	//	if (attribute == 'onclick'){
		//	node.onclick = newValue;
	//	} else {
	//		node.setAttribute(attribute,newValue);
	//	}
	//	alert(node.onclick);
	}
}


params2Object = function(options){
	var cDivider = (options && options.divider)?options.divider:new Array();
	var result = new Array();
	
	tmp = this.split(((cDivider[0])?cDivider[0]:'&'));
	for (i=0;i<tmp.length;++i){		
		value = tmp[i].split(((cDivider[1])?cDivider[1]:'='));
		result[value[0]] = value[1];
	}
	return result;
}

params2Array = function (options){
	var cDivider = (options && options.divider)?options.divider:new Array();
	var value;
	var tmp;
	var tmpIndex;
	var index1;
	var index2;
	var result = new Array();
	tmp = this.split(((cDivider[0])?cDivider[0]:'&'));
	tmpIndex1 = -1;
	tmpIndex2 = -1;
	index2 = 0;
	index1 = -1;
	for (i=0;i<tmp.length;++i){
		value = tmp[i].split("=");
		tmpIndex1 = new Number(value[0].match(/\d+/));
		if (tmpIndex2 > tmpIndex1 || tmpIndex2 < tmpIndex1){
			tmpIndex2 = tmpIndex1;
			index2 = 0;
			++index1;
			result[index1] = new Array();
		} else {
			++index2;
		}
		result[index1][index2] = value[1];
	}
	return result;
}


String.prototype.toParamObject = params2Object;
String.prototype.toParamArray = params2Array;

buildNewsTag = function  (parameters){
	var name = (parameters.name)?parameters.name:'';
	var source = (parameters.source)?parameters.source:'';
	source = $(source);
	var returnString = '';
	var params = getFormParams(source);		
	var paramsObject = new Object();
	paramsObject = params.toParamObject();
	
	var id = (paramsObject[name])?paramsObject[name]:'';
	var group = (paramsObject[name+'_my_group_id'])?paramsObject[name+'_my_group_id']:'';
	var limit = (paramsObject[name+'_my_limit'])?paramsObject[name+'_my_limit']:'';
	var random = (paramsObject[name+'_my_random'])?paramsObject[name+'_my_random']:'';
	var style = (paramsObject[name+'_my_style'])?paramsObject[name+'_my_style']:'';
	
	/*
	$vals[0]['attributes']['GROUP_ID'] 	= (isset ($params_array[0]) && is_numeric($params_array[0])) ? $params_array[0] : null;
				$vals[0]['attributes']['STYLE'] 	= (isset ($params_array[1])) ? $params_array[1] : null;
				$vals[0]['attributes']['LIMIT'] 	= (isset ($params_array[2])) ? $params_array[2] : null;
				$vals[0]['attributes']['RANDOM'] 	= (isset ($params_array[3])) ? $params_array[3] : null;
	*/
	returnString = 'NEWS['+group+','+style+','+limit+','+random+']NEWS';
			
	var adv_news = $(name+'_id');
	if (adv_news){
		adv_news.value=returnString;
	} else {
		var hidden_string = document.createElement("input");
		hidden_string.type = 'hidden';
		hidden_string.id = name+'_id';
		hidden_string.value = returnString;
		hidden_string.name = name;
		parent_node = source.parentNode.parentNode;
		parent_node.appendChild(hidden_string);
	}
	return encodeURI(returnString);
}	

buildCategoryTag = function  (parameters){
	var name = (parameters.name)?parameters.name:'';
	var source = (parameters.source)?parameters.source:'';
	source = $(source);
	if (!source) return '';
	var returnString = '';
	var params = getFormParams(source);		
	var paramsObject = new Object();
	paramsObject = params.toParamObject();
	
	var id = (paramsObject[name])?paramsObject[name]:'';
	var site = (paramsObject[name+'_my_site_id'])?paramsObject[name+'_my_site_id']:'';
	var type = (paramsObject[name+'_my_type'])?paramsObject[name+'_my_type']:'';
	var order = (paramsObject[name+'_my_order'])?paramsObject[name+'_my_order']:'';
	var count = (paramsObject[name+'_my_count'])?paramsObject[name+'_my_count']:'';
	var template = (paramsObject[name+'_my_template'])?paramsObject[name+'_my_template']:'';
	
	returnString = 'CATEGORYPAGE['+site+','+type+','+order+','+count+','+template+']CATEGORYPAGE';
		
	var adv_cat = $(name+'_id');
	if (adv_cat){
		adv_cat.value=returnString;
	} else {
		var hidden_string = document.createElement("input");
		hidden_string.type = 'hidden';
		hidden_string.id = name+'_id';
		hidden_string.value = returnString;
		hidden_string.name = name;
		parent_node = source.parentNode.parentNode;
		parent_node.appendChild(hidden_string);
	}
	return encodeURI(returnString);
}	

buildListTag = function  (parameters){
	var returnString = '';
	var returnHeader = '';
	var returnElements = '';
	
	header = (parameters.header)?parameters.header:'';
	element = (parameters.values)?parameters.values:'';
	rowCount = (parameters.rows)?parameters.rows:'';
	colCount = (parameters.cols)?parameters.cols:2;
	showHeadline = (parameters.show_headline)?parameters.show_headline:0;
	snippet =  (parameters.snippet)?parameters.snippet:'';
	request_name =  (parameters.name)?parameters.name:'';
	
	returnHeader+= snippet+'|'+colCount+'|'+showHeadline;	
	//LISTEN HEADER
	if (typeof header == 'string') header = $(header);	
	if (header && header.getElementsByTagName){
		var params = getFormParams(header,true);
		params = params.toArray();
		if (params.length > 0){
			//var paramsObject = params.toParamArray();
			var paramsObject = params;
		
			/*for (var i=0;i<paramsObject.length;i++){
				if (paramsObject[i]){
					returnHeader += ';';
					for (var j=0;j<paramsObject[i].length;j++){
						returnHeader += (j>0)?',':'';
						returnHeader += paramsObject[i][j];	
					}
				}
			}*/
			for (var i=0;i<paramsObject.length;i++){
				if (paramsObject[i]){
					if (i % colCount == 0) {
						returnHeader += '|';
					} else {
						returnHeader += '~';
					}
					var currentValue = paramsObject[i]['value'][0];
					currentValue = currentValue.replace(/,/g,'##KOMMA##');
					currentValue = currentValue.replace(/;/g,'##SEMI##');
					currentValue = currentValue.replace(/~/g,'##TILDE##');
					returnHeader += currentValue;	
				}
			}
		}
	}
	
	// LISTEN VALUES
	if (typeof element == 'string') element = $(element);	
	if (element && element.getElementsByTagName){ 
		var params = getFormParams(element,true);
		params = params.toArray();
		//var paramsObject = params.toParamArray();
		var paramsObject = params;
		
		for (var i=0;i<paramsObject.length;i++){
			if (paramsObject[i]){
				if (i % colCount == 0) {
					returnElements += '|';
				} else {
					returnElements += '~';
				}
				var currentValue = paramsObject[i]['value'][0];
				currentValue = currentValue.replace(/,/g,'##KOMMA##');
				currentValue = currentValue.replace(/;/g,'##SEMI##');
				currentValue = currentValue.replace(/~/g,'##TILDE##');
				returnElements += currentValue;	
			}
		}
		
		/*for (var i=0;i<paramsObject.length;i++){
			if (paramsObject[i]){
				returnElements += ';';
				for (var j=0;j<paramsObject[i].length;j++){
					returnElements += (j>0)?',':'';
					returnElements += paramsObject[i][j];	
				}
			}
		}*/
	}
	
	returnString = 'ADV_LIST['+returnHeader+returnElements+']ADV_LIST';
	var adv_list = $(request_name+'_id');
	if (adv_list){
		adv_list.value=returnString;
	} else {
		var hidden_string = document.createElement("input");
		hidden_string.type = 'hidden';
		hidden_string.id = request_name+'_id';
		hidden_string.value = returnString;
		hidden_string.name = request_name;
		parent_node = element.parentNode.parentNode;
		parent_node.appendChild(hidden_string);
	}
	return encodeURI(returnString);
}

moveToList = function(source,element,globalindex,id){						
//	element_id = id;
//	--element_id;
	what = (typeof source == 'string')? $(source):source;	
	if (typeof where == 'string') where = $(where);	
	params = getFormParams(what,true);
	//clonable = $(element+(element_id));
	clonable = $(element);
	var tmpNode = clonable.cloneNode(true);	
	tmpNode.style.display = '';
	tmpNode.id = id.replace(/%d/,globalindex);


	increaseIndexRec(tmpNode);
	increaseNameRec(tmpNode,{regexpr:'\\d+'});
	setFunctionIds(tmpNode,{regexpr: id.replace(/%d/,'\\d+'),replace: tmpNode.id});

	
	//increaseIndexRec(what);
	synchNode(tmpNode,params);
	var p = clonable.parentNode;
	p = Element.cleanWhitespace(p);
	clonable.nextSibling.appendChild(tmpNode);

	
}	



editListNode = function(node,options){
	node = $(node);	
	var p = node.parentNode;
	var params = getFormParams(node,true);
//	var paramsObject = params.toArray();
	var paramsObject = params.toArray();
	//paramsObject = (paramsObject[0])?paramsObject[0]:new Array();
	var editElement = (options && options.editElement)?options.editElement:'';
	var editId = (options && options.editId)?options.editId:'';
	var editName = (options && options.editName)?options.editName:'';
	
	p = Element.cleanWhitespace(p);	
	editElement = $(editElement);
	if (!editElement) return;
	
	var tmpEdit = editElement.cloneNode(true);		
	tmpEdit.id = node.id.replace(/row/,'edit');
	setFunctionIds(tmpEdit,{regexpr: 'asset_list_row_edit',replace: tmpEdit.id});
	
	if (!tmpEdit.getElementsByTagName)  return;
	var inputs = tmpEdit.getElementsByTagName('input');
	for (var i=0; i<inputs.length; i++){
		var input = inputs[i];
		var value = (paramsObject[i] && paramsObject[i]['value'])?paramsObject[i]['value']:'';
		if (input.getAttribute && input.getAttribute('type') != 'hidden'){
			input.value = value;
		}
	}	
	
	tmpEdit.style.display = '';
	p.insertBefore(tmpEdit,node);
	Element.hide(node);	
}

cancelEditRow = function(editNode){
	editNode = $(editNode);
	if (editNode){
		var showId = editNode.id.replace(/edit/,'row');
		var showNode = $(showId);
		editNode.parentNode.removeChild(editNode);
		Element.show(showNode);
	}
}

submitEditRow = function(editNode){
	editNode = $(editNode);
	if (editNode){
		var showId = editNode.id.replace(/edit/,'row');
		var showNode = $(showId);
		
		var params = getFormParams(editNode,true);
		synchNode(showNode,params);
		editNode.parentNode.removeChild(editNode);
		Element.show(showNode);
	}
}

removeListNode = function(node){
	node = (typeof node == 'string')? $(node):node;	
	var p = node.parentNode;
	p = Element.cleanWhitespace(p);
	
	
	node.parentNode.removeChild(node);
	
}

newLine2br = function (targetStr) {
    var rn, r, n;
    rn = /\r\n/g;
    r = /\r/g;
    n = /\n/g;
	t = /\t/g;
    targetStr = targetStr.replace(rn, "<br />");
    targetStr = targetStr.replace(r, "<br />");
    targetStr = targetStr.replace(n, "<br />");
    targetStr = targetStr.replace(t, "&nbsp;&nbsp;");
    return targetStr;
}

br2newLine = function (targetStr) {

    targetStr = targetStr.replace(/<br \/>/, "\r\n");
    targetStr = targetStr.replace(/<br>/, "\r\n");
    targetStr = targetStr.replace(/<br\/>/, "\r\n");
    targetStr = targetStr.replace(/&nbsp;&nbsp;/, "\t");
    return targetStr;
}

String.prototype.toRegExpString = function() { // nicht fuer netscape 4;
     return this.replace(/([\^\$\.\*\+\?\=\!\:\|\\\/\(\)\[\]\{\}])/g,"\\$1");
   };
   
 function convertVersionString(versionString){
      var r = versionString.split('.');
      return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);}
	  

function toCursorPointer(e){
	e.element().style.cursor='pointer'
};
function toMovePointer(){this.style.cursor='move'};
	  

require('/ajax/domFunctions.js');


