function CMS_preload(img)
{
	if (!document.images) { return; }
	if (!document.ImgArr) { document.ImgArr = new Array(); }
	
	for(i=0; i < arguments.length; i++) {
		var modstr = ( arguments[i+1] == null ) ? "1" : String(arguments[i+1]);
		document.ImgArr.push(new Image());
		document.ImgArr[document.ImgArr.length-1].src = img.src.substr(0, img.src.lastIndexOf("_")) + "_" + modstr + img.src.substr(img.src.lastIndexOf(".")); 
	}
}



function CMS_imgswap(img, mode)
{
	var modstr = ( mode == null ) ? "0" : String(mode);
	if ( !document.SwpArr ) { document.SwpArr = new Array() };
	while ( document.SwpArr.length > 0 ) 
	{ 
		var swpimg = CMS_swapone(document.SwpArr.pop(), "0");
	}
	CMS_swapone(img, modstr);	
	if ( mode > 0 ) { document.SwpArr.push(img); }
}


function CMS_swapone(img, modstr)
{
	img.src = img.src.substr(0, img.src.lastIndexOf("_")) + "_" + modstr + img.src.substr(img.src.lastIndexOf("."));
}


function CMS_openwin( url, param )
{
	param.l = (param.l) ? param.l : 100;
	param.t = (param.t) ? param.t : 100;
	param.w = (param.w) ? param.w : 800;
	param.h = (param.h) ? param.h : 600;
	
	if ( param.centered ) {
		param.l = (screen.width - param.w) / 2;
		param.t = (screen.height - param.h) / 2;
	}
	
	var winprops = "height="+param.h+",width="+param.w+",top="+param.t+",left="+param.l+",resizable";
	winprops += ( param.scroll != true ) ? ( ",scrollbars=no" ) : ( ",scrollbars=yes" );
	winprops += ( param.status != true ) ? ( ",status=no" ): ( ",status=yes" );
	winprops += ( param.location != true ) ? ( ",location=no" ) : ( ",location=yes" );
	winprops += ( param.menubar != true ) ? ( ",menubar=no" ) : ( ",menubar=yes" );
	
	winname = ( param.name ) ? param.name : "newwindow";	
	win = window.open( url, winname, winprops);
	
	if ( parseInt(navigator.appVersion) >= 4 ) { win.window.focus(); }
}



function CMS_assetswap( imgref, swaptarget, swapurl )
{	
	var swapimg = CMS_findObj(swaptarget);
	swapimg.src = swapurl;
}





function CMS_filitoggle( pRef, pId )
{	
	var lFGLyr = CMS_findObj("Fass_" + pId);
	
	if ( lFGLyr.className.indexOf("filiclose") != -1 ) {
		lFGLyr.className = "fgroup filiopen";
	
	} else {
		lFGLyr.className = "fgroup filiclose";
	}

}









function CMS_openasset( url, param )
{
	param.l = (param.l) ? param.l : 100;
	param.t = (param.t) ? param.t : 100;
	param.w = (param.w) ? param.w : 800;
	param.h = (param.h) ? param.h : 600;
	
	if ( param.centered != undefined ) {
		param.l = (screen.width - param.w) / 2;
		param.t = (screen.height - param.h) / 2;
	}
	
	url = ( url != undefined ) ? url : param.url;
	url = ( url.indexOf("http://") == -1 ) ? "/static/images/" + url : url; 
		
	var winprops = "height="+param.h+",width="+param.w+",top="+param.t+",left="+param.l+",resizable";
	winprops += ( param.scroll != true ) ? ( ",scrollbars=no" ) : ( ",scrollbars=yes" );
	winprops += ( param.status != true ) ? ( ",status=no" ): ( ",status=yes" );
	winprops += ( param.location != true ) ? ( ",location=no" ) : ( ",location=yes" );
	winprops += ( param.menubar != true ) ? ( ",menubar=no" ) : ( ",menubar=yes" );
	
	
	winname = ( param.name ) ? param.name : "newwindow";	
	win = window.open( url, winname, winprops);
	
	if ( parseInt(navigator.appVersion) >= 4 ) { win.window.focus(); }
}




/* * * * * * * * * * * * * * * * * * 
 * find images by name
 *
 * * * * * * * * * * * * * * * * * */
 
function CMS_lnkswap(imgname, mode)
{
	if ( (img = CMS_findObj(imgname)) != null )
	{
		CMS_imgswap(img, mode);
	}
}

function CMS_findObj(obj, scope) 
{ 
  	var p,i,x;  
  
	if (!scope){ scope=document };
	
	if ((( p = obj.indexOf("?")) > 0) && parent.frames.length ) {
		scope = parent.frames[obj.substring(p+1)].document; 
		obj=obj.substring( 0, p );
    }

	if (!(x = scope[obj]) && scope.all) { x = scope.all[obj]; }	
	for( i=0; !x && i < scope.forms.length; i++) { x = scope.forms[i][obj]; }	
	for( i=0; !x && scope.layers && i < scope.layers.length; i++) { x = CMS_findObj( obj, scope.layers[i].document); }
	if ( !x && scope.getElementById ) { x = scope.getElementById(obj); }	
	return x;
}
///////////////////////////////////////////////////////////////////////
//                                                                   //
//                                                                   //
//                                                                   //
///////////////////////////////////////////////////////////////////////

/**
 * @author stefan
 */

if (!CMS || typeof CMS != 'object') {
	var CMS = {};
}


/**
 * 
 * @param {Function} func
 * @param {Object} param
 * @param {Boolex} oal - execute after load, DEFAULT: true
 */
CMS.onload = function(func, param, eal)	{
	if(CMS.onload._executed == true && eal != false)	{
		func(param);
		return;
	}
	
	CMS.onload._stack.push(
		{
			"func"  : func,
			"param" : param
		}
	);
}
CMS.onload._stack = [];
CMS.onload._executed = false;
CMS.onload.execute = function()	{
	var act;
	
	while(CMS.onload._stack.length > 0)	{
		act = CMS.onload._stack.shift();
		act.func(act.param);
	}
	
	CMS.onload._executed = true;
}
window.onload = CMS.onload.execute;

//////////////////////////////
//                          //
//        SearchPage        //
//                          //
//////////////////////////////

CMS.__TMP__ = function()	{
	this.cards = {};
	this.items = {};
	this.preselected = null;
	
	this.registerCard = function(cardId, itemIds)	{
		this.cards[cardId] = new this.IndexCard(this, cardId, itemIds);
	}
	
	this.deselectAll = function()	{
		for ( var i in this.cards ) 	{
			this.cards[i].deselect();
		}
	}
	
	
	this.setPreSelection = function(ids)	{
		this.preselected = ids;
		CMS.onload(this.selectPreselected.bind(this));
	}
	
	this.selectPreselected = function()	{
		for(var i = 0; i < this.preselected.length; i++)	{
			var id = 'CardItem_' + this.preselected[i];
			if(this.items[id] instanceof this.SearchItem)	{
				this.items[id].select();
			}
		}
		
		for(var card in this.cards)	{
			this.cards[card].updateSelection();
		}
	}
	
	this.loadContent = function(itemid)	{
		new Ajax.Request('/XMLHTTPRequest', {
  			method: 'post',
  			parameters: {"cls" : "Category", "id" : itemid.split('_')[1], "method" : "renderXMLHTTPRequest"},
  			onSuccess: this.insertLoadedContent.bind(this)
  		});
	}
	
	this.insertLoadedContent = function(transport, json)	{
		$('left').innerHTML = transport.responseText;
		$('left').style.visibility = 'visible';
	}
	
	this.hideLoadedContent = function()	{
		$('left').innerHTML = '';
		$('left').style.visibility = 'hidden';
	}
	
	this.validate = function()	{
		var hasSelected = false;
		for( var id in this.items )	{
			if(this.items[id].isSelected())	{
				hasSelected = true;
				break;
			}
		}
		if(hasSelected)	{
			document.forms[0].submit();
		}
		return false;
	}
	
	
	this.IndexCard = function(parent, cardId, itemIds)	{
		this.parent = parent;
		this.cardId = cardId;
		this.itemIds = itemIds;
		
		this.items = [];
		
		this.init = function()	{
			this.dom = $(this.cardId)
			this.dom.onclick = this.select.bind(this);
			
			this.input = this.dom.getElementsByTagName('input')[0];
			this.input.onclick = this.selectItems.bind(this);
			
			this.span = this.dom.getElementsByTagName('span')[0];
			
			this.container =$('Items_' + this.cardId);
			
			for( var i = 0; i < this.itemIds.length; i++)	{
				this.items.push(new this.parent.SearchItem(this.parent, this, this.itemIds[i]));
			}
			
			
			// CLONE INITIALISIEREN
			var clone = $(this.cardId + '_clone');
			clone.onclick = this.selectItemsByClone.bind(this);
		}
		
		this.select = function()	{
			this.parent.deselectAll();
			this.dom.addClassName('activ');
			this.container.style.display = 'block';
			this.parent.hideLoadedContent();
		}
		
		this.deselect = function()	{
			this.dom.removeClassName('activ');
			this.container.style.display = 'none';
		}
		this.selectItemsByClone = function()	{
			this.input.checked  = $(this.cardId + '_clone').checked
			this.selectItems()
		}
		
		this.selectItems = function()	{
			this.input.checked != this.input.checked;
			$(this.cardId + '_clone').checked = this.input.checked;
			
			switch(true)	{
				case (this.input.checked ==false):
					for( var i = 0; i < this.items.length; i++)	{
						this.items[i].deselect();
					}
					break;
				default:
					for( var i = 0; i < this.items.length; i++)	{
						this.items[i].select();
					}
					
			}
			
			this.updateSelection();
		}
		 
		this.updateSelection = function()	{
			
			var numSelectedItems = 0;
			for(var i = 0; i < this.items.length; i++)	{
				if(this.items[i].dom.checked)	{
					numSelectedItems++;
				}
			}
			
			switch(true)	{
				case (numSelectedItems == 0):
					this.input.checked = false;
					//this.span.style.backgroundcolor = 'White';
					break;
				case (numSelectedItems == this.items.length):
					this.input.checked = true;
					//this.span.style.backgroundcolor = 'White';
					break;
				default:
					this.input.checked = true;
					//this.span.style.backgroundcolor = 'Black';
			}
			
		}
		
		
		CMS.onload(this.init.bind(this));
	}
	
	this.SearchItem = function( parent, card, id)	{
		this.id = id;
		this.parent = parent;
		this.card = card;
		this.dom   = $(id);
		
		
		parent.items[id] = this;
		
		this.handleClick = function()	{
			this.dom.checked != this.dom.checked
			this.card.updateSelection();
		}
		
		this.select = function()	{
			this.dom.checked = true;
		}
		
		this.deselect = function()	{
			this.dom.checked = false;
		}
		
		this.isSelected = function()	{
			return this.dom.checked;
		}
		
		this.loadContent = function()	{
			this.parent.loadContent(this.id);
		}
		
		this.underline = function()	{
			this.dom.nextSibling.style.textDecoration = 'underline';
			//alert(this.dom.nextSibling.style.textDecoration);
		}
		
		this.removeunderline = function()	{
			this.dom.nextSibling.style.textDecoration = 'none';
		}
		this.dom.onclick = this.handleClick.bind(this);
		this.dom.nextSibling.onclick = this.loadContent.bind(this);
		this.dom.nextSibling.onmouseover = this.underline.bind(this);
		this.dom.nextSibling.onmouseout  = this.removeunderline.bind(this);
	}

}
CMS.SearchPage = new CMS.__TMP__();
delete CMS.__TMP__;

function initControls()
    {
      if(!$('sitemap'))	{
	  	return;
	  }
	  var lLiItems = $('sitemap').getElementsBySelector('li');
      
      for ( var i=0; i<lLiItems.length; i++ ) {
        lLiItems[i].onmouseover = function()
        {     
          var lCont = this.getElementsBySelector('[class="nodeControlsHover"]');
          setControlItemStyle(this.down('span'));
          if ( lCont.length != 0 ) {
            setControlItemStyle(this.down('span'), false);
          }
        }
        
        lLiItems[i].onmouseout = function()
        {
          setControlItemStyle(this.down('span'), false);
          //setControlItemStyle(this.up('span', false);
        }
        
      }
    }
    
    function setControlItemStyle(pElement, pOpenOrClose)
    {
      if ( !pElement ) {
        return;
      }
      
      pOpenOrClose = ( pOpenOrClose == undefined ) ? true : pOpenOrClose;
      
      //alert(pOpenOrClose);
      
      if ( pElement.hasClassName('nodeControls') && pOpenOrClose ) {
        pElement.removeClassName('nodeControls');
        pElement.addClassName('nodeControlsHover');
      } else {
        pElement.removeClassName('nodeControlsHover');
        pElement.addClassName('nodeControls');
      }
    }
    
CMS.onload(initControls);

CMS.Nodemanager = {
	loading : false,
	
	loadNodeOptions : function(select, url, id)	{
		
		this.loading = true;
		
		var param = new Hash();
		param.set('action', 'getNodeOptions');
		param.set('nodetype', select.options[select.selectedIndex].value)
		param.set('id', id)
		
		new Ajax.Request(url,{
			method     : 'post',
			parameters : param,
			onSuccess  : this.updateOptions.bind(this),
			onFailure  : this.onLoadNodeOptionsFailure.bind(this)
		});
	},
	
	updateOptions : function(transport)	{
		
		$('nodeoptions').innerHTML = transport.responseText;
		this.loading = false;
	},
	
	onLoadNodeOptionsFailure : function(failure)	{
		alert('failure: ' + failure.toSource());
		this.loading = false;
	},
	
	switchSubNodeDisplay : function(element)	{
		//alert(element.hasClassName('open'))
		if(element.hasClassName('open'))	{
			this.unregisterItem(element);
			this.closeNode(element);
		}
		else if(element.hasClassName('close'))	{
			this.registerItem(element);
			this.openNode(element);
		}
	},
	
	openNode : function(element)	{
		element.removeClassName('close');
		element.addClassName('open');
		var sibling = element.siblings();
		for ( var i = 0; i < sibling.length; i++ )	{
			if (sibling[i].hasClassName('blindElement')) {
				sibling[i].setStyle({
					display: 'block'
				});
			}
		}
	},
	
	closeNode : function(element)	{
		element.removeClassName('open');
		element.addClassName('close');
		var sub = element.parentNode.getElementsByClassName('blindElement');
		for ( var i = 0; i < sub.length; i++ )	{
			sub[i].setStyle({
				display:'none'
			});
		}
	},
		
	expandAll : function()	{
		var sub = document.getElementsByClassName('blindElement');
		for ( var i = 0; i < sub.length; i++ )	{
			sub[i].setStyle({
				display:'block'
			});
		}
		var arrows = document.getElementsByClassName('structureitem');
		
		var elementIds = [];
		
		for ( var i = 0; i < arrows.length; i++ )	{
			if(arrows[i].hasClassName('close'))	{
				arrows[i].removeClassName('close');
				arrows[i].addClassName('open');
			}
			elementIds.push(arrows[i].id);
		}
		
		this.writeCookie(elementIds);
		
	},
		
	collapseAll : function()	{
		var sub = document.getElementsByClassName('blindElement');
		for ( var i = 0; i < sub.length; i++ )	{
			sub[i].setStyle({
				display:'none'
			});
		}
		
		var arrows = document.getElementsByClassName('structureitem');
		
		for ( var i = 0; i < arrows.length; i++ )	{
			if(arrows[i].hasClassName('open'))	{
				arrows[i].removeClassName('open');
				arrows[i].addClassName('close');
			}
		}
		this.writeCookie([]);
	},
	
	// Funktionen um den Zustand de Baumes in einem Cookie zu peristieren (sch?n gesagt!)
	writeCookie : function(arr)	{
		jimAuld.utils.cookies.set(this.getCookieName()+'openNodes', arr.toString());
	},
	
	readCookie : function()	{
		var val = jimAuld.utils.cookies.get(this.getCookieName()+'openNodes');
		if(!val)	{
			return [];
		}
		return val.split(',')
	},
	
	getCookieName : function()	{
		var href = document.location.href;
		
		if(href.lastIndexOf('/') == href.length - 1)	{
			href = href.substring(0, href.length - 1)
		}
		
		return href.substring(href.lastIndexOf('/'), href.length) + '/';
	},
	
	initOpened : function()	{
		this.getCookieName();
		var items = this.readCookie('nodes');
		for(var i = 0; i < items.length; i++)	{
			var element = $(items[i]);
			if(element && element.hasClassName('close'))	{
				this.switchSubNodeDisplay(element);
			}
		}
	},
	
	registerItem : function(element)	{
		var nodes = this.readCookie();
		if(nodes.indexOf(element.id == -1))	{
			nodes.push(element.id)
			this.writeCookie(nodes);
		}
		
	},
	
	unregisterItem : function(element)	{
		var nodes = this.readCookie();
		if(nodes.indexOf(element.id != -1))	{
			nodes = nodes.without(element.id);
			var sub = element.parentNode.getElementsByClassName('structureitem');
			for ( var i = 0; i < sub.length; i++)	{
				nodes = nodes.without(sub[i].id);
			}
			this.writeCookie(nodes);
		}
	}
	
	
}
CMS.onload(CMS.Nodemanager.initOpened.bind(CMS.Nodemanager))