/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}



/* iPhone DEV Scripts */

iphoneSession = Class.create({
	
	session : null,
	user	: null,
	
	initialize: function(){
		
		this.session = new Hash();
		this.user = false;
		
	},
	
	isUser : function(){
		
		return this.user;
				
	},
	
	
	addKey : function(pLabel,pValue){

		this.session.set(pLabel,pValue);
		
	},
	
	clear : function(){
		
		this.session = null;
		this.session = new Hash();
	},
	
	getKey : function(pKey){
		
		return this.session.get(pKey);
		
	},
	
	drawKeys : function(pElement){
		
		element = $(pElement);
		
		element.innerHTML = '';
				
		this.session.each(function(pair) {

			
			this.insert(pair.key + ' = "' + pair.value + '"<br/>');
			
			
		}.bind(element));
			
	},
	
	getURLVars : function(){
		
		return this.session.toQueryString();
	}
		
});

// http://stackoverflow.com/questions/244601/display-json-yaml-hierarchy-as-a-tree-in-html
function renderJSON(obj) {
	var keys = []
	var retValue = ""
	for (var key in obj) {
	        if(typeof obj[key] == 'object') {
	                retValue += "<div class='tree'><span class='treeTitle'>" + key +'</span>'                                         
	                retValue += renderJSON(obj[key])
	                retValue += "</div>"
	        }
	        else {
	                retValue += "<div class='endtree'>" + key + " = " + obj[key] + "</div>"
	        }
	
	   keys.push(key)
	}
	return retValue
}





	function importerMove(pElement){
		
		var element = $(pElement);
		
		var imp 	= $('toimport');
		var nimp 	= $('tonotimport');
		
		var parent  = element.parentNode;
		
		if(parent == imp){

			nimp.insertBefore(element, nimp.firstChild);
			
		}else{
			
			imp.insertBefore(element, imp.firstChild);
			
		}

				
		
	}

	function addNewContact(pID, pIVHTML)	{
		var tmp 	= $('bookReceipients');
		var form 	= $('bookForm');
		var co		= $('bookReceiversCount');
		
	
		if ($('hiddenFormReceiver'+pID))	{		
		 return true;		 
		}	else	{
			form.appendChild(Builder.node('INPUT',{'type':'hidden','name':'list[]','value':pID,'id':'hiddenFormReceiver'+pID}));
			tmp.innerHTML = '<A class="receiverContact" ID="choosenreceiver'+pID+'" HREF="javascript:switchAddressBookReceiver(\''+pID+'\')">'+pIVHTML+'</A>'+tmp.innerHTML;
		}

		if (co && form)
			co.innerHTML = form.getInputs('hidden', 'list[]').size();
				

		hideFeedbackOnForm();
			
	 return true;		
	}
	
	
	function switchAddressBookReceiver(pID)	{
		
			var tmp 	= $('bookReceipients');
			var form 	= $('bookForm');
			var co		= $('bookReceiversCount');
			var elem	= $('receiver'+pID);
			var cloning;
			
			if ($('hiddenFormReceiver'+pID))	{
				
				// Ok remove it from the receviers list
				Element.remove('hiddenFormReceiver'+pID);
				Element.remove('choosenreceiver'+pID);
				
				if(elem)					
					elem.show();															

			}	else	{
				// Add it to the receivers list
				cloning = elem.cloneNode(true)
				cloning.id = 'choosenreceiver'+pID;
				elem.hide();			
				tmp.insertBefore(cloning, tmp.firstChild);	
				form.appendChild(Builder.node('INPUT',{'type':'hidden','name':'list[]','value':pID,'id':'hiddenFormReceiver'+pID}));
			}

			if (co && form)	
				co.innerHTML = form.getInputs('hidden', 'list[]').size();
				

			hideFeedbackOnForm();
	}
	
	function gotoAddressBookReceiver(pID)	{
		
			if($('goNextButton'))
				$('goNextButton').show();
		
			var tmp 	= $('bookReceipients');
			var form 	= $('bookForm');
			var co		= $('bookReceiversCount');
			var elem	= $('receiver'+pID);
			var cloning;
			
			if ($('hiddenFormReceiver'+pID)){ // is the contact allready in the list ?
				
				if(elem && elem.visible() == true) // if yes then hide
					elem.hide();
	
			}	else	{
				// Add it to the receivers list
				cloning = elem.cloneNode(true)
				cloning.id = 'choosenreceiver'+pID;
				cloning.href = "javascript:removeAddressBookReceiver('"+pID+"');";
				
				elem.hide();			
				tmp.insertBefore(cloning, tmp.firstChild);	
				form.appendChild(Builder.node('INPUT',{'type':'hidden','name':'list[]','value':pID,'id':'hiddenFormReceiver'+pID}));
			}

			if (co && form)	
				co.innerHTML = form.getInputs('hidden', 'list[]').size();
				

			hideFeedbackOnForm();
	}
	
	
	function removeAddressBookReceiver(pID)	{
		
		var form 	= $('bookForm');
		var co		= $('bookReceiversCount');
		var elem	= $('receiver'+pID);
		
		// Ok remove it from the receviers list
		Element.remove('hiddenFormReceiver'+pID);
		Element.remove('choosenreceiver'+pID);
					
		if(elem)					
			elem.show();
			
		if (co && form)	
				co.innerHTML = form.getInputs('hidden', 'list[]').size();
				
		hideFeedbackOnForm();

	}


	function goToInstance(e)	 {
		location.href = "http://www."+sitedomaine+"/p9427/index.html";
	}

	function activateSearch(e)	 {
		
		//if (e.value.indexOf('..')!=-1)
		e.value='';
		e.setStyle({width:'185px'});
		$('searchField').setStyle({width:'220px'});
	}
	
	function deactivateSearch(e)	{

		e.setStyle({width:'90px'});	
		$('searchField').setStyle({width:'120px'});
			
	}
	
	
	function fadePageOut()	{
				
			var tmp = $('pageFader');
			if (!tmp)
				return;
			
			
			Element.show('pageFader');
			
			Element.setStyle({'height':'100%'});
			
			Element.setOpacity('pageFader', '0.01');
			
			new Effect.Opacity('pageFader', {duration:'1', to:'0.6'});
			


		
	}
	
	function fadePageIn()	{
		new Effect.Opacity('pageFader', {duration:0.5, to:0.01, afterFinish:new Function ('', "Element.hide('pageFader');")});
	}
	

	function refreshPage()	{
		location.reload();
	}
	
	function showDebugPane(element)	{
		
		if (!$('consoleInner') && $(element))
			return;
	
		Element.update('consoleInner', $(element).innerHTML);
		activateConsole(800,800);
	}
	
	wpNavLast = null;
	wpNavLock = false;
	
	function setLastActiveMainTab(pID)	{
		wpNavLast = pID;	
	}
	
	function mainTabClick(pID)	{
		var tmp = $(pID);
		
		if (wpNavLock==true)
			return;
					
		if (wpNavLast==pID)	{
			Effect.toggle(wpNavLast+'SD', 'blind', {duration:0.5, queue:'end'});
			$(wpNavLast).setAttribute('class', 'wpMainTabInactive');
			wpNavLast = null;
		 return;
		}
		
		
		tmp = $(pID);
		if (!tmp )
			return;

		wpNavLock = true;			

		if (wpNavLast)	{		
			Effect.toggle(wpNavLast+'SD', 'blind', {duration:0.5, queue:'end'});
			$(wpNavLast).setAttribute('class', 'wpMainTabInactive');			
		}
		
		wpNavLast = pID;
		
		Effect.toggle(pID+'SD', 'blind', {duration:0.5, queue:'end', afterFinish:new Function ('', "wpNavLock=false;")});
		
		tmp.setAttribute('class', 'wpMainTabActive');
		
			
	}
	
	function statuscheckKeyPress(e,pForm){
		
		var characterCode 
		var key_enter 	= 13;
		var key_escape 	= 0;
		
		if(window.event){
			characterCode 	= event.keyCode;
			key_escape 		= 27;
		}else{
			characterCode 	= e.which;
			key_escape 		= e.DOM_VK_ESCAPE;
		}
		
		if(characterCode == key_enter){ 
			eval(pForm);
		}
			
	}

	
	
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

BrowserDetect.init();

function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }

	
	


	var tmpReturnTest;

	function formXAction(pFormID, pXAction)	{

		if (!$(pFormID))
			return false;
			
	 	return xajax.request( { xjxcls: 'xactions', xjxmthd: 'xactionsFormDispatcher' }, { parameters: new Array(pXAction, xajax.getFormValues(pFormID))});
	}

	function boxPutter(pTarget, pMode, pContent)	{

		var tmp = $(pTarget);	

		if (!tmp || !tmp.parentNode)
			return false;

		if(pMode=='REPLACE' || pMode=='replace')					
			Element.replace(tmp, pContent);
		
		if(pMode=='PREPEND' || pMode=='prepend')
			Element.insert(tmp, { before: pContent});
		
		if(pMode=='APPEND' || pMode=='append')
			Element.insert(tmp, { after: pContent});
			
		//resync zaptips
		zaptipssearch();
		
	 return true;
	}

	function brickLoad(pBrick, pUniqueID, pLabel, pTarget, pMode, pContext)	{

		if (!$(pTarget+'Inner'))
			return;

		ojaxTargetLoads(pTarget+'Inner');
		
	 return xajax.request( { xjxcls: 'xactions', xjxmthd: 'xactionsBrickLoader' }, { parameters: arguments } );
	}
	
	
	function brickLoadFromForm(pFormID, pBrick, pUniqueID, pLabel, pTarget, pMode, pContext)	{

		if (!$(pTarget+'Inner'))
			return;
			
		var cache = xajax.getFormValues(pFormID);
		ojaxTargetLoads(pTarget+'Inner');
	
	 return xajax.request( { xjxcls: 'xactions', xjxmthd: 'xactionsBrickLoader' }, { parameters: new Array(pBrick, pUniqueID, pLabel, pTarget, pMode, pContext, cache)} );
	}
	
	
	

	function xAction(pAction, pContext)	{
	 return xajax.request( { xjxcls: 'xactions', xjxmthd: 'xactionsDispatcher' }, { parameters: arguments } );
	}		
		
	


	


// ### SLIDER FROM THE TAG LIBRARY ##############################################################################

function swapSliderPanels(pWhich)	{

	var open 	= $('sliderautoid'+pWhich+'_open');
	var close	= $('sliderautoid'+pWhich+'_close');	
	
	
	if (!open || !close)
		return;
		
	if (open.visible())	{
		open.hide();
		close.show();
	}	else	{
		open.show();
		close.hide();		
	}
	
	
}

function sliderOpen(pWhich)	{

	var open 	= $('sliderautoid'+pWhich+'_open');
	var close	= $('sliderautoid'+pWhich+'_close');
	var content	= $('sliderautoid'+pWhich);
	
	if (!open || !close || !content)
		return;
		
	Effect.BlindDown(content, {duration:0.5,afterFinish:new Function ('', "swapSliderPanels('"+pWhich+"')")});
	
}

function sliderClose(pWhich)	{

	var open 	= $('sliderautoid'+pWhich+'_open');
	var close	= $('sliderautoid'+pWhich+'_close');
	var content	= $('sliderautoid'+pWhich);
	
	if (!open || !close || !content)
		return;
		
	Effect.BlindUp(content, {duration:0.5,afterFinish:new Function ('', "swapSliderPanels('"+pWhich+"')")});
		
}

function sliderToogle(pWhich){

	var sliderElement 		= $('sliderautoid'+pWhich);
	var sliderElementStatus = $('sliderautoid'+pWhich+'_status');
	
	if(sliderElementStatus.innerHTML == "2"){
		Effect.BlindUp(sliderElement, {duration:0.1,afterFinish: (function() {sliderElement.setStyle({'overflow':'visible','height':'auto'})})});
		sliderElementStatus.innerHTML = "0";
	}else if(sliderElementStatus.innerHTML == "0"){
		Effect.BlindDown(sliderElement, {duration:0.5});
		sliderElementStatus.innerHTML = "1";
	}else{
		Effect.BlindUp(sliderElement, {duration:0.5});
		sliderElementStatus.innerHTML = "0";
	}
}


// ### HIGHLIGHTS ###############################################################################################
var lastHLS	= new Array();

function removeHighlightsOnForm(pID) {
	var elem, tmp = $(pID);
	if (!tmp)
		return;
			
	lastHLS.each(function(elem) {
		  	
   		if (elem.hasClassName('highlight'))	{
   			elem.removeClassName('highlight');	
   		}

   		if (!elem.parentNode)
   			retun;

   		elem = elem.parentNode;
   		
   		if($(elem)){

	   		if (elem.hasClassName('highlight')){
	   			
	   			elem.removeClassName('highlight');	
	   			
	   		}
   		
   		}
   			
	});
		
}



function formElementHighlight(pFormID, pID)	{	
	
	var tmp = $(''+pFormID+'input'+pID+'');
	
	if (!tmp){
		return;
	}

	if (tmp.type == 'radio' || tmp.type == 'checkbox')
		tmp = tmp.parentNode;
	
	
	tmp.addClassName('highlight');	

	
	lastHLS.push(tmp);
}



// ### FEEDBACKS ###############################################################################################

var lastFB 	= null;

function formShowErrorFeedback(pFormID, pID, pText)	{
	
	var input = pFormID+'input'+pID, tmp = $(pFormID+pID+'FB'), inn = $(pFormID+pID+'FBInner');
	if (!input || !tmp || !inn)
		return;	
	
	
	hideFeedbackOnForm();
		
	tmp.setAttribute('class', 'inputErrorFeedback');

	Element.update(pFormID+pID+'FBInner', pText);

	if (tmp==lastFB)
		return ;
			
	if (!tmp.visible())
		Effect.BlindDown(tmp, {duration:0.5});					
				
	lastFB = tmp;
}

function formShowFeedback(pFormID, pID) {
	
	var tmp = $(pFormID+pID+'FB'), inn = $(pFormID+pID+'FBInner');
	if (tmp==lastFB)
		return ;
		
	hideFeedbackOnForm();		
		
	if (!tmp || !inn)
		return;	

	if (inn.innerHTML=='')
		return;
		
	if (!tmp.visible())		
		Effect.BlindDown(tmp, {duration:0.4});
		
	lastFB = tmp;
	
}


function hideFeedbackOnForm() {
	var tmp = $(lastFB);
	
	if (!tmp){
		return;
	}
	
	if (tmp.visible())	{
		//tmp.hide();
		if($(tmp.id)){
			$(tmp.id).hide();
		}
	}

		
	lastFB = null;
}



// ### FLOWER EXCHANGE #########################################################################################



var flowerexchange;

function exchangeButtonWithFlower(pID)	{

	var link = $('formSubmitButtons'+pID), flower = $('formSubmitFlower'+pID);
	if (!link || !flower)
		return;	

	flowerexchange = pID;
	Element.hide(link);
	Element.show(flower);



 return true;
}


function exchangeFlowerWithButton()	{
	var id 		= arguments.length>0 ? arguments[0] : flowerexchange;
	var link	= $('formSubmitButtons'+id), flower = $('formSubmitFlower'+id);
	if (!link || !flower)
		return;	

	Element.show(link);
	Element.hide(flower);
	
}

Effect.ResizeTo = Class.create();
Object.extend(Object.extend(Effect.ResizeTo.prototype, Effect.Base.prototype), {
	initialize: function(element, toWidth, toHeight) {
	
	    this.element		= $(element);
	    this.toWidth		= toWidth;
	    this.toHeight		= toHeight;
	
	    this.originalWidth  = parseFloat(Element.getStyle(this.element,'width')  || 0);
	    this.originalHeight = parseFloat(Element.getStyle(this.element,'height') || 0);

	    this.effectiveWidth = this.toWidth 
	                        - parseFloat(Element.getStyle(this.element,'margin-left') || 0) 
	                        - parseFloat(Element.getStyle(this.element,'margin-right') || 0) 
	                        - (document.compatMode == 'BackCompat' ? 0 : // height includes padding & border in IE BackCompat mode
	                            parseFloat(Element.getStyle(this.element,'padding-left') || 0) 
	                           + parseFloat(Element.getStyle(this.element,'padding-right') || 0));
	
	    this.effectiveHeight = this.toHeight
	                        - parseFloat(Element.getStyle(this.element,'margin-top') || 0) 
	                        - parseFloat(Element.getStyle(this.element,'margin-bottom') || 0) 
	                        - (document.compatMode == 'BackCompat' ? 0 : // height includes padding & border in IE BackCompat mode
	                            parseFloat(Element.getStyle(this.element,'padding-top') || 0) 
	                            + parseFloat(Element.getStyle(this.element,'padding-bottom') || 0));
	
	    this.options = arguments[3] || {};
	
	    if (this.effectiveWidth < 0) 	this.effectiveWidth = 0;
	    if (this.effectiveHeight < 0)	this.effectiveHeight = 0;
	
	    if (this.originalWidth == this.effectiveWidth && this.originalHeight == this.effectiveHeight)
	      return;
	    
		this.start(this.options);    
	},

	update: function(position) {
	  widthd  = this.effectiveWidth * (position) + this.originalWidth *  (1 - position);
	  heightd = this.effectiveHeight * (position) + this.originalHeight * (1 - position);
	  this.setPosition(widthd, heightd);
	},
	
	setPosition: function(widthd, heightd) {		
				
		if (isNaN(widthd) || isNaN(heightd))
			return;

		if (this.options['direction'] && this.options['direction']=='center')	{
			this.element.style.left		= ( parseFloat(this.element.style.left)	- Math.round((widthd-parseFloat(this.element.style.width))/2))+'px';
			this.element.style.top		= ( parseFloat(this.element.style.top)	- Math.round((heightd-parseFloat(this.element.style.height))/2))+'px';
		}
		
		this.element.style.width	= widthd+'px';
		this.element.style.height	= heightd+'px';
	}
	
	}
);


function getVerticalScrollPosition()	{

    if ( document.documentElement && document.documentElement.scrollTop )    
        return document.documentElement.scrollTop;
    else 
    	if ( document.body && document.body.scrollTop )
        	return document.body.scrollTop;    
    	else
    		if ( window.pageYOffset )    
        		return window.pageYOffset;
        	else
        		if ( window.scrollY )
   					return window.scrollY;
 return 0;   	
}

function getWindowSize() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' )
		return new Hash({width:window.innerWidth,height:window.innerHeight})
	else
		if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
			return new Hash({width:document.documentElement.clientWidth,height:document.documentElement.clientHeight})
  		else 
  			if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
				return new Hash({width:document.body.clientWidth,height:document.body.clientHeight})
  			
 return new Hash({width:0,height:0});
}

function centerOnUpThirdScreen(pElement)	{

	tmp = $(pElement);
	if (!tmp)	
		return;
		
	s = getWindowSize();
	
	x = ((Math.round(s.get('width')-tmp.getWidth())/2));
	y = 180;
	
	tmp.setStyle({left:x+'px',top:y+'px'});
 return;	
}

function centerOnScreen(pElement)	{

	tmp = $(pElement);
	if (!tmp)	
		return;
		
	s = getWindowSize();
	
	x = ((Math.round(s.get('width')-tmp.getWidth())/2));
	y = ((Math.round(s.get('height')-tmp.getHeight())/2)+getVerticalScrollPosition());
	
	tmp.setStyle({left:x+'px',top:y+'px'});
 return;	
}

// ### SLIDEUP/DOWN FUNCTION #########################################################################################

function slideElement(pElement,pStatus,pduration){
	
	var element = $(pElement);
	
	if(pStatus == "down"){
		
		if(element.style.display == 'none'){
			//Effect.BlindDown(pElement, { duration:pduration })
			element.show();

		}
			
	}else{
		//Effect.BlindUp(pElement, { duration:pduration })
		element.hide();
	}
}

// ### FADE in-out FUNCTION #####

function textteasing_toggle(pIDCount){
		
	var content_small 	= 'tt_small_' + pIDCount;
	var content_big		= 'tt_content_' + pIDCount;
	var commands		= 'tt_commands_' + pIDCount;
					
	//Effect.toggle(content_small, 'blind', {duration: 0.3});
	if($(''+content_big+'').style.display == 'none'){
		
		Effect.BlindUp(content_small	, { duration: 0.3 });
		Effect.BlindDown(content_big	, { delay:0.3,duration: 0.5 });
		$(commands+'_open').hide();
		$(commands+'_close').show();

	}else{
			
		Effect.BlindUp(content_big	, { duration: 0.3 });
		Effect.BlindDown(content_small	, { delay:0.3,duration: 0.5 });
		$(commands+'_close').hide();
		$(commands+'_open').show();
		
	}
		
}

// ACHELP

function show_achelp(pElement,pState){
	
	var element = $(pElement);
	
	$('achelp').clonePosition(element,{'setWidth':false,'setHeight':false,offsetLeft:14,offsetTop:5});
	
	if(pState){
		$('achelp').show();
	}else{
		$('achelp').hide();
	}

	
}


// Special Wizard Functions

function toggleElementList(pList,pElement){
	
	var array_element = pList.split(';');
	
		array_element.each(function(elem){
		
				if(elem == pElement){
					$(elem).show();
				}else{
					$(elem).hide();	
				}
			
		});
	
}

// Set Height on Element before reload, Helps
function fixHeight(pElement){
	
	var element = $(pElement+'Inner');
	
	if(element){
		
		// get height
		tmpheight = element.getHeight();
		
		//alert(tmpheight);
	
		// save
		element.setStyle({'height':tmpheight+'px'});

	}

}

// Testing
function submenuMouseout(pElement,event)
{
	var toElement = null;
	var container = $(pElement);
	
	if (event.relatedTarget){
		toElement = event.relatedTarget;
	}else if (event.toElement){
		toElement = event.toElement;
	}
	
	while (toElement && toElement != container){
		toElement = toElement.parentNode;
	}
	
	/*while (toElement && toElement.tagName != "DIV"){
		toElement = toElement.parentNode;
	}*/
	
	if (!toElement){
		//alert('out of div');
	}
}


function menuIconsButtonShow(pButton){
	
	// We have 4 Button
	
	var buttons = [];
	
	buttons[0] = $('menu_button_0');
	buttons[1] = $('menu_button_1');
	buttons[2] = $('menu_button_2');
	buttons[3] = $('menu_button_3');
	
	for(var I = 0;I<buttons.size();I++){
		
		
		if(pButton == I){
			
			buttons[I].show();
			
		}else{
			
			buttons[I].hide();
			
		}
		
	}
	
}

// ### BOX SLIDER ##############################################################################

var scrollBox = function(pElement,pSide,pDistance){
	
	//parm
	var element 		= $(pElement);
	var distance 		= parseInt(pDistance,10);
	
	//element information
	var elPosition 		= element.positionedOffset();
	var elHeight 		= element.getHeight();
	
	//parent information
	var parentEl 		= element.parentNode;
	var parentHeight 	= parentEl.getHeight();
	

		
	
	if(pSide == 'up'){
				
		distance = Math.min((0-elPosition.top),distance);

				
	}else{
		
		distance = 0 - Math.min((elPosition.top+elHeight-parentHeight),distance);
		
	}
	
	if(distance != 0){
	
		new Effect.Move(element, {y: distance,transition: Effect.Transitions.sinoidal,duration:0.3, queue: { position: 'end', scope: 'scrollboxes', limit: 1 }});
	
	}
		
	
}

var changeScrollButtons = function(pContainer,pElement,pState,event){

	//parm
	var element 		= $(pElement);
	var state			= pState;
	var container		= $(pContainer);
	
	
	if (!event)
		event = window.event;
	
	//get element
	var toElement = $(event.relatedTarget);
			
	while (toElement && (toElement != container)){
			
		toElement = Element.up(toElement);
			
	}
		
		
	if (empty(toElement)){

		if(state=="on"){
			//element.appear({ duration: 0.2 });
			element.show();
			//new Effect.Opacity(pElement,{ duration: 0.2, from: 0.2, to: 1 });
		}else{
			//element.fade({ duration: 0.2 });
			element.hide();
			//new Effect.Opacity(pElement,{ duration: 0.2, from: 1, to: 0.2 });
		}		
			
	}
		
}


var changeVisibleElementlist = {
	
	elements : new Hash(),
	
	addList : function(pLabel,pElement){
		
		this.elements.set(pLabel,pElement);
					
	},
		
	changeElement : function(pLabel,pElement){
		
		
		// hide old element
		if(typeof this.elements.get(pLabel) != "undefined"){
						
			if(this.elements.get(pLabel) == pElement)
				return true;
			
			var oldElement = this.elements.get(pLabel);
			
			this.elements.set(pLabel,pElement)
						
			if(oldElement != null){
				$(oldElement).hide();
			}
			
			if(this.elements.get(pLabel) != null){
				$(this.elements.get(pLabel)).show();
			}
				
		}		
	
	}
	
}


var introMenuSelectLast = null;

var introMenuSelect = function(pItem){
	
	var container = $('introContentWrap');
	
	
		var menus 	= ['introContainer1','introContainer2','introContainer3','introContainer4'];
		var tabs 	= ['introTab1','introTab2','introTab3','introTab4'];
		var bg 		= ['/skins/zap/common/navigation/intro_menu_nightlife.png','/skins/zap/common/navigation/intro_menu_fotoreports.png','/skins/zap/common/navigation/intro_menu_community.png','/skins/zap/common/navigation/intro_menu_singles.png'];
		var bgHover	= ['/skins/zap/common/navigation/intro_menu_nightlife_hover.png','/skins/zap/common/navigation/intro_menu_fotoreports_hover.png','/skins/zap/common/navigation/intro_menu_community_hover.png','/skins/zap/common/navigation/intro_menu_singles_hover.png'];
	
	
	if(introMenuSelectLast != null){
		
		var index = menus.indexOf(introMenuSelectLast);
		
		$(menus[index]).hide();
		$(''+tabs[index]+'').setStyle({backgroundImage:'url('+bg[index]+')'});
		
		
	}
	
	introMenuSelectLast = pItem;
	
	var index = menus.indexOf(introMenuSelectLast);
	
	if(index >= 0){
		$(menus[index]).show();
		$('introMenuCloseButton').show();
		$(''+tabs[index]+'').setStyle({backgroundImage:'url('+bgHover[index]+')'});
	}
		
	if(pItem == null){
		
		
		$('introMenuCloseButton').hide();
		
		
	}
	
}

/* */

function navigationMenu(pElement,pCSSSelector,pStatus,event){

	var toElement = null;
	var container = $(pElement);
	var hasItem   = false;
	
	var items	= new Array();
	items = container.select(pCSSSelector);
	
	
	var status = pStatus;
	
	if (!event)
		event = window.event;
		
	
	if(items.size() > 0){
	
		//get element
		var relTarg = event.relatedTarget;

		
		if(relTarg == null){
			
			if(status){
				relTarg = event.fromElement;
			}else{
				relTarg = event.toElement;
			}
			
		}
				
		var toElement = $(relTarg);
					
		while (toElement && (toElement != container)){
			
			//toElement = Element.up(toElement);
			toElement = toElement.parentNode;
			
		}
		
		
		if (empty(toElement)){
						
			if(!status){
				
				items.each(function(element){
					
					//element.setStyle("opacity: 1;");
					element.hide();

				});
							
	
				
			}else{
				
				
				items.each(function(element){
					
					
					//element.setStyle("opacity: 0;");
					
					element.show();
					
					//Effect.Appear(element, { duration: 0.2 });
										
					
				});					
			}	
		}
	}
}


hasLeavedParentElement = function(event,pParent){
	
		
	// get event
	if (!event)
		event = window.event;
	
	//get element we leaved
	var relTarg = event.relatedTarget;
		
	if(relTarg == null){
			
		relTarg = event.toElement;
			
	}
	
	// extend element
	var element = $(relTarg);
	
	// parent child
	var parentElement = $(pParent).descendants();
	

	// bool val
	var notfound = true;
	
	// loop for the parent
	for(var I=0;I<parentElement.size();I++){

		if(parentElement[I] == element){
			
			notfound = false;
			break;
			
		}
	}
	
	return notfound;
	
}

stillInsideParent = function(event,pParent){
	
	
	// get event
	if (!event)
		event = window.event;
	
	//get element we leaved
	var relTarg = event.relatedTarget;
		
	if(relTarg == null){
			
		relTarg = event.toElement;
			
	}
	
	// extend element
	var element = $(relTarg);
	
	// parent child
	var parentElement = $(pParent).descendants();
	

	// bool val
	var found = false;
	
	// loop for the parent
	for(var I=0;I<parentElement.size();I++){

		if(parentElement[I] == element){
			
			found = true;
			break;
			
		}
	}
	
	return found;
	
}





var loadContentBuffer	= new Hash();

function handleConfirmationNAK()	{
	$('confirm').hide();
}

function hideUserConfirm()	{
	$('confirm').hide();
}


function userConfirm(pURL, pText, pConsoleVisible)	{

	window.scroll(0,0); // horizontal and vertical scroll targets (X;Y)
	centerOnScreen('confirm');

	//centerOnUpThirdScreen('confirm');

	var tmp 			= $('confirmText');
	if (!tmp)
		return;

	confirmURL			= pURL;
	tmp.innerHTML 		= pText;

	//if(pConsoleVisible){
		$('confirm').appear();
	//}

	$('confirmACK').href='javascript:'+pURL;
}

function hideConsoleAndShowConfirm(pURL,pText){

	var consoleVisible = $('console').visible();

	if(consoleVisible){
		//1 HideConsole
		$("console").fade();
	}

	//2 ShowConfirm
	userConfirm(pURL, pText,consoleVisible);
}

function hideConfirmAndShowConsole(){

	//1 HideConfirm
	$("confirm").fade();

	//2 ShowConsole
	$("console").appear();
}


// --
// ** User Confirmation
// --

// init confirmation
function confirmAction(pURL,pText){

	//check if a console if open
	var consoleVisible = $('console').visible();

	// if console is active, hide
	if(consoleVisible){

		//1 HideConsole
		$("console").fade();

	}else{

		// fade page out
		fadePageOut();
	}

	// open confirmation
	openConfirm(pURL,pText,consoleVisible);

}

// show Confirmation
function openConfirm(pURL,pText,pConsoleVisible){

	window.scroll(0,0); // horizontal and vertical scroll targets (X;Y)
	//centerOnScreen('confirm');

	centerOnUpThirdScreen('confirm');

	var tmp 			= $('confirmText');
	if (!tmp)
		return;

	confirmURL			= pURL;
	tmp.innerHTML 		= pText;


	$('confirm').appear();



	if(pConsoleVisible){
		$('confirmNAK').href='javascript:closeConfirmAction(true)';
		$('confirmACK').href='javascript:closeConfirmAction(true);'+pURL;
	}else{

		$('confirmACK').href='javascript:closeConfirmAction(false);'+pURL;

	}


}

//
function closeConfirmAction(pConsoleVisible){

	//1 HideConfirm
	$("confirm").fade();


	if(pConsoleVisible){

		//2 ShowConsole
		$("console").appear();

	}else{

		// fade page in
		fadePageIn();

	}


}


function confirmFormCall(pURL, pTarget, pFormID)	{
	confirmOjaxCall(pURL, pTarget);
	confirmDataSource = pFormID;
 return;
}


function consoleLoads()	{

	var tmp = $('console'), inn	= $('consoleLoading');

	if (!tmp || !inn)
		return;


	Element.update($('consoleInner'), $('consoleLoading').innerHTML);
	//activateConsole(inn.getWidth(), inn.getHeight());
	activateConsole();

	window.scroll(0,0); // horizontal and vertical scroll targets (X;Y)

}

function putIn(pKey)	{
	var content, tmp		= $('consoleInner');
	if (!tmp)
		return;

	content = loadContentBuffer.get(pKey);
	loadContentBuffer.unset(pKey);
	Element.update(tmp, content);
	centerOnUpThirdScreen('console');

	new Effect.Opacity	('consoleInner', {duration:0.4, from:0.0, to:1.0});
}


function finishConsoleRequest(transport)	{
		
	var d	= new Date();
	var key = d.getSeconds()+'-'+d.getMilliseconds();
	var tmp = $('consoleInner');
	if (!tmp)
		return;

	loadContentBuffer.set(key,transport.responseText);
	
	if (tmp.visible())	{
		new Effect.Opacity	('consoleInner', {duration:0.4, from:1.0, to:0.0, afterFinish:new Function ('', 'putIn("'+key+'")')});
		//new Effect.Opacity	('consoleInner', {duration:0.4, from:0.0, to:1.0, queue: 'end'});
	}	else	{
		putIn(key);
	}
}

function loadIntoConsole(pURL)	{
		
	var tmp = $('console'), inn	= $('consoleInner');

	if (!tmp || !inn)	{
		Event.observe(window,'load',function(){
			loadIntoConsole(pURL);
		}); 
	return;
	}

	var w			= 640;
	var h			= tmp.getHeight();

	var parameters	= new Hash();
		
	if (arguments.length>1)	{
		
		if (typeof arguments[1]  == "object" && Object.isHash(arguments[1]))	{
			
			parameters	= arguments[1];
			
		}	else	{
						
			if ($(arguments[1]) && $(arguments[1]).tagName.toLowerCase() == 'form')
				parameters 	= $(arguments[1]).serialize(true);

		}

	}
	
	
	if(Object.isHash(parameters)){
	
		parameters.set('tctxt', 'console');
	
	}else{
		
		Object.extend(parameters, {tctxt:'console'});
		
	}
	
	consoleLoads();
	
	if($('console').getWidth()!=w){
		centerOnUpThirdScreen('console');
		new Effect.ResizeTo	('console', w, h, {direction:'center',duration:0.4});
	}

	new Ajax.Request(pURL, {  method:'post', parameters:parameters,  onComplete:finishConsoleRequest});
}




function activateConsole()	{

	var tmp = $('console'), inn	= $('consoleInner');

	if (!tmp || !inn)	{
	 return;
	}

	var w	= ((arguments.length>0) ? arguments[0] : tmp.getWidth());
	var h	= ((arguments.length>1) ? arguments[1] : tmp.getHeight());


	if (tmp.visible()==false)	{

		//tmp.setStyle({width:0+'px',height:0+'px'});
		centerOnUpThirdScreen('console');

		tmp.setStyle({opacity:0.0});
		tmp.show();

		new Effect.ResizeTo	('console', w-2, h-2, {direction:'center',duration:0.3});
		new Effect.Opacity	('console', 	{duration:0.4, from:0.0, to:1.0});
	//	new Effect.Opacity	('consoleInner', {duration:0.3,  from:0.0, to:1.0});
		fadePageOut();
	}	else	{
		centerOnUpThirdScreen('console');
		new Effect.ResizeTo	('console', w, h, {direction:'center',duration:0.3});

	}


}

function deactivateConsoleDelayed(pMillis)	{
	setTimeout('deactivateConsole()', pMillis);
}


function deactivateConsole()	{

	var tmp = $('console'), inn	= $('consoleInner');

	if (!tmp || !inn){
	 return;
	}

	if (window.consoleCloseCleanup){
		window.consoleCloseCleanup();
		delete(window.consoleCloseCleanup);
	}



	//new Effect.ResizeTo	('console', 640, 0, {direction:'center',duration:0.4});
	//new Effect.Opacity	('consoleInner', {duration:0.2, from:1.0, to:0.0});
	
	//alert('Before effect');
	
	new Effect.Opacity	('console', {duration:0.4,  from:1.0, to:0.0, afterFinish:new Function('','$("console").hide(); $("consoleInner").innerHTML="";')});
	
	//alert('After effect');
	
	fadePageIn();

}






function activateHomepage(pURL)	{

	var tmp = $('homepageBrowser');	
	
	if (!tmp)
	 return;
	
	centerOnScreen('homepageBrowser');	
	Element.show('homepageBrowser');
	frames['homepageBrowser'].location.href = 'http://'+pURL;
	fadePageOut();
}

function deactivateHomepage(){
	Element.hide('homepageBrowser');	
	fadePageIn();		
}

/* GetMember */

var getMemberForm = {
	
	lastShow : [],
	
	hover: function(pElement,pStatus,pImg,pImg_hover){
		
		var element = $(pElement);
		
		if(pStatus == ''){
				
			//element.style.background='url('+pImg+')';
			
			element.setStyle({backgroundImage:'url('+pImg+')'});
				
		}else if(pStatus == 'hover'){
			
			
				
			//element.style.background='url('+pImg+')';
			element.setStyle({backgroundImage:'url('+pImg+')'});
			
			if(this.lastShow != null){
				
				this.lastShow.hide();			
				
			}
			
			this.lastShow = $(element.id+'_info');
			this.lastShow.show();
				
		}	
	}
}

function getmemberconditions(pElement,pURL){
	
}

function jumpToID(pID,pAlternative){
	
	if($(pID)){
			
		location.href = $(pID).href;
		
	}else{

		if(!empty(pAlternative)){
			
			location.href = pAlternative;
		}
		
	}
	
}


// {{{ empty
function empty( mixed_var ) {
    // Determine whether a variable is empty
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_empty/
    // +       version: 903.421
    // +   original by: Philippe Baumann
    // +      input by: Onno Marsman
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: LH
    // +   improved by: Onno Marsman
    // +   improved by: Francesco
    // +   improved by: Marc Jansen
    // *     example 1: empty(null);
    // *     returns 1: true
    // *     example 2: empty(undefined);
    // *     returns 2: true
    // *     example 3: empty([]);
    // *     returns 3: true
    // *     example 4: empty({});
    // *     returns 4: true
    // *     example 5: empty({'aFunc' : function () { alert('humpty'); } });
    // *     returns 5: false
    
    var key;
    
    if (mixed_var === ""
        || mixed_var === 0
        || mixed_var === "0"
        || mixed_var === null
        || mixed_var === false
        || mixed_var === undefined
    ){
        return true;
    }

    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }

    return false;
}// }}}


function checkPrivateValues(pValue){
	

	
	var masterval = parseInt(pValue,10);
	
	var elements = $('private_apps').select('.private_apps_values');
	

	
	var tmp,tmp2, tmpval_2, tmpval_3, tmpvalue = null;
	var tmpval = [];

	
	for(I=0;I<elements.size();I++){
	
		
		// search <input>
		tmp = elements[I].select('input');
		
	
		
		// check what value is set
		if(tmp[0].checked){
			
			tmpvalue = 0;
			
		}else if(tmp[1].checked){
			
			tmpvalue = 2;
			
		}else if(tmp[2].checked){
			
			tmpvalue = 4;
			
		}else{ //fallback, schould never happen
			
			tmpvalue = 0;
			
		}
		
		
		// check if value is not smaller then master value an change if needed
		id = ((masterval/2));
		

		/*if(masterval > tmpvalue){
			
			tmp[id].checked = true;
			
		}*/
		
			
		for(Y=0;Y<=2;Y++){
				
			if(Y < id){
				
				
				tmp[Y].disable();
				
			}else{
				
				tmp[Y].enable();
				
			}
					
		}
		
		
		tmp[id].checked = true;
					
								
	}

}


function triggerIfNotSet(pElement){
	
	var element = $(pElement);
	
	if(element.checked){
				
		element.onclick = null;
		
	}else{
		
		element.checked = true;
		//element.onclick();
		
	}
	
}

function triggerFix(pElement){
	
	var element = $(pElement);
			
	if(Prototype.Browser.IE){
		
		element.onchange();		
		
	}
	
	element.blur();
	
}












var ojaxLoadContentBuffer = new Hash();
var global =null;


function ojaxTargetLoads(pTarget)	{
	var inn	= $('loadingOjax');

	if (!inn)
		return;

	Element.update($(pTarget), inn.innerHTML);
}

function ojaxPutIn(pTarget)	{
	var tmp = $(pTarget);
	if (!tmp)
		return;



	Element.update(tmp, ojaxLoadContentBuffer.get(pTarget));
	ojaxLoadContentBuffer.unset(pTarget);
}

function finishOjaxRequest(pTarget, pTransport)	{

	var tmp = $(pTarget);

	if (!tmp)
		return;


	ojaxLoadContentBuffer.set(pTarget, pTransport.responseText);

	//resync zaptips
	zaptipssearch();

	new Effect.Opacity(pTarget, {duration:0.2, from:1.0, to:0.0, afterFinish: new Function('', 'ojaxPutIn("'+pTarget+'")')});
	new Effect.Opacity(pTarget, {duration:0.3, from:0.0, to:1.0, queue:'end'});


}

function pageLoadFromForm(pFormID, pLabel, pTarget)	{

		if (!$(pTarget+'Inner'))
			return;

		var cache = xajax.getFormValues(pFormID);
		ojaxTargetLoads(pTarget+'Inner');

	 return xajax.request( { xjxcls: 'xactions', xjxmthd: 'xactionsBrickLoader' }, { parameters: new Array(pBrick, pUniqueID, pLabel, pTarget, pMode, pContext, cache)} );
	}


function loadOJAXInto(pHandler, pTarget)	{

	ojaxTargetLoads(pTarget);

	if (pHandler.indexOf('?')==-1)
		handler = pHandler + '?tctxt=ojax';
	else
		handler = pHandler + '&tctxt=ojax';


	new Ajax.Request(handler, {  evalScripts:true, onComplete:new Function ('t', 'finishOjaxRequest("'+pTarget+'", t)')});

}

function loadIVInto(pTarget, pID, pMode)	{

	var parms 	= new Hash();
	
	if (arguments.length>3){
		parms = Object.toJSON(arguments[3]);
	}

	
		var url	= '/en/p11382/index.html?id='+escape(pID)+'&mode='+escape(pMode)+'&tctxt=ojax&parms='+escape(parms);
	

	ojaxTargetLoads(pTarget);

	new Ajax.Request(url, {  method:'post', evalScripts:true, onComplete:new Function ('t', 'finishOjaxRequest("'+pTarget+'", t)')});

}

function filterRegionLoader(pFilter, pID)	{

	var parms 	= new Hash();

	
		var url	= '/en/p13539/index.html?id='+escape(pID)+'&filter='+pFilter+'&tctxt=ojax&parms='+escape(parms.toJSON());
	

	if (arguments.length>2){
		parms = arguments[2];
	}

	//ojaxTargetLoads(pTarget); ???
	ojaxTargetLoads(pFilter+'region');

	new Ajax.Request(url, {  method:'post', evalScripts:true, onComplete:new Function ('t', 'finishOjaxRequest("'+pFilter+'region", t)')});

}




function showElementToggle(pElement,pState){
	
	//
	//	pElement : ID of element
	//	pState	 : change visibility to this (hidden;visible)
	//
	
	if(conElement = document.getElementById(pElement)){
	
		oldState = conElement.style.visibility;
		
		if(pState == ""){
			conElement.style.visibility = "visible";
		}else{
			conElement.style.visibility = pState;
		}
	
	}
	
}

function checkRows(textArea, pMinCols){
			
	if (navigator.appName.indexOf("Microsoft Internet Explorer") == 0) {
		textArea.style.overflow = 'visible';
		return;
	}
	
	while (textArea.rows > pMinCols && (textArea.scrollHeight < textArea.offsetHeight)){
		textArea.rows--;
	}
	
	while (textArea.scrollHeight > textArea.offsetHeight) {
		textArea.rows++;
	}
	
	return;
}


function checkCount(pTextarea){
	
	var element = $(pTextarea);
	
	if($(pTextarea+'_count')){
		
		$(pTextarea+'_count').innerHTML = element.value.length;
	
	}
}

function checkMax(Object,MaxLen,Event){
	
	 event = Event || window.Event;

	
	if(event.keyCode == 8 || event.keyCode==46 || (event.keyCode>=35&&event.keyCode<=40))
		return true;
		
	if(Object.value.length == MaxLen)
		return false;
		
	if(Object.value.length > MaxLen){
		
		Object.value=Object.value.substring(0,MaxLen);
		
		return false;
		
	}
		
	
}


function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
	obj.value=obj.value.substring(0,mlength)
}


function clearContent(pElement,pDefaultText){
	
	var element = $(pElement);
	
	if(element.value == pDefaultText){	
		element.value = '';
		element.setStyle({'color':''});
	}

}



	var columns 		= new Array();
	var columnssliders	= new Array();
	var boxmargin		= 10;
	var guimode			= 'page';
	var endid			= 0;
	
	function sliderSnap(pCol, pX, pY)	{
		
		var x					= pX;
		var rightsingularity 	= columns[pCol+1].getWidth()+columns[pCol].getWidth()-40;

		$('debugger').innerHTML = rightsingularity+' '+pX;
			
		if(x<20)
			x = 20;
		else	
			if (x>rightsingularity)
				x = rightsingularity;
		
 	 return [x, pY];
	}
	
	function sliderDrag(pCol, pE, pMouse)	{
		var	left 	= columnssliders[pCol].offsetLeft		
		var total 	= columns[pCol+1].getWidth()+columns[pCol].getWidth();
		var width1	= left;
		var	width2	= total-width1-boxmargin;
		
		columns[pCol].setStyle({width:width1+'px'});
		columns[pCol+1].setStyle({width:width2+'px'});		
	
	}
	
	function sliderEnd(pCol, pE, pMouse)	{
		var widths = Array();
		
		for (I=0;I<columns.length;I++)
			widths[I] = columns[I].getWidth();
		
		xAction('', guimode, endid, widths);
	}

	function enableSlider(pI)	{
		new Draggable('COLUMN'+pI+'SLIDER', {constraint:'horizontal', onDrag:new Function('sliderDragHooker'+pI,'sliderDrag('+pI+',arguments[0], arguments[1]);'),  onEnd:new Function('sliderDragHooker'+pI,'sliderEnd('+pI+',arguments[0], arguments[1]);'),  snap:new Function('sliderDragHooker'+pI,'return sliderSnap('+pI+',arguments[0], arguments[1]);')});
	}
		
	function enableSliders(pColumns, pBoxMargin, pMode, pID)	{
		
		boxmargin 	= pBoxMargin;
		guimode		= pMode;
		endid		= pID;
		
		for (I=0;I<pColumns;I++){			
			columns[I] 			= $('COLUMN'+I);		
			if (I<pColumns-1)	{
				columnssliders[I] 	= $('COLUMN'+I+'SLIDER');					
				enableSlider(I);
			}
		}
	}



 

Array.prototype.has = function(value) {

	var i;
	
	for (var i = 0, loopCnt = this.length; i < loopCnt; i++) {
	
		if (this[i] === value) {
		
			return true;
		
		}
	
	}
	
	return false;

};



Ajax.ZapAutocompleter = Class.create(Ajax.Autocompleter,
{
	markPrevious: function() {
	    if(this.index > 0) this.index--;
	      else this.index = this.entryCount-1;
  	},

 	 markNext: function() {
	    if(this.index < this.entryCount-1) this.index++;
	      else this.index = 0;
  	},
  	
  	onKeyPress: function(event) {
    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         Event.stop(event);
         return;
      }
     else{
       if(this.options.actype == "multi"){
     		switch(event.keyCode){
		       	case Event.KEY_RETURN:
      					this.options.addfunction('', this.element.value);
		    }
       }
     	
     	if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
         (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
     }

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer =
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  }
  	
	
});

function trimspaces(pValue){
	
	var temp = ''+pValue+'';
	reg = /\s+/;
	return temp.replace(reg, "");
	
}

function checkACInput(pName){
	
		if( $(pName+'_label').value != $(pName+'_lastlabel').value){
			$(pName+'_type').value = "request";

		}

}




var Autocompleter2 = { };
Autocompleter2.Base = Class.create({
  baseInitialize: function(element, update, options) {
    element          = $(element);
    this.element     = element;
    this.update      = $(update);
    this.updatezone  = $(''+update+'Values'); // Where to show the new values
    this.updateadd	 = $(''+update+'New'); // If we don't find annything, show
    this.hasFocus    = false;
    this.changed     = false;
    this.active      = false;
    this.index       = 0;
    this.entryCount  = 0;
    this.oldElementValue = this.element.value;

    if(this.setOptions)
      this.setOptions(options);
    else
      this.options = options || { };

    // Type

    this.options.limitac	  = this.options.limitac || false;

    // Yellow
    this.options.yellow		  = this.options.yellow || false;
    this.options.yellowset	  = false;
    this.options.yellowlist	  = '';
    this.options.yellowcb	  = this.options.yellowcb || '';

    this.options.paramName    = this.options.paramName || this.element.name;
    this.options.tokens       = this.options.tokens || [];
    this.options.frequency    = this.options.frequency || 0.4;
    this.options.minChars     = this.options.minChars || 1;
    this.options.onShow       = this.options.onShow ||
      function(element, update){
        if(!update.style.position || update.style.position=='absolute') {
          update.style.position = 'absolute';

          update.show();
          update.clonePosition(element,{

          	setHeight: false,
            offsetTop: element.offsetHeight

          });
          update.hide();



          /*Position.clone(element, update, {
            setHeight: false,
            offsetTop: element.offsetHeight
          });*/

        }

       	// Show Div
        Effect.SlideDown(update,{duration:0.15});
      };

    this.options.onHide = this.options.onHide ||
      function(element, update){ new Effect.Fade(update,{duration:0.15}) };

    if(typeof(this.options.tokens) == 'string')
      this.options.tokens = new Array(this.options.tokens);
    // Force carriage returns as token delimiters anyway
    if (!this.options.tokens.include('\n'))
      this.options.tokens.push('\n');

    this.observer = null;

    this.element.setAttribute('autocomplete','off');

    //Element.hide(this.update);

    Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
    Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));


    // Focus The element field
    Event.observe(this.element, 'focus', this.onFocus.bindAsEventListener(this));

  },

  show: function() {


    if(Element.getStyle(this.update, 'display')=='none'){

    	this.options.onShow(this.element, this.update);

    }



    if(!this.iefix &&
      (Prototype.Browser.IE) &&
      (Element.getStyle(this.update, 'position')=='absolute')) {
      new Insertion.After(this.update,
       '<iframe id="' + this.update.id + '_iefix" '+
       'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
       'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
      this.iefix = $(this.update.id+'_iefix');
    }
    if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
  },

  fixIEOverlapping: function() {
    Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
    this.iefix.style.zIndex = 1;
    this.update.style.zIndex = 2;
    Element.show(this.iefix);
  },

  hide: function() {

    this.stopIndicator();
    if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
    if(this.iefix) Element.hide(this.iefix);

    this.updatezone.innerHTML = '';

  },

  startIndicator: function() {
    if(this.options.indicator) Element.show(this.options.indicator);
  },

  stopIndicator: function() {
    if(this.options.indicator) Element.hide(this.options.indicator);
  },

  onKeyPress: function(event) {
    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         Event.stop(event);
         return;
      }
     else
       if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
         (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer =
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  },

  activate: function() {
    this.changed = false;
    this.hasFocus = true;
    this.getUpdatedChoices();
  },

  onHover: function(event) {
    var element = Event.findElement(event, 'LI');
    if(this.index != element.autocompleteIndex)
    {
        this.index = element.autocompleteIndex;
        this.render();
    }
    Event.stop(event);
  },

  onClick: function(event) {
    var element = Event.findElement(event, 'LI');
    this.index = element.autocompleteIndex;
    this.selectEntry();
  },

  onBlur: function(event) {
    // needed to make click events working
    setTimeout(this.hide.bind(this), 250);
    this.hasFocus = false;
    this.active = false;
  },

  onFocus: function(event) {
    this.show();
  },

  render: function() {
    if(this.entryCount > 0) {
      for (var i = 0; i < this.entryCount; i++)
        this.index==i ?
          Element.addClassName(this.getEntry(i),"selected") :
          Element.removeClassName(this.getEntry(i),"selected");
      if(this.hasFocus) {
        this.show();
        this.active = true;
      }
    }/* else {
      this.active = false;
      this.hide();
    }*/
  },

  markPrevious: function() {
    if(this.index > 0) this.index--;
      else this.index = this.entryCount-1;
    this.getEntry(this.index).scrollIntoView(true);
  },

  markNext: function() {
    if(this.index < this.entryCount-1) this.index++;
      else this.index = 0;
   this.getEntry(this.index).scrollIntoView(false);
  },

  getEntry: function(index) {
    return this.updatezone.firstChild.childNodes[index];
  },

  getCurrentEntry: function() {
    return this.getEntry(this.index);
  },

  selectEntry: function() {
    //this.active = false;
    this.updateElement(this.getCurrentEntry());
  },

  updateElement: function(selectedElement) {
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = $(selectedElement).select('.' + this.options.select) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');

    var bounds = this.getTokenBounds();
    if (bounds[0] != -1) {
      var newValue = this.element.value.substr(0, bounds[0]);
      var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value + this.element.value.substr(bounds[1]);
    } else {
      this.element.value = value;
    }
    this.oldElementValue = this.element.value;
    this.element.focus();

	 if (this.options.afterUpdateElement){
	 	this.options.afterUpdateElement(this.element, selectedElement);
	 }

  },

  updateChoices: function(choices) {

  ////console.log('[updateChoices]');

   if(!this.changed && this.hasFocus) {

      this.updatezone.innerHTML = choices;

      	if(this.options.limitac != true){

	        var licont			= Builder.node('LI',{ className: 'inputAutoCompleter2_addTag_container'});
	     	var container		= Builder.node('DIV');
	      	var imagediv 		= Builder.node('DIV',{ className: 'ac_view_icon informal' });
	      	var	image			= Builder.node('IMG',{SRC:this.options.iconadd,ALT:''});
			var addtextcont		= Builder.node('DIV',{className:'ac_view_content inputAutoCompleter2_addTag'});
			var addtexttitle	= Builder.node('DIV');
			var addtexttitle2	= Builder.node('SPAN',{className:'inputAutoCompleter2_addTag_title'},this.element.value);
			var	addtext			= Builder.node('DIV',{className:'title_small_grey informal'});

			addtext.innerHTML 	= this.options.tagtext;

			imagediv.appendChild(image);

			addtexttitle.appendChild(addtexttitle2);
			addtextcont.appendChild(addtexttitle);
			addtextcont.appendChild(addtext);

			container.appendChild(imagediv);
			container.appendChild(addtextcont);

			licont.appendChild(container);

	      this.updatezone.firstChild.appendChild(licont);

       }

      Element.cleanWhitespace(this.updatezone);
      Element.cleanWhitespace(this.updatezone.down());

      if(this.updatezone.firstChild && this.updatezone.down().childNodes) {

      	this.entryCount = this.updatezone.down().childNodes.length;

        for (var i = 0; i < this.entryCount; i++) {
          var entry = this.getEntry(i);
          entry.autocompleteIndex = i;
          this.addObservers(entry);
        }
      } else {
        this.entryCount = 0;
      }


      this.stopIndicator();
      this.index = 0;

      if(this.entryCount==1 && this.options.autoSelect) {
        this.selectEntry();
        //this.hide();
      } else {
        this.render();
      }
    }
  },

  addObservers: function(element) {
    Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
    Event.observe(element, "click", this.onClick.bindAsEventListener(this));
  },

  onObserverEvent: function() {
    this.changed = false;
    this.tokenBounds = null;
    if(this.getToken().length>=this.options.minChars) {
      this.getUpdatedChoices();
    } else {
    	this.updatezone.innerHTML = '';
      	//this.active = false;
      	//this.hide();
    }
    this.oldElementValue = this.element.value;
  },

  getToken: function() {
    var bounds = this.getTokenBounds();
    return this.element.value.substring(bounds[0], bounds[1]).strip();
  },

  getTokenBounds: function() {

    if (null != this.tokenBounds) return this.tokenBounds;

    var value = this.element.value;

    if (value.strip().empty()) return [-1, 0];

    var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);

    var offset = (diff == this.oldElementValue.length ? 1 : 0);

    var prevTokenPos = -1, nextTokenPos = value.length;

    var tp;

    for (var index = 0, l = this.options.tokens.length; index < l; ++index) {


      tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
      if (tp > prevTokenPos) prevTokenPos = tp;
      tp = value.indexOf(this.options.tokens[index], diff + offset);
      if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
    }

    return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
  }
});

Autocompleter2.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
  var boundary = Math.min(newS.length, oldS.length);
  for (var index = 0; index < boundary; ++index)
    if (newS[index] != oldS[index])
      return index;
  return boundary;
};



Ajax.Autocompleter2 = Class.create(Autocompleter2.Base, {
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;

    // testing
     this.options.isDone	     = false;
     this.options.isDoneYellow   = false;

    this.url                   = url;
  },

  getUpdatedChoices: function() {

    this.startIndicator();

    var entry = encodeURIComponent(this.options.paramName) + '=' +
      encodeURIComponent(this.getToken());

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

    if(this.options.defaultParams){
      this.options.parameters += '&' + this.options.defaultParams;
    }

    this.options.isDone	   = false;
    this.options.isDoneYellow = false;

    new Ajax.Request(this.url, this.options);


    if(this.options.yellow){

	    /*new Ajax.Request('http://www.zapdev.lu/proxy/yellow?q='+encodeURIComponent(this.element.value), {  method: 'get',
		  onComplete: function(reponse){

		  	this.injectYellowTokens(reponse.responseText);

		  }.bind(this)
		});*/

		//request = 'http://www.zapdev.lu/proxy/yellow?q='+encodeURIComponent(this.element.value)+'&callback='+this.options.yellowcb;
		request = 'http://yellow.rtl.lu/search/zap/?q='+encodeURIComponent(this.element.value);

		aObj = new JSONscriptRequest(request);
		aObj.buildScriptTag();
		aObj.addScriptTag();


  	}

  },

  //
  onComplete: function(request) {

  	if(this.options.isDone)
  		return true;

  	var response = request.responseText;

    if(this.options.isDoneYellow){
      	response = response.substr(0,response.length-5) + this.options.yellowlist + '</ul>';
    }

    this.options.isDone	= true;

	this.updateChoices(response);

  },

  getYellowTokens: function(){

	// The web service call
	var req  = 'http://yellow.rtl.lu/search/zap?q=luxembourg';
	// Create a new request object
	bObj = new JSONscriptRequest(req);
	// Build the dynamic script tag
	bObj.buildScriptTag();
	// Add the script tag to the page
	bObj.addScriptTag();

  },

  injectYellowTokens: function(reponse){

  	if(this.options.isDoneYellow || !this.active){
  		return true;
  	}
  	
  	var yellow  = reponse;
  	
  	var elementHTML = '';

  	var wrap = Builder.node('div');

  	for(var I=0;I<yellow.size();I++){
  		
  		if(I >= 4){ // limit to 4
  			break;
  		}
  		 	
  		//var title = yellow[I].title.slice(0,1).toUpperCase() + yellow[I].title.slice(1);

  		var title = '';

  		var tmp_title = yellow[I].title.split(" ");

  		for(var Y=0;Y<tmp_title.size();Y++){

  			title = title + ' ' + tmp_title[Y].slice(0,1) + tmp_title[Y].slice(1);

  		}


  		//var city = yellow[I].citylu.slice(0,1).toUpperCase() + yellow[I].citylu.slice(1);
  		var city = '';
  		
  		var address1 =  yellow[I].addr1;
  		var address2 =  yellow[I].addr2;

  		if(I==0){

  			var cell_container 	= 	Builder.node('li',{'class':'ac_yellow_header'});
  			var cell_title		= 	Builder.node('div',{'class':'ac_yellow_header'},title)

  		}else{

  			var cell_container 	= 	Builder.node('li');
  			var cell_title		= 	Builder.node('div',{'class':''},title)

  		}

  		var cell_label 		= 	Builder.node('div');
  		
  		
  		if(!empty(yellow[I].addr1)){
  			
  			var address1 =  yellow[I].addr1;
  			cell_label.appendChild(Builder.node('span',{'class':'title_small_grey informal','style':'line-height:11px;'},address1));
  			
  		}
  		
  		if(!empty(yellow[I].addr2)){
  			
  			cell_label.appendChild(Builder.node('br'));
  			
  			
  			var address2 =  yellow[I].addr2;
  			cell_label.appendChild(Builder.node('span',{'class':'title_small_grey informal','style':'line-height:11px;'},address2));
  			
  		}


  		if(!empty(yellow[I].htmlpage)){

  			var cell_link		= 	Builder.node('div',{'style':'display:none','class':'yellow_link informal'},yellow[I].htmlpage);
  			cell_container.appendChild(cell_link);

  		}

  		cell_container.appendChild(cell_title);
  		cell_container.appendChild(cell_label);
  		wrap.appendChild(cell_container);




  	}

  	// done with calculation
  	this.options.isDoneYellow = true;

  	if(this.options.isDone){

  		tmp = this.updatezone.innerHTML;

  		tmp = tmp.substr(0,tmp.length-5) + wrap.innerHTML + '</ul>';

  		elementHTML = tmp;

  	}else{

  		//console.log('[injectYellowTokens] Display alone');
  		//console.log(wrap.innerHTML);

  		if(!empty(wrap.innerHTML)){
  			elementHTML = '<ul>'+wrap.innerHTML+'</ul>';
  		}

  		this.options.yellowlist = wrap.innerHTML;
  	}
  	
   	tmpIndex = this.index;

   	// update with injected cells
  	this.updateChoices(elementHTML);
  	
  	this.index = tmpIndex;
    this.render();

  }


});


/** NEW AUTOCOMPLETE **/

Ajax.ZapAutocompleter2 = Class.create(Ajax.Autocompleter2,
{
	markPrevious: function() {
	    if(this.index > 0) this.index--;
	      else this.index = this.entryCount-1;
  	},

 	 markNext: function() {
	    if(this.index < this.entryCount-1) this.index++;
	      else this.index = 0;
  	},

  	onKeyPress: function(event) {
    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         Event.stop(event);
         return;
      }
     else{
       if(this.options.actype == "multi" && !this.options.limitac){
     		switch(event.keyCode){
		       	case Event.KEY_RETURN:
		       			//alert('pressed enter!');
      					this.options.addfunction('', this.element.value);
      					this.hide();
		    }
       }

     	if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
         (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
     }

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer =
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  }


});


// Local Autocompleter
localACSearch = function(pElement,pSearchZone){

			toShow = new Array();
			toHide = new Array();

			var hits = $(pSearchZone).select('div.ac_view_label');
			var search = $(pElement).value.toLowerCase();
			var tmp = '';

			for(I=0;I<hits.size();I++){

				tmp = hits[I].innerHTML.toLowerCase();

				if(tmp.indexOf(search)<0){

					// search for parent
					//hits[I].parentNode.parentNode.hide();
					//hits[I].up().up().hide();
					toHide.push(hits[I].up().up());

				}else{

					//hits[I].parentNode.parentNode.show();
					//hits[I].up().up().show();
					toShow.push(hits[I].up().up());

					if(search.length > 0){
						// effect

					}

				}

			}

			//
			toHide.each(Element.hide);
			toShow.each(Element.show);
	}



var localAC = {

		searchlist: new Array(),
		elementlist: new Array(),
		element : null,
		started: false,

		init: function(pElement,pSearchZone){

			var startTime = new Date();

			this.element = $(pElement);

			this.searchlist.clear();
			this.elementlist.clear();

			var hits = $(pSearchZone).select('div.ac_view_label');

			for(I=0;I<hits.size();I++){

				this.searchlist.push(hits[I].innerHTML.toLowerCase());
				this.elementlist.push(hits[I].up().up());

			}

			////console.log("Calculate: ", new Date() - startTime, " ms");

		},

		search: function(){

			var startTime = new Date();

			var searchstr = this.element.value.toLowerCase();

			var HideArray = new Array();
			var ShowArray = new Array();

			if(!empty(searchstr)){

			for(var I=0;I<this.elementlist.size();I++){

				if(this.searchlist[I].indexOf(searchstr)>-1){

					ShowArray.push(this.elementlist[I]);

				}else{

					HideArray.push(this.elementlist[I]);

				}

			}

			}else{

				ShowArray = this.elementlist;

			}



			HideArray.each(Element.hide);
			ShowArray.each(Element.show);

			////console.log("Show/Hide: ", new Date() - startTime, " ms");


		},

		reset: function(pElement,pSearchZone){

			var arrayElements = new Array();

			$(pElement).value = '';

			var hits = $(pSearchZone).select('div.ac_view_label');

			for(I=0;I<hits.size();I++){

				arrayElements.push(hits[I].up().up());

			}

			arrayElements.each(Element.show);

		}

	}


	function testCallBack(pNull){

		alert('bla');

	}
	
	
var localSearch = Class.create({
	
	input 		: null,
	zone 		: null,
	css			: null,
	helptext	: '',
	searchlist	: new Array(),
	elementlist	: new Array(),
	afterSearch : null,
	
	/* -- VARs
	*	pInput = what to serach
	*	pZone = where to search
	*	pCSSClass = what to hide
	*/
	
	initialize: function(pInput,pZone,pCSSContainer,pCSSLabel) {
		
		
		this.input 			= $(pInput);
		this.zone 			= $(pZone);
		this.cssContainer	= pCSSContainer;
		this.cssLabel		= pCSSLabel;
		
		// get helper text
		this.helptext = this.input.value;
		
		// clear vars
		this.searchlist.clear();
		this.elementlist.clear();
		
		// Hits
		this.elementlist = this.zone.select(this.cssContainer);
		
		// Populate list
		for(I=0;I<this.elementlist.size();I++){
			

			var tmp = this.elementlist[I].select(this.cssLabel);
			
			this.searchlist.push(tmp[0].innerHTML.toLowerCase());	

		}
		
		// events
		this.input.observe('keyup', this.search.bind(this));
		//this.input.observe('keydown', this.evalKey.bind(this));
		
	},
	
	evalKey: function(e){
				
		var keycode;
		
		if (window.event) keycode = window.event.keyCode;
		
		else if (e) keycode = e.which;
		
		zap.log('CODE:'+keycode);
		
		if(keycode == 27){
			
			this.reset();
					
		}
		
	},
	
	search: function(){
		
		var searchstr = this.input.value.toLowerCase();
		
		var HideArray = new Array();
		var ShowArray = new Array();

		if(!empty(searchstr)){

			for(var I=0;I<this.elementlist.size();I++){

				if(this.searchlist[I].indexOf(searchstr)>-1){

					ShowArray.push(this.elementlist[I]);

				}else{

					HideArray.push(this.elementlist[I]);

				}

			}

		}else{

				ShowArray = this.elementlist;

		}

		HideArray.each(Element.hide);
		ShowArray.each(Element.show);
		
		if(this.afterSearch !== null)
			this.afterSearch();
		
	},

	reset: function(){
		
		this.elementlist.each(Element.show);
		this.input.value = '';
		
		if(this.afterSearch !== null)
			this.afterSearch();
		
	}	
 	
 });
 
 
 

 // new Autocompleter 
 
var zapAutocompleter = { };

zapAutocompleter.Base = Class.create(Autocompleter.Base,{
	
});
	
	
Ajax.zapAutocompleter = Class.create(Ajax.Autocompleter,{
	
	
	baseInitialize : function($super, element, update, options) {
		
		//rewrite onshow
		options.onShow = this.onShowNew;
		
		
		//parent
		$super(element, update, options);
		
		// extend my vars
		zap.log('Init after parent');
		
	},
	
	markPrevious: function() {
	    if(this.index > 0) this.index--;
	      else this.index = this.entryCount-1;
  	},

 	markNext: function() {
	    if(this.index < this.entryCount-1) this.index++;
	      else this.index = 0;
  	},
  	
  	onKeyPress: function($super, event) {
  		
  		if(!this.active){

  			switch(event.keyCode){
		       	case Event.KEY_RETURN:
		       		zap.log('Enter not alowed when not active')
      			
		    }	
  			
  		}
  		
  		//parent
  		$super(event);
  		
  	},
  	
  	
  	selectEntry: function($super){
  		
  		
  		value = this.getCurrentEntry();
  		
  		this.evalReturn(value);
  		  		
  		//parent
  		$super();
  		
  		//reset input
  		this.element.value = '';
  		
  		//trigger function after having value
  		
  	},
  	
  	
  	evalReturn: function(pElement){
  		
  		element = $(pElement);
 
  		label = Element.collectTextNodesIgnoreClass(element,'informal'); 
  		
  		zap.log('Label:'+label);
  		zap.log('Id:'+element.id);  		
  		
  	},
  	
  	onShowNew: function(element, update){
  		
        if(!update.style.position || update.style.position=='absolute') {
          update.style.position = 'absolute';
          Position.clone(element, update, {
            setHeight: false,
            offsetTop: element.offsetHeight,
            setLeft:false
          });
        }
        
        //add borders 
        zap.log('Width:'+update.getWidth());
        
        update.style.width = (update.getWidth() + 1) + 'px';
        
        Effect.Appear(update,{duration:0.15});
        
    }
	
});
	
	







function isset(  ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FremyCompany
    // +   improved by: Onno Marsman
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true
    
    var a=arguments; var l=a.length; var i=0;
    
    if (l==0) { 
        throw new Error('Empty isset'); 
    }
    
    while (i!=l) {
        if (typeof(a[i])=='undefined' || a[i]===null) { 
            return false; 
        } else { 
            i++; 
        }
    }
    return true;
}

var elCounter 	= 1;

function buildTagDivTo(pID,pValue,pFormID,pName,pDestination,pLimit){

		var draw 		= false;
		var inputvalue	= '';
		var inputid		= '';
		var showvalue	= '';
		var approved	= '';
		
		
		elCounter++;

		if((pID == "") && (trimspaces(pValue) != "")){
				draw 		= true;
				inputid 	= 'r'+elCounter;
				inputvalue 	= pValue;
		}else if((pID != "") && (trimspaces(pValue) != "")){
				draw = true;
				inputid 	= pID;
				inputvalue 	= '';
				approved	= '_approved';
				
		}
			
		if(draw == true){
	
			container_cell 			= Builder.node('div', 	{id: inputid, className: 'form_multipleinputs_container_cell'+approved});
			container_cell_start 	= Builder.node('div', 	{className: 'form_multipleinputs_container_cell'+ approved +'_start'});
			container_cell_center 	= Builder.node('div', 	{className: 'form_multipleinputs_container_cell'+ approved +'_center'},pValue);
			container_cell_remove	= Builder.node('div', 	{className: 'form_multipleinputs_container_cell'+ approved +'_remove',onclick:"this.up().remove(true); return false;"});
			valueinput				= Builder.node('input', {id:pFormID+'input'+pName, type: 'hidden', name: pName+'['+inputid+']', value: inputvalue})
			
			container_cell_center.appendChild(valueinput);
			container_cell.appendChild(container_cell_start);
			container_cell.appendChild(container_cell_center);
			container_cell.appendChild(container_cell_remove);
			
			if(pLimit == "1"){	
				$(pDestination).innerHTML = '';
			}
			$(pDestination).appendChild(container_cell);

		}

}



function elToggle(pElement){
	
	var effType 	= 'appear';
	var effDuration = 0.3;
	
	Effect.toggle(pElement, effType, { duration: effDuration});
	
}

function NotesTreeToggle(pSource,pElement){
	
	var source = $(pSource);
	var element = $(pElement);
	
	if(	source.hasClassName('form_tree_container_close') ){
		
			source.removeClassName('form_tree_container_close');
			source.toggleClassName('form_tree_container_open');
		
	}else{
			source.removeClassName('form_tree_container_open');
			source.toggleClassName('form_tree_container_close');
	}
	
	elToggle(element);
	
}


	
/* Filter V3 */
var filter3 = Class.create({
	
	criterias		: new Hash(),
	defcriterias 	: new Hash(),
	savedcriterias	: new Hash(),
	savedlookup		: new Hash(),
	
	// State
	state			:{
		
			STATE_DEFAULT 	: 0, // Bubble not shown
			STATE_MODIFIED 	: 1,  // Bubble shown
			STATE_LOADED	: 2
		
	},
	
	actualstate 	: null,
	statefed		: '(changed)',
	actualloaded	: null,
	
	isuser			: false,
			
	
	// Elements list
	elements  		: new Hash(),
	
	cloudelement	: null,
	activeelement	: null,
	syslabel		: '',
	
	// List of sources
	sourcelist		: new Array(),
	sourcelookup	: new Hash(),
	
	// Count of the nodes
	countlist		: new Array(),
	countlookup		: new Hash(),
	
	// Count vars
	mincount 		: null,
	maxcount 		: 0,
	
	// TopN function
	topmax			: 20,
	topenable		: true,
	toplist			: new Array(),
	tophash			: new Hash(),
	
	// Active Nodes
	activelist		: new Hash(),
	waitlist		: new Hash(),
	
	// List of static nodes
	staticlist		: new Hash(),
	

	// *****************************************
  	// Initialize filter
  	
	 	initialize: function(pLabel,pCriterias) {
	 		
	 		if(!empty(pCriterias)){			
	 			
	 			if((typeof pCriterias == 'string')){
	 				
	 				pCriterias = pCriterias.evalJSON();	 				
	 				
	 			}
	 			
	 			if((typeof pCriterias == 'object')){
	 				
	 				this.actualstate = this.state.STATE_DEFAULT;

		 			this.convertToHash(pCriterias);
		 			
		 			this.syslabel 	= pLabel;
		 			
		 			if($(pLabel+'ItemTags')){
		 				
		 				this.cloudelement  = $(pLabel+'ItemTags');
		 				this.activeelement = $(pLabel+'SelectedTags');
		 					 				
		 			}else{
		 				
		 				zap.log('[initialize] No Cloud found');
		 				
		 			}
	 			
	 			}else{
	 				
	 				zap.log('[initialize] Problem: pCriterias Wrong Type');
	 				zap.log('[initialize] Type: '+typeof pCriterias);
	 				zap.log('[initialize] Element: '+pCriterias);
	 			
	 			}
	 			
	 			
	 			
	 		}else{
	 			
	 			zap.log('[initialize] Problem: pCriterias Empty');

	 		}
	 		
	  	},
	  	
	  	
	  	setLabel: function(pLabel){
	  		
	  		this.syslabel 	= pLabel;
	  		this.cloudelement  = $(pLabel+'ItemTags');
		 	this.activeelement = $(pLabel+'SelectedTags');
	  		
	  	},

	  	setStateTitel:function(pText){
	  		
	  		var elTitle = $(this.syslabel+'savepanel_state');
	  		
	  		if(!empty(pText)){
	  				  		
	  			elTitle.innerHTML = ' - '+pText;
	
	  		}else{
	  			
	  			elTitle.innerHTML = '';
	  		}
	  		
	  	},
	  	
	  	showBubble:function(){
	  		
	  		$(this.syslabel+'savepanel').show();
	  		
	  	},
	  	
	  	
	  	hideBubble: function(){
	  		
	  		if(this.savedcriterias.size() == 0){
	  		
	  			$(this.syslabel+'savepanel').hide();
	  		
	  		}
	  			
	  	},
	  	
	  	
	  	// pIsUser = boolean 
	  	setUserState: function(pIsUser){
	  		
	  		this.isuser = pIsUser;
	  		
	  	},
	  	
	  	
	  	hideSaveLink: function(){
	  		
	  		if($(this.syslabel+'savecriteriastate')){
	  		
	  			$(this.syslabel+'savecriteriastate').hide();
	  			
	  			//$(this.syslabel+'savecriteriastatecontainer').hide();
	  		
	  		}
	  		
	  	},
	  	
	  	
	  	showSaveLink: function(){
	  		
	  		if($(this.syslabel+'savecriteriastate')){
	  		
	  			$(this.syslabel+'savecriteriastate').show();
	  		
	  		}
	  		
	  	},
	  		  	
	  	
	  	changeState: function(pNewState,pNewTitle){
	  		
	  		var oldstate = this.actualstate;
	  		var newstate = pNewState;
	  		
	  		if(oldstate == this.state.STATE_DEFAULT){
	  			
	  			if(newstate == this.state.STATE_MODIFIED){
	  				
	  				this.showBubble();
	  				
	  				this.showSaveLink();
	  				
	  				this.showResetLink();
	  				
	  				this.setStateTitel(this.statefed);
	  				
	  			}
	  			
	  			if(newstate == this.state.STATE_LOADED){
	  				
	  				this.setStateTitel(pNewTitle);
	  				
	  				this.showResetLink();

	  			}
	  			
	  			this.actualstate = newstate;
	  			
	  		}
	  		
	  		
	  		if(oldstate == this.state.STATE_MODIFIED){
	  			
	  			if(newstate == this.state.STATE_DEFAULT){
	  				
	  				this.setStateTitel('');
	  				
	  				this.hideSaveLink();
	  				this.hideResetLink();
	  				
	  				if(this.savedcriterias.size() == 0){
	  					
	  					this.hideBubble();
	  					
	  				}
	  				
	  				this.actualloaded = null;
	  				
	  			}
	  			
	  			if(newstate == this.state.STATE_LOADED){
	  				
	  				this.setStateTitel(pNewTitle);
	  				
	  				this.hideSaveLink();

	  			}

	  			this.actualstate = newstate;  			
	  			
	  		}
	  		
	  		
	  		if(oldstate == this.state.STATE_LOADED){
	  			
	  			if(newstate == this.state.STATE_DEFAULT){
	  				
	  				this.setStateTitel(pNewTitle);
	  				
	  				this.hideSaveLink();
	  				
	  				this.hideResetLink();
	  				
	  				this.actualloaded = null;
	  				
	  			}
	  			
	  			
	  			if(newstate == this.state.STATE_MODIFIED){
	  				
	  				this.showSaveLink();
	  				
	  				this.showResetLink();
	  				
	  				this.setStateTitel(this.statefed);
	  				
	  				this.actualloaded = null;

	  			}
	  			
	  			if(newstate == this.state.STATE_LOADED){
	  					  				
	  				this.setStateTitel(pNewTitle);
	  				
	  			}
	  			
	  			this.actualstate = newstate;
	  			
	  		}

	  	},
	  	
	  	showResetLink: function(){
	  		
	  		$(this.syslabel+'resetdefaultcriterias').show();
	  		
	  	},
	  	
	  	
	  	hideResetLink: function(){
	  		
	  		$(this.syslabel+'resetdefaultcriterias').hide();
	  		
	  	},
	  	
	  		  	
	//
  	// *****************************************
  	
  	// *****************************************
  	// ELEMENTS handling
  	
  		addElement: function(pCriteria,pElementsArray,pType){
  						  			
  			this.elements.set(pCriteria,[pType,pElementsArray]);
  			
  		},
  		
  		resetToDefault: function(){
  			
  			this.changeState(this.state.STATE_DEFAULT,'');
  			  			
  			this.resetElements(this.defcriterias);
  			
  			this.criteriaXaction('');  	
  			
  		},
  		
  		
  		resetToActive: function(){
  			
  			this.resetElements(this.criterias);
  			
  		},
  		
  		
  		resetElements: function(pCriterias){
  			
  			var values = pCriterias;
  			  			  			
  			var keys = this.elements.keys();
  			
  			for(var I=0;I<keys.size();I++){
  				
  				tmp = this.elements.get(keys[I]);
  				
  				type = tmp[0];
  				tmparray = tmp[1];
  				
  				value = values.get(keys[I]);
  				
  				switch(type){
  					
  					case"checkbox":
  					
  						mycheckbox = tmparray[0];
  						  						
  						this.resetElementCheckbox(mycheckbox[0],value);
  					
  					break;
  					
  					
  					case"radio":
  					
  						//zap.log('[radio] Value: '+value+' Type:'+typeof value);
  					
  						this.resetElementRadio(tmparray,value);
  					
  					break;
  					
  					case"calendar":
  					  						
  						//zap.log('[calendar] Value: '+value+' Type:'+typeof value);
  					  						  						
  						date = value.split('-');
  						
  						date = date[0]+date[1]+date[2];
  						  						  						
  						var calobject = tmparray[0];

  						tmpEvent  = eval(calobject+'.handlers');
  						
  						var tmpSelect = tmpEvent.onSelect;
  						
  						tmpEvent.onSelect = Prototype.emptyFunction;
  						
  						eval(calobject+'.selection.set('+date+');');
  						eval(calobject+'.moveTo('+date+');');
  						
  						tmpEvent.onSelect = tmpSelect;
  						  						
  					
  					break;
  					  					
  					case"bounding":
		
  						$(''+tmparray[0]+'').value = value;
  						
  					break;
  					
  					case"region":
  					
  						//zap.log('[region] Value:'+value);
  						
  						region 	= value;
  						label 	= tmparray[0][0];
  						input 	= tmparray[0][1];
  						acview 	= tmparray[0][2];

  						$(''+input+'').value = '';
  						
  						if(!empty(region)){
  						
  							$(''+acview+'').show();
  							
  							filterRegionLoader(label, region);

  						}

  					break;
  					
  					case"regionradius":
  					  						
  						$(''+tmparray[0]+'').value = value;
  					
  					break;
  					
  					case"acsearch":
  					
  						//zap.log('[acsearch] Value:'+value);
  						

  						id 			= tmparray[0][0];
  						container 	= tmparray[0][1];
  						ivcell 		= tmparray[0][2];
  						input 		= tmparray[0][3];
  						
  						$(''+input+'').value = '';
  						
  						if(empty(value)){
  							
  							$(''+ivcell+'').hide();							
  							
  						}else{
  							  							
  							$(''+ivcell+'').show();		

  							loadIVInto(container,id,'acview');
  							
  						}
  						
  						
  					
  					break;
  					
  					case"tagcloud":
  					
  						//zap.log('[tagcloud] Value:'+value+' Type:'+typeof value);
  						  						 
  						this.resetElementTagCloud(value);

  					break;
  					
  					
  					case"checkboxes":
  					  					
  						this.resetElementCheckboxes(tmparray,value);
  					
  					break;
  					
  					// special
  					case"checkboxcloud":
  					break;
  					
  					
  					
  					
  					
  				}
 				
   			}
   			
   			this.injectCriterias(values); 			
   			
   			var tmp = values.toJSON();
   			this.reloadBricks('{"vcCriteria":'+tmp.toJSON()+'}');
  			
  		},
  		
  		
  		resetElementCheckbox: function(pElement,pValue){
  			  			  			
  			var element = $(pElement);
	  		
	  		element.checked = pValue;  			
  		},
  		
  		
  		resetElementRadio: function(pElements,pValue){
  			
  			var elements = pElements;
  			
  			var tocheck = null;
  		  	  			
  			// deselect all and search Element 
  			for(var I=0;I<elements.size();I++){

  				element = elements[I];
  				
  				//if($(element[0]+'_label').hasClassName("filtertextsimple"))
  				//	$(element[0]+'_label').removeClassName("filtertextsimple");
  							  				
  				if(element[1] == pValue){
  					  					
  					tocheck = element[0];
  					
  				}else{
  					
  					$(element[0]).checked = false;
  					  					
  				}

  			}
  			
  			// Select Element of Value
  			$(tocheck).checked = true;
  			
  			//$(tocheck+'_label').addClassName("filtertextsimple");
  			
  			
  		},
  		
  		
  		resetElementTagCloud: function(pArrayIDs){
  			
  			//this.activeelement	
  			//this.activelist = new Hash();
  			
  			var tmparray = pArrayIDs;
  			var values = this.activelist.values();
  			var tmpactives = this.activelist.clone();
  			
  			
  			// remove tags
  			for(var I=0;I<tmpactives.size();I++){
  				
  				if(tmparray.indexOf(values[I]) >= 0){
  					
  					//zap.log('[resetElementTagCloud] A: Found');
  					
  				}else{
  					  					
  					this.activelist.unset(values[I]);
  					
  					$('fctag'+values[I]).remove();
  					
  				}
  				
  			}
  			
  			// add to actives
  			for(var I=0;I<tmparray.size();I++){
  				
  				
  				
  				if(typeof this.activelist.get(tmparray[I]) == 'undefined'){
  					
  					this.waitlist.set(String(tmparray[I]),tmparray[I]);		
  					
  				}else{
  					
  					//zap.log('[resetElementTagCloud] B: Found');
  					
  				}
  				
  				
  			}
  			
  			
  			
  			
  		},
  		
  		resetElementCheckboxes: function(pArray,pValues){
  			
  			var values = pValues;
  			var elements = pArray;
  			
	  		// remove tags
  			for(var I=0;I<elements.size();I++){
  				
	  			if(values.indexOf(elements[I][1])>=0){
	  				$(elements[I][0]).checked = true;
	  			}else{
	  				$(elements[I][0]).checked = false;
	  			}
  				
  			}
	  		

  		},
  		
  		/*getActiveElementForCriteria: function(pCriteria){
  			
  			//get active value
  			var critValue 		= this.getCriteria(pCriteria);
  			var critElements 	= this.elements.get(pCriteria);
  			var critType		= critElements[0];
  			
  			// remove type
  			critElements = critElements[1];
  			
  			for(var I=0;I<critElements.size();I++){
  				
  				//
  				
  				
  				
  			}
  			
  			
  		},
  		*/
  	
  	//
  	// *****************************************
  	
	
  	// *****************************************
  	// CRITERIAS handling
  	  	
  		// pCriterias = String()
  		loadSavedCriterias: function(pSaveID){
  			
  			var tmpcriterias = this.savedcriterias.get(pSaveID);
  			
  			this.injectCriterias(tmpcriterias[1]);
  			
  			this.resetToActive();
  			
  			this.criteriaXaction(pSaveID);
  			
  			this.actualloaded = pSaveID;
  			
  			// STATE
  			this.changeState(this.state.STATE_LOADED,tmpcriterias[0]);
  			  			
  		},
  		
  		// pCriterias = JSON Object()
  		addDefaultCriterias: function(pJSON){
  			
  			this.defcriterias = this.convertJSONtoCriterias(pJSON); 			
  			
  		},
  		
  		// ** Saved Criterias
  		
  		// Array of JSON Objects 
  		addSavedCriterias: function(pArray){
  			
  			var tmparray = pArray;
  			
  			for(var I=0;I<tmparray.size();I++){
  				
  				this.savedcriterias.set(tmparray[I][0],[tmparray[I][1],this.convertJSONtoCriterias(tmparray[I][2])]);
  				
  				//this.savedlookup.set(tmparray[I][1],tmparray[I][0]);
  				
  			}

  			
  		},
  		
  		addNewSavedCriterias: function(pSaveID,pName){
  			
  			this.savedcriterias.set(pSaveID,[pName,this.criterias]);
  			
  			$(this.syslabel+'savedcriteriaslist').show();
  			
  			$(this.syslabel+'savedcriterias').show();
  			
  			var node = Builder.node('li',{'id':this.syslabel+'savedcriterias_item'+pSaveID});
  			
  			node.appendChild(Builder.node('a',{'class':'text','href':'javascript:'+this.syslabel+'_filter.loadSavedCriterias('+pSaveID+')'},pName+' '));
  			
  			node.appendChild(Builder.node('a',{'href':'javascript:'+this.syslabel+'_filter.deleteSavedCriteria('+pSaveID+')'},[
  			
  					
  					
	  				Builder.node('img',{'src':'/skins/zap/common/delete.png'})
	  				
	  				
	  				
  			]));
  			
  			$(this.syslabel+'savedcriterias_items').appendChild(node);
  			
  			$(this.syslabel+'savedcriteriascount').innerHTML = this.savedcriterias.size();
  			  			
			this.changeState(this.state.STATE_LOADED,pName);
			
			this.actualloaded = pSaveID;
			
  			
  		},
  		
  		overwriteSavedCriteria: function(pSaveID){
  			
  			var tmpcriterias = this.criterias.clone();
    			
  			var tmpsaved = this.savedcriterias.get(pSaveID);
  			  			  			
  			this.savedcriterias.set(pSaveID,[tmpsaved[0],tmpcriterias]);
  			
  			$(this.syslabel+'savedcriterias').show();  			
  			
  			this.changeState(this.state.STATE_LOADED,tmpsaved[0]);
  				
  		
  		},
  		  		
  		deleteSavedCriteria:function(pSaveID){
  			  			
  			if($(this.syslabel+'savedcriterias_item'+pSaveID)){
  			
  				$(this.syslabel+'savedcriterias_item'+pSaveID).remove();
  				
  				this.savedcriterias.unset(pSaveID);
  			
  				//this.deleteSavedCriteriaXaction(pSaveID)
  				
  				$(this.syslabel+'savedcriteriascount').innerHTML = this.savedcriterias.size();
  				
  				this.deleteSavedCriteriaXaction(pSaveID);
  			
  			}
  			
  			if(this.savedcriterias.size() == 0){
  				
  				$(this.syslabel+'savedcriteriaslist').hide();
  				  				
  			}
  			
  			if(this.actualloaded == pSaveID){
  				
  				this.changeState(this.state.STATE_MODIFIED,'');
  				
  			}
  			
  			
  			
  			
  					
  			  			
  		},
  		
  		// pSaveName = String()
  		getSavedCriterias: function(pSaveName){

  		},
  		
  		// pCriterias = Hash()
  		injectCriterias: function(pCriteriasHash){
  			
  			this.criterias = pCriteriasHash.clone();
  			
  			
  		},
  		
  		convertStringToCriterias: function(pCriteriasString){
  			
  			var tmpJSON = pCriteriasString.evalJSON();
  			
  			this.convertJSONtoCriterias(tmpJSON);
  			
  			
  		},
  		
  		// pCriterias = JSON Object()
  		convertJSONtoCriterias: function(pJSON){
  			
  			
  			var values 	= Object.values(pJSON);
	  		var keys	= Object.keys(pJSON);
	  		
	  		var tmpHash = new Hash();
	  		
	  		for(var I=0;I<keys.size();I++){
	  				  			
	  			tmpHash.set(keys[I],values[I]);
	  			
	  		}
	  		
	  		return tmpHash;
  			
  			
  		},
  	 	
	  	setCriteria: function(pCriteria,pValue){
	  			  		
	  		if(this.criterias.get(pCriteria) != "undefined"){
	  			
	  			var tmpval = this.criterias.get(pCriteria);
	  			
	  			if(tmpval != pValue){
	  			
	  				this.criterias.set(pCriteria,pValue);
	  				

	  				// Send
			  		this.sendCriterias();
			  		
			  		
			  		this.changeState(this.state.STATE_MODIFIED,'');
	  				
	  			
	  			}else{
	  				
	  				zap.log('[setCriteria] Same Value allready in Criterias');
	  				
	  			}
	  			
	  		}else{
	  			
	  			zap.log('[setCriteria] Criteria not found');
	  			// maybe create it?
	  			
	  		}
  		
	  	},
	  	
	  	
	  	setCriteriaIfNotChecked: function(pCriterias,pValue,pChecked){
	  		
	  		if(!pChecked){
	  			
	  			this.setCriteria(pCriterias,pValue);
	  			
	  		}else{
	  			
	  			zap.log('[setCriteriaIfNotChecked] Allready checked');
	  			
	  		}
	  		
	  		
	  	},
	  	
	  	checkAndSendCriteria: function(pElement,pCriteria){
	  		
	  		var element = $(pElement);

	  		// label 
	  		
	  		//critElement = this.elements.get(pCriteria);
	  		
	  		element.checked = true;
	  		
	  		this.setCriteria(pCriteria,element.value);
	  		
	  	},

	  	
	  	toogleCheckAndSendCriteria: function(pElement,pCriteria){
	  		
	  		var element = $(pElement);
	  		
	  		var state = !element.checked;
	  		
	  		element.checked = state;
	  			  		
	  		this.setCriteria(pCriteria,state);
	  		
	  	},
	  	
	  	  	
	  	getCriteria: function(pCriterias){
	  		
	  		return this.criterias.get(pCriterias);
	  		
	  	},
	  	
	  	getCriterias: function(){
	  		
	  		return this.criterias.toJSON();	  		
	  		
	  	},
	  	
	  	sendCriterias: function(){
	  		
	  		// put activelist
	  		
	  		this.criterias.set('e',this.activelist.values());
	  		
	  		var tmp = this.criterias.toJSON();
	  			  		
	  		this.criteriaChanged(tmp);
	  		
	  		this.reloadBricks('{"vcCriteria":'+tmp.toJSON()+',"page":0}');
	  		
	  		
	  	},
	  	
	  	buildSearch: function(){
	  			  		
	  	},
	  	
	  	convertToHash: function(pCriterias){
	  			  		
	  		var values 	= Object.values(pCriterias);
	  		var keys	= Object.keys(pCriterias);
	  		
	  		for(var I=0;I<keys.size();I++){
	  				  			
	  			this.criterias.set(keys[I],values[I]);
	  			
	  		}
	  		
	  	},
	  		  	
	  	criteriaChanged: function(pCriterias){
	  		// ** PLACE HOLDER : Function will be overridden ** //
	  	},
	  	
	  	// update array of criteria
	  	updateCriteriaSet: function(pCriteria,pValue){
	  			  		
	  		tmpCriteria = this.getCriteria(pCriteria);
	  		
	  		if(tmpCriteria.indexOf(pValue)>=0){
	  			
	  			//array found, remove
	  			//tmpCriteria = tmpCriteria.without(pValue);
	  			
	  			tmpCriteria.splice(tmpCriteria.indexOf(pValue),1);
	  			  			
	  			
	  		}else{ // item not found in array
	  			
	  			// add to array
	  			tmpCriteria.push(pValue);
  			
	  			
	  		}
	  		
	  		this.changeState(this.state.STATE_MODIFIED,'');
	  		
	  		this.sendCriterias();
	  		
	  	},
	  	
	  	toogleCheckAndUpdateCriteriaSet: function(pElement,pCriteria){
	  		
	  		var element = $(pElement);
	  		
	  		var state = !element.checked;
	  		
	  		element.checked = state;
	  			  		
	  		this.updateCriteriaSet(pCriteria,element.value);
	  		
	  	},
	  	

  	
  	//
  	// *****************************************
  	
  	// *****************************************
  	// REGION & RADIUS Handling
  	
  	//
  	// *****************************************
  	
  	
  	
  	// *****************************************
  	// BRICKS & FILTER Handling
  	
	  	reloadBricks: function(pCriterias){
	  		// ** PLACE HOLDER : Function will be overridden ** //
	  	},
	  	
	  	resetFilter: function(){
	  		// ** PLACE HOLDER : Function will be overridden ** //	
	  	},
	  	
	//
  	// *****************************************
  	
  	
  	// *****************************************
  	// Nodes Handling
  	
  		addStatics: function(pNodeArray){
  			
  			var tmp_nodearray = [];
  			
  			tmp_nodearray = pNodeArray;
  			  			
  			for(var i=0;i<tmp_nodearray.size();i++){
  				  				
  				this.staticlist.set(String(tmp_nodearray[i]),tmp_nodearray[i])
  				  				
  			}

  		},
  	
	  	addSource: function(pSourceID,pNodeArray){
	  			  		
	  		// Check if Source was allready loaded before	
			if(isset(this.sourcelookup.get(pSourceID))){
				
				// Yes, delete old and import new
				// delete Tags from the old source
				this.removeSource(pSourceID);
								
				// Reset Source
				tmp_nodearray = pNodeArray;
				this.sourcelist[this.sourcelookup.get(pSourceID)] = tmp_nodearray;
				
				for(var i=0;i<tmp_nodearray.size();i++){
					
					var tmp_tag = tmp_nodearray[i];
					
					
					if(this.isWaiting(tmp_tag[0])){
	  			
			  			this.drawActive(tmp_tag[0],tmp_tag[1]);
			  		
			  		}
					
					
					// Test if ID is okay
					if(IsNumeric(tmp_tag[0])){
					
						this.addTag(tmp_tag[0],tmp_tag[1],tmp_tag[2]);
					
					}
				
				}
				
						
			}else{
				
				// No, load into list
	
				tmp_nodearray = pNodeArray;
				
				this.sourcelookup.set(pSourceID,this.sourcelist.size());
				this.sourcelist[this.sourcelist.size()] = tmp_nodearray;
				
				// add Tags to waitlist
				
				for(var i=0;i<tmp_nodearray.size();i++){
					
					var tmp_tag = tmp_nodearray[i];
					
					// Test if ID is okay
					if(IsNumeric(tmp_tag[0])){
					
						this.addTag(tmp_tag[0],tmp_tag[1],tmp_tag[2]);
					
					}
				
				}
						
			}
			
			
			this.refreshWeight();
			
	  	},
	  	
	  	removeSource: function(pSourceID){

			var tmp_nodearray = [];
						
			tmp_nodearray = this.sourcelist[this.sourcelookup.get(pSourceID)];
			
			for(var i=0;i<tmp_nodearray.size(); i++){
				
				var tmp_tag = tmp_nodearray[i];
				
				this.removeTag(tmp_tag[0],tmp_tag[2]);
				
			}
			
		},
	  	
	  	addTag: function(pID,pLabel,pWeight){
	  		

		  		// Check if allready set
				if(isset(this.countlookup.get(pID))){
					
					var tmp_weight = parseInt(this.countlookup.get(pID),10);
					
					// if so, add his weight	
					this.countlookup.set(pID, parseInt(pWeight,10)+tmp_weight);
					
					
				}else{ 
					
					this.countlookup.set(pID,parseInt(pWeight,10));
					
					//draw 
					this.drawTag(pID,pLabel,pWeight);
		
				}
			  		

	  	},
	  	
	  	removeTag: function(pID,pWeight){
			
			if(isset(this.countlookup.get(pID))){
				
				
				// remove weight
				var tmp_weight = parseInt(this.countlookup.get(pID),10) - parseInt(pWeight,10);
				
				// resetTop
						
				if(tmp_weight < 1){
						
					// remove lookup table
					this.countlookup.unset(pID);
					
					// Delete element
					if($('ctag'+pID)){
						$('ctag'+pID).remove();
					}
					
					
				}else{
					
					this.countlookup.set(pID,tmp_weight);
					
				}
				
							
				return true;
				
				
			}else{
				
				this.addDebug('*ERROR* [removeTag] NO TAG');
				
				return false;
				
			}	
			
			
		},
		
		isUsable: function(pID){
			
			return !this.isActive(pID) && !this.isStatic(pID);
			
		},
		
		isWaiting: function(pID){
			
			
			if(typeof this.waitlist.get(pID) == 'undefined'){
				
				return false;
				
			}else{
				
				return true;				
				
			}
			
			
		},
	  	
	  	
	  	drawTag: function(pID,pLabel,pWeight){
	  		
	  		if(this.cloudelement != null){
	  			
	  			if(this.isUsable(pID)){
						
					/*var container = Builder.node('span',{'id':'ctag'+pID,'STYLE':'float:left;margin:2px;'});
					
					container.appendChild(Builder.node('a',{'id':'actag'+pID,'href':'/i'+pID+'/index.html','class':'filtertext','style':'line-height:20px;'},pLabel));
			
					var container_remove = Builder.node('a',{'href':'javascript:'+this.syslabel+'_filter.drawActive('+pID+',"'+pLabel+'")','class':'box_void_botton_add'})
					container_remove.innerHTML = '&nbsp;';*/
					
					var container = Builder.node('span',{'id':'ctag'+pID,'STYLE':'float:left;'});
					
					container.appendChild(Builder.node('a',{'id':'actag'+pID,'href':'javascript:'+this.syslabel+'_filter.drawActive('+pID+',"'+pLabel+'")','style':'line-height:18px;','class':'text filtertextblue'},pLabel));
					
					//&nbsp;
			  		this.cloudelement.appendChild(container);
		  		
	  			}
		  	
	  		
	  			
	  		}else{
	  			
	  			zap.log('[drawTag] No cloud Element Found!');
	  			
	  		}
	  	},
	  	
	  	
	  	resetTop: function(){
		
			//clear old top
			
			this.toplist.clear();
			
			var tmpCount 	= this.countlookup.clone();		
			//this.tophash
	
			for(var I=0;(I < this.topmax);I++){
				
				if(tmpCount.size() > 0){
								
					tmpKeys 	= tmpCount.keys();
					tmpValues 	= tmpCount.values();
								
					//get top value
					max = Math.max.apply( Math, tmpValues );
					
					if(typeof max != 'number'){
						
						
					}else{
				
						index 	= tmpValues.indexOf(max);
						
						if(index >= 0){
																					
							this.toplist.push(tmpKeys[index]);
								
							tmpCount.unset(tmpKeys[index]);
						
						}
					
					}
					
				
				}
			}
		},
		
		inTop: function(pID){
		
		
			if(this.toplist.indexOf(pID)>-1){
				
				return true;			
				
			}
			
			return false;
			
		},
		
		refreshWeight: function(){
		
			var tagids = this.countlookup.keys();
					
			// TopN Function
			this.resetTop();
			
			
			// Get Min/Max values
			for(var I=0;I < this.countlookup.size();I++){
				
				if(!this.isActive(tagids[I])){
				
					var tmp = parseInt(this.countlookup.get(tagids[I]),10);
					
					// first
					if(this.mincount == null){
						
						this.mincount = tmp;
						
					}
					
					// get Max value
					if(tmp > this.maxcount){
						
						this.maxcount = tmp;
						
					}
					
					// get Min Value
					if(tmp < this.mincount){
						
						this.mincount = tmp;
						
					}
				
				}
				
			}
			
				
			// Size Vars
			var maxsize = 18;
			var minsize = 12;
			
			var tagsize = minsize;
			
			var tag = null;
			
			//loop countlist
			for(var I=0;I < this.countlookup.size();I++){
				
				if(this.isUsable(tagids[I])){
					
					if(this.inTop(tagids[I])){
						
						$('ctag'+tagids[I]).show();
					
						if(this.maxcount != this.mincount){
							var size = Math.round((((this.countlookup.get(tagids[I])-this.mincount) * (maxsize-minsize)) / (this.maxcount-this.mincount))+minsize);
						}else{
							var size = 11;
						}
								
						$('actag'+tagids[I]).setStyle({'fontSize':size+'px'});
					
					}else{
						
						$('ctag'+tagids[I]).hide();
						
					}
				
				}
				
			}
			
			
		},
		
		
		isActive: function(pID){
		
			if(this.activelist.get(String(pID))){
				
				return true;
				
			}else{
				
				return false;
				
			}
			
		},
		
		isStatic: function(pID){
		
			if(this.staticlist.get(String(pID))){
				
				return true;
				
			}else{
				
				return false;
				
			}
			
		},
		
		
		
		setActive: function(pID){
			
			if(!this.isActive(pID)){
				
				this.addActive(pID);
				
			}
			
		},
		
		
		unsetActive: function(pID){
			
			if(this.isActive){
				
				this.activelist.unset(pID);
			
			}
			
		},
		
		addActive: function(pID){
		
			this.activelist.set(pID,pID);
	
			// Send Data
		  	this.sendCriterias();
					
		},
				
		addActiveNodes: function(pNodeArray){
			
			
			var tmp_nodearray = [];
  			
  			tmp_nodearray = pNodeArray;
  			  			
  			for(var i=0;i<tmp_nodearray.size();i++){
  				  				
  				this.activelist.set(String(tmp_nodearray[i]),tmp_nodearray[i]);
  				  				  				
  			}

		},
		
		drawActive: function(pID,pLabel){
			
			if(this.isWaiting(pID)){
		
				this.activelist.set(String(pID),pID);
				this.waitlist.unset(pID);
			
			}else{
				
				this.addActive(pID);
				this.changeState(this.state.STATE_MODIFIED,'');
			}
			
			
			//IE BUG
			if(Prototype.Browser.IE && (parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6)){
				var floatval = 'none';
			}else{
				var floatval = 'left';
			}
				
			var approved = "_approved";
			var pName = 'fitlernodes';
			var label = pLabel;
			
			if(label.length >= 25){
				
				label = label.substring(0,23) + '...';
				
			}
									
			container_cell = Builder.node('span',{'id':'fctag'+pID,'STYLE':'float:left;'});
			container_cell.appendChild(Builder.node('a', 	{'href':'javascript:'+this.syslabel+'_filter.removeActive('+pID+')','class':'filtertext','style':'font-size:13px;float:'+floatval+';'},label));
				
			this.activeelement.appendChild(container_cell);
			
			if($('ctag'+pID)){
				$('ctag'+pID).remove();
			}
			
			this.mincount = null;
			this.maxcount = 0;
						
		},
		
		removeActive: function(pID){
		
			// remove
			if($('fctag'+pID)){
				$('fctag'+pID).remove();
			}
			
			this.activelist.unset(pID);
			

			
			// Send Data
		  	this.sendCriterias();
		  	
		  	this.changeState(this.state.STATE_MODIFIED,'');
								
		},
	  		  	
  	
  	//
  	// *****************************************
  	
  	
  	addDebug: function(pLogMessage){
  		
  		zap.log(pLogMessage);
  		
  	},
  	
  	close: function(){
  		//doh!
  	},
  	
  	routeCountClick: function(pURL){
  		
  		if($(this.syslabel+'_count_wrap')){
  			
  			tmpWrap = $(this.syslabel+'_count_wrap');
  			
  			if(tmpWrap.hasClassName('active')){
  				
  				location.href = pURL;
  				
  			}
  	  		
  		}
    		
  	},
  	
  	// update count box
  	setCount: function(pCount){
  		
  		if(isset(pCount) && (pCount>0) && $(this.syslabel+'_count')){
  			
  			tmpWrap = $(this.syslabel+'_count_wrap');
  			tmpCell = $(this.syslabel+'_count');
  			
  			tmpWrap.removeClassName('inactive');
  			tmpWrap.addClassName('active');
  			tmpCell.innerHTML = pCount;

  		}else{
  			
  			tmpWrap = $(this.syslabel+'_count_wrap');
  			
  			tmpWrap.removeClassName('active');
  			tmpWrap.addClassName('inactive');
  			  			
  		}
  		
  		this.popCount();
  		
  	},
  	
  	popCount: function(){
  		
  		// get count wraper
  		if($(this.syslabel+'_count_container')){
  			
  			tmpElement = $(this.syslabel+'_count_container');
  			
  			if(!isset(this.faderColor))
  				this.faderColor = tmpElement.getStyle('backgroundColor');
  				
  				
  			if(isset(this.fadeEffect) && this.fadeEffect.state != "finished"){
  				this.fadeEffect.cancel();
  			}
  			  			
  			errorColor = '#98B426';
  			
  			// set error color
  			tmpElement.setStyle({'backgroundColor':errorColor});
  			
  			
  			this.fadeEffect = new Effect.Morph(tmpElement, {
			  	style: 'background-color:'+this.faderColor+';',
			  	duration: 1
			});

  		}
  	}
  
});







var karoussel2 = Class.create();

karoussel2.prototype = {
	
	initialize: function(pMode, pContainer ,pHash ,pIDTable ,pSelected ,pWidth ,pHeight ,pNext,pPrev,pNextIMG,pItemClass) {

		// Set values
		this.selected 	= parseInt(pSelected,10);
	    this.hash  		= pHash;
	    this.idtable	= pIDTable;
	    this.size		= this.hash.size(); 
	    this.next		= pNext; // id of next image
	    this.nextPath	= pNextIMG; // id of next image
	    this.prev		= pPrev; // id of next image
	    this.mode		= pMode;
	    this.encoder	= "obfuscate";//encode,obfuscate
	    
	    this.itemClass  = pItemClass;
	    
	    // Cookies
	    this.cookie		= "cZapKaroussel";
	    this.cookieopen	= "isOpen";
	    this.cookieclose= "isClose";
	    this.cookietime	= 10;
	    
	    // debug mode
	    this.debug		= false;
	    if(this.debug){
  			alert('Karoussel in Debug Mode!');
  		}
	    
	    this.destination = 'myKarousselTable';
	   	
	   	this.elWidth	= pWidth;
	   	this.elHeight	= pHeight;
	   	
	   	this.container  = $(pContainer);
	   	this.conWidth	= $(pContainer).getWidth();
	   	
	   	// IE6 BUG
	   	$(pContainer).setStyle({'Width':this.conWidth,'zoom':'1'});
	   	
	   	this.totWidth 	= this.elWidth * this.size;
	   	
	   	// Calculate how many elements to load
	    this.toLoad		= Math.ceil( this.conWidth / this.elWidth );
	   	   
	    // Draw the master grid
	    if(this.mode == 'ie6'){
			$('navigation_block').hide();
			$('karousselClose').hide();
			
	    }else{
	    	
	    	if(this.size > 1){
	    	
	    		this.prerender();
	    	
	    	}else{
	    		
	    		$('navigation_block').hide();
				$('karousselClose').hide();
	    		
	    	}
	    	
	    	
	    }
	    
		
		 if(!this.checkCookie()){
	    	
	    	$('navigation_block').hide();
	    	
	    }
		
		this.canrender = true;
		
		// Precaching next image
		/*Event.observe(window,'load',function(){
		
			myKaroussel.preLoadNext();
		
		});*/
		
		
		Event.observe(document,'keydown',function(event){
			
				
				if(event.keyCode == 39){ // next
						
					myKaroussel.goNext();
						
				}else if(event.keyCode == 37){ // prev
						
					myKaroussel.goPrev();
						
				}else if(event.keyCode == 40){ //scrolldown
					
					myKaroussel.goDown();
					
				}else if(event.keyCode == 38){ //scrollup
					
					myKaroussel.goUp();
					
				}
				
		});
		
			    
  	},
  	
  	decodeHTML: function(pString){
  		
  		
  		if(this.encoder == "encode"){
  			
  			return unescape(pString);
  			
  		}else if(this.encoder == "obfuscate"){
  			  			
  			return pString.replace(/<>(.*?)<\/>/g,'<$1>');
  			
  		}
  		
  	},
  	  	
  	// Prepare everything
  	// Draw table
  	prerender: function(){
  		
  		if(this.debug){
  			alert('Start prerender');
  		}
  		
  		// Start Positioning
  		if(this.selected < Math.ceil(this.toLoad / 2)){
  			// Right
  			this.position = 0;	
  			
  		}else if((this.selected) > (this.size - Math.ceil(this.toLoad / 2)-1)){
  			// Left
  			this.position = (this.size * this.elWidth)-this.conWidth;
  			
  		}else{
  			// Center Image
  			this.position = (this.selected * this.elWidth) + Math.round(this.elWidth / 2) - Math.round(this.conWidth / 2);
  		}
  		 		  		
		
  		var startpos = (0-this.position);
		
  		if(this.debug){
  			alert('Build Table');
  		}
  		
  		var table 				= Builder.node('TABLE',{'id':this.destination+'main','border':'0px','cellspacing':'0px','cellpadding':'0px','STYLE':'position:relative;left:'+startpos+'px;'});
  		var table_tbody 		= Builder.node("TBODY");
  		var	table_tr 			= Builder.node('TR',{id:this.destination});
  		var	table_tr_selecter 	= Builder.node('TR');
  		
  	  		
  		for(var I = 0; I <= (this.size-1) ;I++){
  			
  			var tmp 	= 	Builder.node('TD',{'valign':'middle','class':'karoussel_cell','STYLE':'height:'+(this.elHeight)+'px;'});
  			var tmp2 	=	Builder.node('DIV',{'id':'myKarousselValue_'+this.idtable.get(I),'STYLE':'width:'+this.elWidth+'px','class':''+this.itemClass});
  			  
  			var selection = 'karoussel_cell_empty';
  			
  			if(I == this.selected){
  				selection = 'karoussel_cell_selected';
  			}
  			
  			table_tr_selecter.appendChild(Builder.node('TD',{'class':selection}));
  			
  			tmp.appendChild(tmp2);
	    		    		    	
	    	table_tr.appendChild(tmp);
	    		    		
  		}
  		
  		table_tbody.appendChild(table_tr_selecter);
  		table_tbody.appendChild(table_tr);
  		table.appendChild(table_tbody);
  		
  		
  		this.container.appendChild(table);
  		
  		this.rendercell('center',this.toLoad);
  		
  		if(this.debug){
  			alert('Done this.prerender');
  		}
  		
  	},
  	
  	rendercell: function(pSide){
  		
  		if(this.debug){
  			alert('Start rendercell');
  		}
  		
  		if(pSide == 'left'){
  			
  			if(this.debug){
	  			alert('Render Left');
	  		}
  			
			var tmppmin = Math.max(0,(this.pmin-this.toLoad));
						
			if(tmppmin != this.pmin){
			
				for(var I = tmppmin ; I <= this.pmin ; I++){
						
					$('myKarousselValue_'+this.idtable.get(I)).innerHTML = this.decodeHTML(this.hash.get(this.idtable.get(I)));
					
	  			}
	  			
	  			this.pmin = tmppmin;
  			
			}
			
			
  					
  		}else if(pSide == 'right'){
  			
  			if(this.debug){
  				alert('Render Right');
  			}
  			
  			var tmppmax = Math.min((this.size-1),(this.pmax+this.toLoad));
  			  			
  			if(tmppmax != this.pmax){
			
			for(var I = this.pmax ; I <= tmppmax; I++){
  				
  				$('myKarousselValue_'+this.idtable.get(I)).innerHTML = this.decodeHTML(this.hash.get(this.idtable.get(I)));
  
  			}
  			
  			this.pmax = tmppmax;
  			
  			}
  			
  			
  			
  		}else{ // center
  			
  			if(this.debug){
  				alert('Render Center');
  			}
  			
  			var todo = Math.ceil(this.toLoad / 2);
  			  			
  			this.pmin = Math.max(0,Math.min((this.size-1),parseInt(this.selected) + parseInt(todo))-(2*parseInt(todo)));
  			this.pmax = Math.min((this.size-1),Math.max(0,parseInt(this.selected)-parseInt(todo))+2*parseInt(todo));
  						  					
  			for(var I = this.pmin ; I <= this.pmax ; I++){
  				
   				$('myKarousselValue_'+this.idtable.get(I)).innerHTML = this.decodeHTML(this.hash.get(this.idtable.get(I)));
  
  			}
  			
  			
  			
  		}
  		
  	},
  	

  	
  	scrollTo: function(pSide){
  		
  		if(this.debug){
  			alert('Start ScrollTo');
  		}
  		
  		if(this.mode == 'ie6'){
  			
  			if(pSide == 1){ // move to from 
  				
  				if(!empty(this.next)  && !inflagrante.enableSearch){
  			
  					location.href = this.next;
  			
			  	}
			  	
  				
  			}else{ // move to back
  				
  				if(!empty(this.prev)  && !inflagrante.enableSearch){
			  			
			  			location.href = this.prev;
			  			
			  		}
  	
  			}
  			
  			
  		}else{
  		
	  		if(this.canrender){
	  		
		  		tmppos = this.position; //positive value of position
		  		
		  		var move = null;
		  		
		  		this.render();
		  		
		  		if(pSide == 1){ // move to from 
		  			
		  			this.rendercell('right');
		  			
		  			if((this.totWidth - tmppos - this.conWidth) > this.conWidth){
		
		  				move = (0-(this.conWidth));
		
		  			}else{
		  				
		  				if((this.totWidth - tmppos - this.conWidth) > 0){
		  					move = (0-(this.totWidth - tmppos - this.conWidth));
		  				}
				
		  			}
		  			
		  			this.position = this.position + (0 - move);
		  			
		  		}else{ // move to back
		  			  			
		  			this.rendercell('left')	;
		  			
		  			if(tmppos > 0){
		  				
		  				if(tmppos < this.conWidth){
		  					
		  					move = tmppos;
		  					
		  				}else{
		 
		  					move = this.conWidth;
		  				}
		  				
		  			}
		  			
		  			this.position = this.position - move;
		  			
		  		}
		  		
		  		if(move != null){
			  		new Effect.Move(this.destination+'main', {
					   	x: move, 
					   transition: Effect.Transitions.sinoidal,
					   afterFinish: function(){
					   	
					   	//this.render();
					   	this.render();
					   	
					   }.bind(this)
					});
		  		}else{
		  			this.render();
		  		}
	  		
	  		}  
  		}	

  	},
  	
  	showTable: function(){
  		alert(this.idtable.inspect());
  	},
  	
  	getpos: function(){
  		return 'Pos:'+this.position+' totWidth:'+this.totWidth+' conWidth:'+this.conWidth+' toLoad:'+this.toLoad+' selected:'+this.selected+' size:'+this.size;
  	},
  	
  	getlast: function(){
  		
  		return 'Lastleft:'+this.pmin+'Lastright:'+this.pmax;
  	},
  	
  	render:function(){
  		
  		this.canrender = ! this.canrender;
  		
  		return this.canrender;
  	},
  	
  	goNext: function(){
  		  		
  		if(!empty(this.next) && !inflagrante.enableSearch && myKaroussel.checkFocus()){
  			
  			location.href = this.next;
  			
  		}
  	},
  	
  	goPrev: function(){
  		  		
  		if(!empty(this.prev) && !inflagrante.enableSearch && myKaroussel.checkFocus()){
  			
  			location.href = this.prev;
  			
  		}
  		
  	},
  	
  	goDown: function(){
  		
  		if(inflagrante.started && !inflagrante.enableSearch && myKaroussel.checkFocus()){
  			
  			$(inflagrante.imgElement).scrollTo();
  			
  		}
  		
  	},
  	
  	goUp: function(){
  		  		
  		if(inflagrante.started && !inflagrante.enableSearch && myKaroussel.checkFocus()){
  			
  			$('pagetopcontainer').scrollTo();
  			
  		}
  		
  	},
  	
  	toggleBar: function(){
  		
  		if((this.mode != 'ie6') && (this.size > 1)){
  		
	  		if(this.checkCookie()){
	  			
	  			this.toggleCookie();
	  			$('navigation_block').hide();
	  			
	  		}else{
	  			
	  			this.toggleCookie();
	  			$('navigation_block').show();
	  			
	  		}
  		
  		}

 
  		// Effect.toggle('navigation_block', 'slide', { delay: 0.5 });

  	},
  	
  	preLoadNext: function(){
  		
  		if(!empty(this.nextPath)){
  			
  			var img = document.createElement('IMG');
       		img.src = this.nextPath;
  			
  		}
  		
  	},
  	
  	checkCookie: function(){
  		
  		var nameEQ = this.cookie + "=";
  		var allCookies = document.cookie.split(';');
  		
  		for(var i=0;i < allCookies.length;i++) {
  			
  			var c = allCookies[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(this.cookie) == 0){
				
				if(c.substring(nameEQ.length,c.length) == this.cookieopen){
					return true;
				}else{
					return false;
				}
				
			}
			
  		}
  		
  		return true;
  		
  		
  	},
  	
  	toggleCookie: function(){
  		
  		var isSet 	= false;
  		var status 	= true;
  		// check 
  		
  		var nameEQ = this.cookie + "=";
  		var allCookies = document.cookie.split(';');
  		
  		for(var i=0;i < allCookies.length;i++) {
  			
  			var c = allCookies[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(this.cookie) == 0){

				// Get Cookie Stauts
				status = c.substring(nameEQ.length,c.length);
				isSet = true;
				
			}
			
  		}
  		
  		// check if we found it
  		if(!isSet){

  			// if not then create it
  			var date = new Date();
			date.setTime(date.getTime()+(this.cookietime*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
			document.cookie = this.cookie+"="+this.cookieopen+expires+"; path=/";
			
			// not set before, but set now!
			return false;


  		}else{
  			
  			// if found check status and reverse
  			if(status == this.cookieopen){
  				
  				var date = new Date();
				date.setTime(date.getTime()+(this.cookietime*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
				document.cookie = this.cookie+"="+this.cookieclose+expires+"; path=/";
  				
				return true;
  				
  				
  			}else if(status == this.cookieclose){
  				
  				var date = new Date();
				date.setTime(date.getTime()+(this.cookietime*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
				document.cookie = this.cookie+"="+this.cookieopen+expires+"; path=/";
				
				return false;
  				
  			}
  			
  		}

  		
  	},
  	
  	checkFocus: function(){
  		
		// initialize function global reference to document
		// element that currently h(as)f(ocus)
		var hf;
		// IE uses activeElement
		if ( document.activeElement ) hf = document.activeElement;
		// Firefox uses focusNode
		else hf = document.focusNode;
		
		if(hf == window.document.body){
			return true;
		}else{
			return false;
		}
  		
  	},
  	
  	sortTable: function(){
  		
  		var testtable = new Hash();
  		
  		this.hash.each(function(element){
  			
  			zap.log('ID' + element.key)
  			
  			testtable.set(String(element.key),element.key);
  			
  		}.bind(this));
  		
  		zap.log('Size:'+testtable.size());
  		zap.log('------------------------------');
  		zap.log(testtable.inspect());
  		
  	},
  	
  	
  	
  	benchmarkStrReplace: function(){
  		
  		tmpString = '<div class=\"media_audio_mix_listingsmall_wrap\"><div class=\"media_audio_mix_listingsmall_img iv_instance_image\"><a href=\"/i2961935/index.html?vc=9.vcAudioMixesSearch.77cc815a721dc49f95ff29fc3b488a2f\"><IMG SRC=\"/skins/zap/klasses/artist/dj/nopinano.png\"ALT=\"\"></a></div><div class=\"media_audio_mix_listingsmall_content\"><div class=\"media_audio_mix_listingsmall_title\"><a class=\"text media_audio_mix_listingsmall_title\" href=\"/i2961935/index.html?vc=9.vcAudioMixesSearch.77cc815a721dc49f95ff29fc3b488a2f\">dfvsdvsfdvsfd</a></div><div class=\"media_audio_mix_listingsmall_dj\"><span class=\"title_small_grey\">vum <a class=\"text\" href=\"/i2961904/index.html\">sdcdsacsac</a></span></div></div><a href=\"javascript:musicplayer.open(\'/i2961935/player/index.html?vc=9.vcAudioMixesSearch.77cc815a721dc49f95ff29fc3b488a2f\')\" class=\"media_audio_mix_listing_play\"><img src=\"/skins/zap/common/pixel.gif\" height=\"24px\" width=\"24px\"></a></div>';
  		tmpStringOut = '';
  		times = 200;
  		
  		start = new Date();
  		
  		for(var I = 0;I<times;I++){
  			
  			
  			 tmpStringOut = tmpString.replace(/<(.*?)>/g,'%$1#');
   			
  		}
  		
  		
  		
  		stop = new Date();
  		
  		zap.log('Time:'+(stop.getTime()-start.getTime())+'ms');
	
  	},
  	
  	benchmarkBase64: function(){
  		
  		
  		tmpString = 'PGRpdiBjbGFzcz0ibWVkaWFfYXVkaW9fbWl4X2xpc3RpbmdzbWFsbF93cmFwIj48ZGl2IGNsYXNzPSJtZWRpYV9hdWRpb19taXhfbGlzdGluZ3NtYWxsX2ltZyBpdl9pbnN0YW5jZV9pbWFnZSI+PGEgaHJlZj0iL2kzMDcwMTIzL2luZGV4Lmh0bWw/dmM9MTEuMjk2MTQ0MC41ODk2ZTg5M2EyYzUxMGI4YjUwODEzN2QxODFjMzkxZiI+PGltZyBjbGFzcz0iIiBzcmM9Ii9zdG9yYWdlLzg4UWNuLmpwZyIgIGFsdD0iIj48L2E+PC9kaXY+PGRpdiBjbGFzcz0ibWVkaWFfYXVkaW9fbWl4X2xpc3RpbmdzbWFsbF9jb250ZW50Ij48ZGl2IGNsYXNzPSJtZWRpYV9hdWRpb19taXhfbGlzdGluZ3NtYWxsX3RpdGxlIj48YSBjbGFzcz0idGV4dCBtZWRpYV9hdWRpb19taXhfbGlzdGluZ3NtYWxsX3RpdGxlIiBocmVmPSIvaTMwNzAxMjMvaW5kZXguaHRtbD92Yz0xMS4yOTYxNDQwLjU4OTZlODkzYTJjNTEwYjhiNTA4MTM3ZDE4MWMzOTFmIj5xcXF3d3dlZWU8L2E+PC9kaXY+PGRpdiBjbGFzcz0ibWVkaWFfYXVkaW9fbWl4X2xpc3RpbmdzbWFsbF9kaiI+PHNwYW4gY2xhc3M9InRpdGxlX3NtYWxsX2dyZXkiPnZ1bSA8YSBjbGFzcz0idGV4dCIgaHJlZj0iL2kyOTQ1MjcwL2luZGV4Lmh0bWwiPkFydGlzdC5ESjwvYT48L3NwYW4+PC9kaXY+PC9kaXY+PGEgaHJlZj0iamF2YXNjcmlwdDptdXNpY3BsYXllci5vcGVuKCcvaTMwNzAxMjMvcGxheWVyL2luZGV4Lmh0bWw/dmM9MTEuMjk2MTQ0MC41ODk2ZTg5M2EyYzUxMGI4YjUwODEzN2QxODFjMzkxZicpIiBjbGFzcz0ibWVkaWFfYXVkaW9fbWl4X2xpc3RpbmdfcGxheSI+PGltZyBzcmM9Ii9za2lucy96YXAvY29tbW9uL3BpeGVsLmdpZiIgaGVpZ2h0PSIyNHB4IiB3aWR0aD0iMjRweCI+PC9hPjwvZGl2Pg==';
  		tmpStringOut = '';
  		times = 200;
  		
  		start = new Date();
  		
  		for(var I = 0;I<times;I++){
  			
  			
  			 tmpStringOut = Base64.decode(tmpString);
   			
  		}
  		
  		
  		
  		stop = new Date();
  		
  		zap.log('Time:'+(stop.getTime()-start.getTime())+'ms');
  		
  	}
	
}




					
					var inflagrante = {
								
								/**
								 * Holds the current Cropper.Img object
								 * @var obj
								 */
								curCrop			: null,
								started			: false,
								imgElement		: null,
								divElement		: null,
								divSeeker		: null,
								divSeekerInner	: null,
								divWraper		: null,
								tagHelp			: null,
								tagButton		: null,
								tagButtonEffect	: null,
								isUser			: false,
								isAnoLink		: '',
								enableSearch	: false,
								canDraw			: false,
								lastID			: 1,
								tagTable		: new Array(),
								tagLookup		: new Hash(),
								
								// new Inflagrante
								selectedId		: null,
								selectedLabel	: null,
								
																
								
								/**
								 * Initialises the cropImageManager
								 *
								 * @access public
								 * @return void
								 */
								init: function(pImage,pAddURL,pDelURL,pApplID,pOwnerID,pUserID) {
										
										this.started			= 	true;							
										
										this.addURL				=  	pAddURL;
										this.delURL				=   pDelURL;
										
										this.selectorloaded		= 	false;
										
										this.applID				=   pApplID; // id of the application
										this.ownerID			=   pOwnerID; // Ultimateowner of the Image
										this.userID				=   pUserID; // actual User ID (session)
										
										this.imgElement 		= 	pImage;	
										this.selectPos 			= 	new Hash();
										this.selectDims			= 	new Hash();
										this.afterSelectBind	=	this.afterSelect.bind(this);
										this.beforeSelectBind	=	this.beforeSelect.bind(this);
										this.drawListBind		= 	this.drawList.bind(this);
										
										// Create Search Gif
										// this.divElement = Builder.node('DIV',{id:'inflagrante_search',style:'position:absolute;display:none;','class':'tools_inflagrante'},'Loading ...');
										
										
										//$('pagetopcontainer').appendChild(this.divElement);
										//$('wpContent').innerHTML = '';
										
																			
										// Renew Image size
										this.height 			=	$(this.imgElement).offsetHeight;
										this.width 				= 	$(this.imgElement).offsetWidth;
										
										Event.observe(window,'load',this.drawListBind);
										
								},
								
								/**
								 * Handles the changing of the select to change the image, the option value
								 * is a pipe seperated list of imgSrc|width|height
								 * 
								 * @access public
								 * @param obj event
								 * @return void
								 */
								onChange: function( e ) {
									var vals = $F( Event.element( e ) ).split('|');
									this.setImage( vals[0], vals[1], vals[2] ); 
								},
								
								/**
								 * Sets the image within the element & attaches/resets the image cropper
								 *
								 * @access private
								 * @param string Source path of new image
								 * @param int Width of new image in pixels
								 * @param int Height of new image in pixels
								 * @return void
								 */
								setImage: function( imgSrc, w, h ) {
									$( 'testImage' ).src = imgSrc;
									$( 'testImage' ).width = w;
									$( 'testImage' ).height = h;
									this.attachCropper();
								},
								
								/** 
								 * Attaches/resets the image cropper
								 *
								 * @access private
								 * @return void
								 */
								attachCropper: function() {
									
										if( this.curCrop === null ){
											
											if(this.selectorloaded == false){
												
												// Load Search page into Div
												eval(this.addURL);
												
											}
											
											this.enableSearch = true;

											
											this.hideTagButton();
																	
											this.curCrop = new Cropper.Img( this.imgElement, { 
												minWidth: 80, 
												minHeight: 80,
												displayOnInit: false,
												onEndCrop: this.afterSelectBind,
												onStartCrop: this.beforeSelectBind,
												captureKeys: false
											});
											
											this.showTagHelp();
											
											
										}else{
											
											this.enableSearch = true;
											this.curCrop.reset();
											//$('loading').hide();
											//$('goload').show();
											
											this.showTagHelp();
											
										}
										
										//this.showNames();
				
								},
								
								/**
								 * Removes the cropper
								 *
								 * @access public
								 * @return void
								 */
								removeCropper: function() {
									if( this.curCrop !== null ) {
										this.curCrop.remove();
										this.curCrop = null;
										this.canDraw = false;
										this.enableSearch = false;
											
									}
								},
								
								/**
								 * Resets the cropper, either re-setting or re-applying
								 *
								 * @access public
								 * @return void
								 */
								resetCropper: function() {
									//this.curCrop.reset();
									this.divElement.hide();
									
									this.canDraw = false;
									this.attachCropper();
									
								},
								
								/**
								* Called function on Selection End
								*/
								afterSelect: function(coords, dimensions){
																		
									this.selectPos.set('x1',coords.x1);
									this.selectPos.set('y1',coords.y1);
									this.selectPos.set('x2',coords.x2);
									this.selectPos.set('y2',coords.y2);
									
									this.selectDims.set('width',dimensions.width);
									this.selectDims.set('height',dimensions.height);
									
									
									if(this.canDraw){
																				
										if(!this.divElement.visible()){

												this.divElement.show();
												/*if($('inputinflagrante')){
													$('inputinflagrante').focus();
												}*/

										}
										
										
										this.divElement.clonePosition('imgCrop_id_clickArea',{setWidth:false,setHeight:false,offsetLeft:dimensions.width+10});
										
									}

								},
								
								
								beforeSelect: function(){
																		
									this.hideTagHelp();
									
									this.canDraw = true;
																																	
									if(this.enableSearch){
										
										this.divElement.hide();
									}
									
								},
																
								stopAll: function(){
					
									
									this.divElement.hide();
									this.removeCropper();
									this.canDraw = false;
									
									this.hideNames();
									
								},
								
								getPos: function(){
									this.height 			=	$(this.imgElement).offsetHeight;
									this.width 				= 	$(this.imgElement).offsetWidth;
									
									return this.calculateNewPos(this.selectPos.get('x1'),this.selectPos.get('y1'),this.selectPos.get('x2'),this.selectPos.get('y2'),this.width,this.height);
								},
								
								populateDrawList: function(pID,pPosition,pName,pType){
									
												
									var tmpindex = this.tagTable.size();
																		
									this.tagTable[tmpindex] = new Array(pID,pName,pPosition,pType);
									this.tagLookup.set(pID,tmpindex);
									
									return tmpindex;
									
								},
								
								prepareWraper: function(){
									
									
									// Cache insertion point, just above the Image (in DOM level)
									var insertPoint = $(this.imgElement).parentNode;
									
									// Creating the main container DIV
									this.imgWrap = Builder.node( 'div', {'id':'inflagrante_drawlist_wraper','class': 'tools_inflagrante_drawlist_wraper','STYLE':'position:relative;' });
									
									// Creating the Cells Container
									this.divWraper = Builder.node( 'div', {'id':'inflagrante_drawlist_container'});
									this.imgWrap.appendChild(this.divWraper);
									
									// Move the image to an other location
									var tmp		 = Builder.node( 'div');
									tmp.appendChild($(this.imgElement));
									
									this.imgWrap.appendChild(tmp);
									
									// Write and done!
									insertPoint.appendChild(this.imgWrap);
									
									// Create Search Gif
									this.divElement = Builder.node('div',{'id':'inflagrante_search','style':'position:absolute;display:none;','class':'tools_inflagrante'});
									this.divElement.appendChild(Builder.node('div',{'id':'inflagrante_search_inner','class':'tools_inflagrante_inner'},'Loading ...'));

									
									$('pagetopcontainer').appendChild(this.divElement);
																			
									//Event.observe('inflagrante_drawlist_wraper','mouseover',this.showNames);
									//Event.observe('inflagrante_drawlist_wraper','mouseout',this.hideNames);
									
								},								
								
								/**
								* Draw Wraper for the Tagging Cells
								*/
								
								drawList: function(){
									
									if(this.divWraper === null){
										this.prepareWraper();
									}
																		
									// clear content
									this.divWraper.innerHTML = '';
									
									// Create Seeker and attach
									this.divSeeker 		= 	Builder.node('DIV',{'id':'inflagrante_seeker','style':'display:none;position:absolute;','class':'tools_inflagrante_drawlist_cell'});
									this.divSeekerInner = 	Builder.node('DIV',{'id':'inflagrante_seeker_inner','class':'tools_inflagrante_drawlist_cell_inner'});
									this.divSeeker.appendChild(this.divSeekerInner);					
											
									this.divWraper.appendChild(this.divSeeker);
									
									// Renew Image size
									this.height 			=	$(this.imgElement).offsetHeight;
									this.width 				= 	$(this.imgElement).offsetWidth;
									
									var pos = 0; // set position to zero
									
																		
									for(var I = 0;I < this.tagTable.size();I++){
										
										// Border bug?
										border = 4;
										
										tmparray 	= this.tagTable[I];

																					
										id			= tmparray[0];
										if(tmparray[3] == 'user'){
											linkID		= tmparray[0];
										}else{
											linkID		= '';
										}
										
										name 		= tmparray[1];
										pos 		= tmparray[2].split(';');
																				
										
										
										// calculte
										if(this.width > 0){
											X1 = Math.round(( this.width * pos[0] ) / 100);
											X2 = Math.round(( this.width * pos[2] ) / 100);
										}else{
											X1 = 0;
											X2 = 0;
										}
										
										if(this.height > 0){
											Y1 = Math.round(( this.height * pos[1] ) / 100);
											Y2 = Math.round(( this.height * pos[3] ) / 100);
										}else{
											Y1 = 0;
											Y2 = 0;
										}
										
										tmpwidth 	= (X2 - X1);
										tmpheight	= (Y2 - Y1);
										
										var tmpcell 	= 	Builder.node('DIV',{'id':'inflagrante_cell_'+id,'style':'position:absolute;display:inline;top:'+(Y1+border)+'px;left:'+(X1+border)+'px;height:'+(tmpheight-(border*2))+'px;width:'+(tmpwidth-(border*2))+'px;','onmouseout':'inflagrante.seekID('+id+',"off")','onmouseover':'inflagrante.seekID('+id+',"on")'});
										
										if(Prototype.Browser.IE){
											tmpcell.appendChild(Builder.node('IMG',{'SRC':'/skins/zap/common/pixel.gif','height':(tmpheight-(border*2))+'px','width':(tmpwidth-(border*2))+'px'}));								
										}
												
										
										var tmpcellname = 	Builder.node('div',{'id':'cell_name_'+id,'style':'position:absolute;display:none;z-index:8888;','class':'tools_inflagrante_drawlist_cell_title',onclick:'inflagrante.linkToId('+linkID+')','onmouseout':'inflagrante.seekID('+id+',"off")','onmouseover':'inflagrante.seekID('+id+',"on")'},[
															Builder.node('DIV',{'class':'tools_inflagrante_drawlist_cell_title_right'},[
															Builder.node('DIV',{'class':'tools_inflagrante_drawlist_cell_title_name'},name)
															])]);
															

										this.divWraper.appendChild(tmpcell);
										
										this.divWraper.appendChild(tmpcellname);
										
										tmpcellname.setStyle({'top':(Math.min(this.height,(Y2+4+tmpcellname.getHeight()))-tmpcellname.getHeight())+'px','right':(this.width - (Math.max(0,(X2 - tmpcellname.getWidth())) + tmpcellname.getWidth()))+'px'});

									
										
													
									}
									
									// testing
									this.drawTagButton();
									
									return true;
																											
								},
								
								showNames: function(){
									
									f= $$('.tools_inflagrante_drawlist_cell_title');
									for(var i=0; i<f.length; i++){
										f[i].show();
									}

									
								},
								
								hideNames: function(){
									
									f= $$('.tools_inflagrante_drawlist_cell_title');
									for(var i=0; i<f.length; i++){
										f[i].hide();
									}
									
								},
								
															
								// calculte procentual position in image
								calculateNewPos: function(pX1,pY1,pX2,pY2,pWidth,pHeight){
																		
									var x1 = 0;
									var y1 = 0;
									var x2 = 0;
									var y2 = 0;
									
									x1 = Math.round(((100 * pX1) /  pWidth)*1000)/1000;
									y1 = Math.round(((100 * pY1) /  pHeight)*1000)/1000;
									x2 = Math.round(((100 * pX2) /  pWidth)*1000)/1000;
									y2 = Math.round(((100 * pY2) /  pHeight)*1000)/1000;

									return x1+';'+y1+';'+x2+';'+y2;
									
								},
								
								
								linkToId: function(pID){
																	
									if(!empty(pID)){

										url = '/i'+pID+'/index.html';
										window.location.href = url;
										
									}
									
								},
								
								
								seekID:function(pID,pType){
									
									if(!empty(pID)){
										
										if($('cell_name_'+pID) && $('inflagrante_cell_'+pID) && !(this.enableSearch)){
										
											if(pType == 'on'){
												
												
													$('inflagrante_cell_'+pID).setStyle({'z-index':'9999'});
													$('cell_name_'+pID).setStyle({'z-index':'9999'});
													
													$('cell_name_'+pID).show();
			
													
													this.divSeeker.show();
													
													this.divSeeker.clonePosition($('inflagrante_cell_'+pID),{setWidth:false,setHeight:false,offsetLeft:-4,offsetTop:-4});
													this.divSeekerInner.clonePosition($('inflagrante_cell_'+pID),{setLeft:false,setTop:false});
																										
													
													
											}else{
												
													$('inflagrante_cell_'+pID).setStyle({'z-index':'auto'});
													$('cell_name_'+pID).setStyle({'z-index':'auto'});
													
													$('cell_name_'+pID).hide();
																										
													
													this.divSeeker.hide();

													
													
											}
											
										}
										
									}
									
								},
								
								addToList: function(pTableKey){
									
									if(pTableKey !== ""){
										
										tmparray = this.tagTable[pTableKey];

										var container 	= Builder.node('SPAN',{'id':'inflagrante_list_'+tmparray[0]+'','onmouseout':'inflagrante.seekID('+tmparray[0]+',\'off\')','onmouseover':'inflagrante.seekID('+tmparray[0]+',\'on\')'});

											tmpDOM = Builder.node('SPAN');
											

											if(pTableKey > 0){
												tmpDOM.appendChild(Builder.node('SPAN',', '));
											}
											
											if(tmparray[3] == 'user'){
												//tmpDOM.appendChild(Builder.node('A',{'href':'','class':'text'},tmparray[1]));
												tmpDOM.appendChild(Builder.node('A',{'href':'/i'+tmparray[0]+'/index.html','class':'text'},tmparray[1]));
											}else{
												tmpDOM.appendChild(Builder.node('SPAN',tmparray[1]));
											}
											
	
											if((this.userID == this.ownerID) || (tmparray[0] == this.userID)){

												tmpDOM.appendChild(	
														Builder.node('A',{'href':'javascript:inflagrante.removeUser('+tmparray[0]+')'},[
														Builder.node('IMG',{'SRC':'/skins/zap/common/delete.png','style':'margin-left:3px;margin-right:3px;'})
												]));
											}
											
											container.appendChild(tmpDOM);
											
										
										$('inflagrante_list').appendChild(container);
										
										if($('inflagrante_null')){
											
											$('inflagrante_null').remove();
											
										}

									
									}
									
									
								},
								
								removeUser: function(pID){
									
									if((this.userID == this.ownerID) || (pID == this.userID)){
										
										//if(this.tagTable[this.tagLookup.get(pID)][3] == 'user'){
											
											xAction(this.delURL,this.applID,this.tagTable[this.tagLookup.get(pID)][0]);
											
										//}else{
											
										//}
									
									}else{
										
										alert('No access!');
										
									}
									
								},
								
								// callback methode for Ajax
								callRemoveUser: function(pID){
									
									$('inflagrante_list_'+pID).remove();
									$('inflagrante_cell_'+pID).remove();
									$('cell_name_'+pID).remove();
									
									this.divSeeker.hide();
									
									this.tagTable.splice(this.tagLookup.get(pID),1);

								},
								
								// callback methode for Ajax
								callAddUser: function(pID,pName,pPosition,pType){
																											
									var test = this.populateDrawList(pID,pPosition,pName,pType);
																		
									this.addToList(test);
									
									//$('inputinflagrante').value = '';
									//$('inputtest').value = '';
									//$('inputtest2').value = '';
									
								
									//this.resetCropper();
																	
									// reset ghost inputs
									$('ghost_name').value= '';
									$('ghost_mail').value= '';
									
									// reset loading
									$('loading').hide();
									$('loading_selection').hide();
									$('goload').show();
									$('goload_selection').show();
									
									
									// reset multighost
									$('inflagrante_multighost').hide();

									this.drawList();
									
									this.unshowSelected();
																		
									this.hideTagButton();
																		
									this.stopAll();
									
								},
								
								showUnknown: function(){
									
									
								},
								
								drawTagButton: function(){
									
									
									msgText = "Recognised somebody?";
									
																		
									
									if(this.isUser == true)
										link = 'inflagrante.attachCropper()';
									else
										link = this.isAnoLink;
									
									
									// container div
									container = $(this.imgElement+'_wrap');
									
									this.tagButton = Builder.node('div',{'class':'application_inflagrante_tagButton_wrap','style':'position:absolute;top:15px;left:15px;','onclick':link},[
													Builder.node('div',{'class':'application_inflagrante_tagButton_innerwrap'},[
													Builder.node('div',{'class':'application_inflagrante_tagButton_content'},msgText)])]);
									
									//this.tagButton = Builder.node('div',{'style':''});
									
									container.appendChild(this.tagButton);
									
									
									this.showTimesTagButton();
									
									// add Event
									Event.observe(document,'mousemove',this.showTimesTagButton.bind(this));
									//Event.observe('window','mouseout',this.fadeTagButton.bind(this));
									
								},
								
								showTagHelp: function(){
									
									// MSG 300x200
									msgHeight = 50;
									
									
									
										msgText = "Click on the photo to tag your friends and acquaintances.";
										icon = "/skins/zap/common/inflagrante.png";
									
									
								
									targetElement = $('imgCrop_id_dragArea');
									
									dimensions = targetElement.getDimensions();
									
									posX = 10;

									posY = 10;
									
									msgWidth  = dimensions.width - 20;
									
									container = Builder.node('div',{'class':'application_inflagrante_tagHelp_container','style':'position:absolute;top:'+posY+'px;left:'+posX+'px;height:'+msgHeight+'px;width:'+370+'px;'});
									
									// Top Elements
									container.appendChild(
										Builder.node('div',{'class':'application_inflagrante_tagHelp_top_left'},[
										Builder.node('div',{'class':'application_inflagrante_tagHelp_top_right'},[
										Builder.node('div',{'class':'application_inflagrante_tagHelp_top_center'}
									)])]));
									
									// Center Elements
									container.appendChild(
										Builder.node('div',{'class':'application_inflagrante_tagHelp_center_left'},[
										Builder.node('div',{'class':'application_inflagrante_tagHelp_center_right'},[
										Builder.node('div',{'class':'application_inflagrante_tagHelp_center_center'},msgText
									)])]));
									
									// Bottom Elements
									container.appendChild(
										Builder.node('div',{'class':'application_inflagrante_tagHelp_bottom_left'},[
										Builder.node('div',{'class':'application_inflagrante_tagHelp_bottom_right'},[
										Builder.node('div',{'class':'application_inflagrante_tagHelp_bottom_center'}
									)])]));
									
									
									this.tagHelp = container;
									
									//this.tagHelp.setOpacity(0.5);
									
									targetElement.appendChild(this.tagHelp);
									
								},
								
								hideTagHelp: function(){
									
									this.tagHelp.hide();
									
								},
																
								
								showTagButton: function(event){
								
									this.tagButton.show();

								},
								
								hideTagButton: function(event){
									
									this.tagButton.hide();
								},
								
								showTimesTagButton: function(event){
									
									if(!this.enableSearch){
									
										if(this.tagButtonEffect != null){
											
											this.tagButtonEffect.cancel();
											this.tagButtonEffect == null;
											this.tagButton.setOpacity(1);
											this.tagButton.show();
											
										}
										
										this.tagButtonEffect = Effect.Fade(this.tagButton,{duration: 1.0,delay:1});
									
									}
								}
								
							};
							
			
			var smallInflagrante = Class.create({
				
				borderfix	: 4,
				element 	: null,
				img 	: null,
				position 	: null,
								
				initialize: function(pElement,pCords){
										
					this.element = $(pElement);
					
					var tmp = this.element.select('img');
					
					this.img = tmp[0];
					
					this.position = pCords;
					
					// Event 							
					Event.observe(window, 'load', this.draw.bind(this));
		
				},
				
				
				// draw image
				draw: function(){
					
					// calculate position
					var cords = this.position.split(';');
					
					// get div dimenstion
					var dims = this.img.getDimensions();
									
					// parseInt(,10)
					var x1,y1,x2,x2 = 0;
					
					x1 = Math.round(	(dims.width-(this.borderfix*2)) 	* (parseFloat(cords[0]) / 100));
					y1 = Math.round(	(dims.height-(this.borderfix*2)) * (parseFloat(cords[1]) / 100));
					x2 = Math.round(	(dims.width-(this.borderfix*2)) 	* (parseFloat(cords[2]) / 100));
					y2 = Math.round(	(dims.height-(this.borderfix*2))	* (parseFloat(cords[3]) / 100));
					
					this.element.appendChild(
					
					Builder.node('div',{'style':'position:absolute;top:'+(y1+this.borderfix)+'px;left:'+(x1+this.borderfix)+'px;height:'+(y2-y1)+'px;width:'+(x2-x1)+'px;','class':'tools_inflagrantesmall_cell'},[
						Builder.node('div',{'style':'height:'+((y2-y1)-2)+'px;width:'+((x2-x1)-2)+'px;','class':'tools_inflagrantesmall_cell_inner'})
					]));

				}
				
			});
			





var zaptipslist = [];

function zaptipssearch(){
		
	zaptipslist.each(function(zaptipsobject){
			
		// clear the element
		zaptipsobject.container.remove();
			
	});
		
	// clear list
	zaptipslist.clear();
	
	$$('a[rel].layoutbuttontip').each(function(element) {
		zaptipslist.push(new zaptips(element, element.rel,'',false));
	});
				
	$$('a[rel].shortviewstatus').each(function(element) {
		zaptipslist.push(new zaptips(element, element.rel,'status',false));
	});
	
	$$('a[rel].layoutbuttonboxes').each(function(element) {
		zaptipslist.push(new zaptips(element, element.rel,'closeButtons',false));
	});
	
}

fixIEzaptips = function (){
	
	zaptipslist.each(function(zaptipsobject){
			
		zaptipsobject.fixIE();
		
	});
	
}

var zaptips = Class.create({
	
	version 	: '0.0.1',
	element 	: null,
	tiptext 	: '',
	container	: null,
	defaultStyle: 'orange_simple',
	chosenStyle : null,
	effect		: null,
	nomouse		: false,
	options		: new Hash,
		
	// Styles declaration 
	styles		: {
		
		'orange':{
			
			snap		: 'bottom',
			left		: 0,
			top  		: 5,
			className	: '',
			align		: 'left',
			tic			: false
			
		},
		
		'orange2':{
			
			snap		: 'top',
			left		: 0,
			top  		: -5,
			className	: 'orange_simple',
			align		: 'right',
			tic			: false
			
		},
		
		'orange_simple':{
			
			snap		: 'bottom',
			left		: 0,
			top  		: 0,
			className	: '',
			align		: 'left',
			tic			: true
			
		},
		
		'status':{
			
			snap		: 'right',
			left		: 5,
			top  		: 0,
			align		: 'left',
			tic			: false
			
		},
		
		'tabsTopLeft':{
			
			snap		: 'top',
			left		: 10,
			top  		: -10,
			className	: 'orange_simple',
			align		: 'left',
			tic			: true
			
		},
		
		'tabsTopRight':{
			
			snap		: 'top',
			left		: -10,
			top  		: -10,
			className	: 'orange_simple',
			align		: 'right',
			tic			: true
			
		},
		
		'tabsLogin':{
			
			snap		: 'top',
			left		: -90,
			top  		: -10,
			className	: 'orange_simple',
			align		: 'right',
			tic			: true
			
		},
		
		'closeButtons':{
			
			snap		: 'top',
			left		: 0,
			top  		: -15,
			className	: 'orange_simple',
			align		: 'left',
			tic			: true

		}
	},
	
	// ---
	
 	initialize: function(pElement,pText,pStyle,pNoMouse) {
 		
 		// pOptions  - placeholder
 		
 		this.element 		= 	$(pElement);
 		this.tiptext 		= 	pText;
 		this.nomouse 		= pNoMouse;
		 	 		
 		this.drawTip(pStyle);
 		
 		
	},
	
	showTip: function(){
			
		//this.container.show();
		//this.container.appear({ duration: 0.2 });
		
		this.sync();
		
		this.effect = new Effect.Appear(this.container, { 
		  duration: 0.2
		});

		
	},
	
	hideTip: function(){
		
		// bug fix
		if(this.effect != null){
			this.effect.cancel();
		}
		
		this.container.hide();
		
	},
	
	
	drawTip: function (pStyle){
		
				
		// help Vars
		
		var offset 		= { left:0, top:0};
		var dimensions	= this.element.getDimensions();
				
		// Create Elementwrap
		
 		this.container = Builder.node('div',{'class':'tools_zaptips','style':'z-index:1999;'});
 		
 		
 		
 		
		// Check for style
		if(this.styles[pStyle]){
			
			this.chosenStyle = this.styles[pStyle];
			
			if(empty(this.chosenStyle.className)){
				var cssStyle = 'tools_zaptips_'+pStyle;
			}else{
				var cssStyle = 'tools_zaptips_'+this.chosenStyle.className;
			}

		}else{
			
			this.chosenStyle = this.styles[this.defaultStyle];
		
			if(empty(this.chosenStyle.className)){
				var cssStyle = 'tools_zaptips_'+this.defaultStyle;
			}else{
				var cssStyle = 'tools_zaptips_'+this.chosenStyle.className;
			}

		}
			

		// Create Tip
 		/*var tmpcellname = 	Builder.node('div',{'class':cssStyle+'_left'},[
							Builder.node('DIV',{'class':cssStyle+'_right'},[
							Builder.node('DIV',{'class':cssStyle+'_name'},this.tiptext)
							])]);*/
							
		/*var tmpcellname =   Builder.node('div',{'class':cssStyle+'_t'},[
							Builder.node('DIV',{'class':cssStyle+'_b'},[
							Builder.node('DIV',{'class':cssStyle+'_l'},[
							Builder.node('DIV',{'class':cssStyle+'_r'},[
							Builder.node('DIV',{'class':cssStyle+'_bl'},[
							Builder.node('DIV',{'class':cssStyle+'_br'},[
							Builder.node('DIV',{'class':cssStyle+'_tl'},[
							Builder.node('DIV',{'class':cssStyle+'_tr'},this.tiptext)
							
							])])])])])])]);*/
		
		this.container.appendChild(Builder.node('div',{'class':cssStyle+'_tl'},[
							Builder.node('div',{'class':cssStyle+'_tr'},[
							Builder.node('div',{'class':cssStyle+'_t'},' ')
							])]));
							
		this.container.appendChild(Builder.node('div',{'class':cssStyle+'_cl'},[
							Builder.node('div',{'class':cssStyle+'_cr'},[
							Builder.node('div',{'class':cssStyle+'_c'},this.tiptext)
							])]));
							
		this.container.appendChild(Builder.node('div',{'class':cssStyle+'_bl'},[
							Builder.node('div',{'class':cssStyle+'_br'},[
							Builder.node('div',{'class':cssStyle+'_b'},' ')
							])]));
							
							
		
		// Calculate position (top,bottom,right) TODO_F : Make a "left" option ... 
		/*switch(this.chosenStyle.snap){
			
			case'bottom':
			
				offset.top  = this.chosenStyle.top + dimensions.height;
				offset.left = this.chosenStyle.left;
				
			break;
			
			case'right':
			
				offset.top  = this.chosenStyle.top;
				offset.left = this.chosenStyle.left + dimensions.width;
			
			break;
			
			case'top':
			
				offset.top  = this.chosenStyle.top - dimensions.height;
				offset.left = this.chosenStyle.left;
			
			break;
			
		}
		
		// Add tip to wraper				
		//this.container.appendChild(tmpcellname);

		// Set Position			
		this.container.clonePosition(this.element,
		{
			setWidth	:	false,
			setHeight	:	false,
			offsetLeft	: 	offset.left,
			offsetTop 	: 	offset.top
		});*/
		
		// add Tic
		
		if(this.chosenStyle.tic == true){
						
			// okay, where to add ?
			switch(this.chosenStyle.snap){
				
				case'bottom':
				
					this.container.insert({top:Builder.node('div',{'class':cssStyle+'_'+this.chosenStyle.snap+'_tic_'+this.chosenStyle.align},' ')});
				
				break;
				
				case'top':
		
					this.container.appendChild(Builder.node('div',{'class':cssStyle+'_'+this.chosenStyle.snap+'_tic_'+this.chosenStyle.align},' '));
					
				break;
			}

		}
		
		// Hide Tip
		this.container.hide();
		 		
		// Insert to Flow
 		$(document.body).insert(this.container);
 		
 		//zap.log('Width:'+);
 		
 		if(this.nomouse == false){
 		
	 		// Create Event
	 		this.element.observe('mouseover', this.showTip.bind(this));
	 		this.element.observe('mouseout', this.hideTip.bind(this));
 		
 		}
 		
	},
	
	sync: function(){
		
		var offset 		= { left:0 , top:0 };
		var dimensions	= this.element.getDimensions();
		
		// Calculate position (top,bottom,right) TODO_F : Make a "left" option ... 
		switch(this.chosenStyle.snap){
			
			case'bottom':
			
				offset.top  = this.chosenStyle.top + dimensions.height;
				offset.left = this.chosenStyle.left;
				
			break;
			
			case'right':
			
				offset.top  = this.chosenStyle.top;
				offset.left = this.chosenStyle.left + dimensions.width;
			
			break;
			
			case'top':
			
				offset.top  = this.chosenStyle.top - dimensions.height;
				offset.left = this.chosenStyle.left;
			
			break;
			
		}
		
		switch(this.chosenStyle.align){
			
			case"right":
							
				offset.left = offset.left - (this.container.getWidth() - dimensions.width);
			
			break;
			
			default:
			break;
			
		}
		
		
		
	
		// Set Position			
		this.container.clonePosition(this.element,
		{
			
			setWidth	:	false,
			setHeight	:	false,
			offsetLeft	: 	offset.left,
			offsetTop 	: 	offset.top
			
		});
		
		
		// destroy
		dimension = null;
		offset = null;
		
		this.fixIE();
		
	},
	
	
	delayShow: function(){
		
		this.sync();
		
		this.effect = new Effect.Appear(this.container, { 
		  duration: 0.2,
		  delay : 1
		});
		
		
	},
	
	fixIE: function(){
		
		this.container.setStyle({'height':this.container.getHeight(),'width':this.container.getWidth()});		
		
	}
	
});


var blinkElement = {
	
	elements : new Array(),
	effect   : null,
	status	 : false,
	timer	 : null,
	
	start: function(){
		
		this.searchElements();
		this.toggleElements();
		
		
	},
	
	stop: function(){
		
	},
	
	searchElements: function(){
		
		this.elements = $$('div.menu_navigation_bubble_blink').clone();

	},
	
	addElement: function(pElement){
		
		var element = $(pElement);		
		
		this.elements.push(element);		
		
	},
	
	deleteElement: function(pElement){
		
		
	},
	
	toggleElements: function(){
		
		
		for(var I=0;I<this.elements.size();I++){
				
			if(!this.status){
				
				Effect.Fade(this.elements[I]);
				
			}else{
				
				Effect.Appear(this.elements[I]);
				
			}
									
		}
		
		this.status = !this.status;
			
		timer = setTimeout("blinkElement.toggleElements()",2000);
		

	}
	
	
};


reallyNewUserTips = function(){
	
	//Country
	var country = new zaptips('layout_head_tabs_region','Choose your region','tabsTopRight',true);
	
	//Language
	var language = new zaptips('layout_head_tabs_lang','Choose your language','tabsTopLeft',true);
	
	// Aloggen
	var login = new zaptips('layout_head_tabs_login','Sign up','tabsLogin',true);
	
	country.delayShow();
	language.delayShow();
	login.delayShow();
	
	
	zaptipslist.push(country);
	zaptipslist.push(language);
	zaptipslist.push(login);

}




function showScraper() {
        var tmp = $('ad120x600');
        if (!tmp)
                return;

        if (tmp.getWidth()!='350')
                tmp.setStyle({'width':'350px', 'right':'0px'});

}

function hideScraper()  {
        var tmp = $('ad120x600');
        if (!tmp)
                return;

        if (tmp.getWidth()!='120')
                tmp.setStyle({'width':'120px'});

}


function showLeader() {
	
        var tmp = $('ad728x90');
        if (!tmp)
                return;

        if (tmp.getHeight()<'290')
                tmp.setStyle({'height':'290px'});
        
}

function hideLeader()   {
			
        var tmp = $('ad728x90');
        if (!tmp)
                return;

        if (tmp.getHeight()>'90')
                tmp.setStyle({'height':'90px'});

}



function setNGroup(n, id)	{
	createCookie(n, id);
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}





var tickerElement = Class.create();
Object.extend(tickerElement.prototype,{

	label 	: '',
	config  : null,

	initialize: function(pLabel){

		this.label = pLabel;

		this.config = new Hash();

	},

	setConfig : function(pParam,pValue){

		//zap.log('[setConfig] Param: '+pParam+' ,Value:'+pValue);

		this.config.set(String(pParam),pValue);

	},

	getConfig : function(pParam){

		return this.config.get(pParam);

	}

});


var ticker = {

	elements : new Hash(),
	status	 : false,

	position: {

		TOP		: 'top',
		BOTTOM	: 'bottom',
		REPLACE : 'replace'

	},

	addElement:function(pLabel,pElement){

		this.elements.set(pLabel,pElement);

	},


	start:function(){

		if( this.status == false ){

			var keys = this.elements.keys();

			for(var I=0;I<this.elements.size();I++){

				this.trigger(keys[I]);

			}

			this.status = true;

		}
	},

	stop: function(){

		if( this.status == true ){

			var keys = this.elements.keys();

			for(var I=0;I<this.elements.size();I++){

				this.stopTrigger(keys[I]);

			}

			this.status = false;

		}

	},

	trigger: function(pLabel){

		tmpelement = this.elements.get(pLabel);

		var timer = window.setInterval("ticker.action('"+pLabel+"');", tmpelement.getConfig('time'));

		tmpelement.setConfig('interval',timer);

		this.status = true;
	},

	stopTrigger: function(pLabel){

		tmpelement = this.elements.get(pLabel);

		window.clearInterval(tmpelement.getConfig('interval'));

	},

	action: function(pLabel){

		tmpelement = this.elements.get(pLabel);

		if(tmpelement.getConfig('xaction')){

			tmpxaction = tmpelement.getConfig('xaction');

			if(tmpxaction.transport.readyState != 4){


				try{

					tmpxaction._complete = true;

					tmpxaction.respondToReadyState(4);

					tmpelement.config.unset('xaction');

				}catch(e){

					zap.log('Action Error: '+e);

				}

			}

		}

		// limit elements
		if(tmpelement.getConfig('maxelements')){

			tmpelements = $(tmpelement.getConfig('container')).select(tmpelement.getConfig('elementSelect'));

			for(var I=tmpelement.getConfig('maxelements');I<tmpelements.size();I++){

				tmpelements[(I-1)].remove();

			}


		}

		var elXaction = new Ajax.Updater(tmpelement.getConfig('container'),tmpelement.getConfig('url'), {  method:'post', evalScripts:true,insertion:tmpelement.getConfig('position')});

		tmpelement.setConfig('xaction',elXaction);

	},

	callback: function(pLabel,pTransport){

		tmpelement = this.elements.get(pLabel);
		this.insertData(tmpelement.getConfig('container'),pTransport.responseText,null);

	},

	createElement: function(pLabel,pTime,pURL,pContainer){

		var tmpelement = new tickerElement(pLabel);

		tmpelement.setConfig('time',pTime);
		tmpelement.setConfig('url',pURL);
		tmpelement.setConfig('container',pContainer);
		tmpelement.setConfig('position',this.position.TOP);

		this.addElement(pLabel,tmpelement);

		return tmpelement;

	},


	setElementConfig: function(pLabel,pParam,pValue){

		//zap.log('[setElementConfig] Label: "'+pLabel+'" ,Param: "'+pParam+'" , Value: "'+pValue+'"');

		tmpelement = this.elements.get(pLabel);

		tmpelement.setConfig(pParam,pValue);

	},


	abortXactionFrom: function(pLabel){

		tmpelement = this.elements.get(pLabel);

		tmpxaction = tmpelement.getConfig('xaction');

		tmpxaction.transport.abort();

		return tmpxaction;

	},


	getXactionFrom: function(pLabel){

		tmpelement = this.elements.get(pLabel);

		return tmpelement.getConfig('xaction');

	}


};


var tickerManager = {

	bricks 	: new Hash(),
	config	: new Hash(), // tickerManager Configuration
	time	: 10000,
	timer	: null,
	started : false,
	
	
	url 	: ' /en/p13547/index.html',
	
	
	autostart : true,

	tmp: '',


	addBrick : function(pName,pOject){

		this.bricks.set(String(pName),pOject);

		if((this.started == false) && (this.autostart == true))
			this.start();

	},


	sync : function(){



	},

	start : function(){

		this.started = true;
		this.timer = window.setInterval("tickerManager.sendRequest()", this.time);

	},

	stop : function(){

		window.clearInterval(this.timer);
		this.started = false;

	},

	getJSON : function(){

		tmp = this.bricks.keys();

		tmphash = new Hash();

		for(var I=0;I<tmp.size();I++){

			tmpconfig = this.bricks.get(tmp[I]);

			tmphash.set(tmp[I],tmpconfig.config.clone());

		}

		return tmphash.toJSON();
	},

	evalReturn : function(pReturnText){

		// 4 debug
		// this.tmp = pReturnText;

		tmpcontainer = Builder.node('div');

		tmpcontainer.insert(pReturnText);

		tmpulmain = tmpcontainer.down();

		Element.cleanWhitespace(tmpcontainer);
		Element.cleanWhitespace(tmpulmain);

		for(var I=0;I<tmpulmain.childNodes.length;I++){

			// get First Brick Values


			tmpTickerElement = tmpulmain.childNodes[I];

			Element.cleanWhitespace(tmpTickerElement);


			objID = tmpTickerElement.id;

			label = String(objID.substr(15,objID.length));

			tmpelements = $('ticker_'+label+'').select('div.portalviewinner');

			elementsize = tmpelements.size();

			if(this.bricks.get(label)){

				tmpobject = this.bricks.get(label);

			}


			if(tmpTickerElement.childNodes.length > 0){



				tmpitems = tmpTickerElement.firstChild.childNodes;



				// loop elements
				for(var Y=0;Y<tmpitems.length;Y++){


					newElement = tmpitems[Y].firstChild;



					//newElement.setStyle({'display':'none'});

					$(newElement).hide();

					$('ticker_'+label+'').insert({top:newElement});


					$(newElement).appear({ duration: 0.4 });

					//tmpelements = $('ticker_'+label+'').select('div.portalviewinner');

					//elementsize = tmpelements.size();
					var elementsize = $('ticker_'+label+'').childElementCount;

					if(typeof elementsize == "undefined")
						elementsize = $('ticker_'+label+'').childNodes.length;

					if((elementsize > tmpobject.getConfig('max')) && (elementsize > 0)){

						tmplast = tmpelements[tmpelements.size()-1].remove();

					}


				}

			}else{

				//zap.log('[evalReturn] Empty list');

			}


		}




	},


	sendRequest : function(){

		if(this.bricks.size() > 0){

			new Ajax.Request(this.url, { method: 'post',  onSuccess: function(transport) { this.evalReturn(transport.responseText); }.bind(this),parameters:{'tctxt':'silent','data':this.getJSON()} });

		}else{

			//zap.log('[sendRequest] Size:'+this.bricks.size());
		}

	},

	getBrick : function(pName){

		if(this.bricks.get(pName)){

			return this.bricks.get(pName);

		}
	}

}


// jsr_class.js
//
// JSONscriptRequest -- a simple class for making HTTP requests
// using dynamically generated script tags and JSON
//
// Author: Jason Levitt
// Date: December 7th, 2005
//
// A SECURITY WARNING FROM DOUGLAS CROCKFORD:
// "The dynamic <script> tag hack suffers from a problem. It allows a page 
// to access data from any server in the web, which is really useful. 
// Unfortunately, the data is returned in the form of a script. That script 
// can deliver the data, but it runs with the same authority as scripts on 
// the base page, so it is able to steal cookies or misuse the authorization 
// of the user with the server. A rogue script can do destructive things to 
// the relationship between the user and the base server."
//
// So, be extremely cautious in your use of this script.
//
//
// Sample Usage:
//
// <script type="text/javascript" src="jsr_class.js"></script>
// 
// function callbackfunc(jsonData) {
//      alert('Latitude = ' + jsonData.ResultSet.Result[0].Latitude + 
//            '  Longitude = ' + jsonData.ResultSet.Result[0].Longitude);
//      aObj.removeScriptTag();
// }
//
// request = 'http://api.local.yahoo.com/MapsService/V1/geocode?appid=YahooDemo&
//            output=json&callback=callbackfunc&location=78704';
// aObj = new JSONscriptRequest(request);
// aObj.buildScriptTag();
// aObj.addScriptTag();
//
//


// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}


// Zap Class
var zap = {
	
	// VARS
	
			debug:false,
		

	hasConsole		:false,
	virtualConsole	:null,
	logCache		:[],
	
	init: function(){
		
		// check if firebug or other console is enabled
		this.hasConsole = (window.console != undefined);		
		
		// init something if needed
	},
	
	// -- log function ... bye bye Alert!!!!
	log: function(pMessage){
		
		this.hasConsole = !(typeof window.console == 'undefined');
		
		if(this.debug && this.hasConsole && !(Prototype.Browser.IE)){
			
			console.log(pMessage);
			
		}else if(this.debug && !this.hasConsole){
			
			// create virtual console
			this.logVirtual(pMessage,false);
			
			
		}
		
		
		
	},
	
	vlog: function(pMessage){
		
		// create virtual console
		this.logVirtual(pMessage,true);
		
	},
	
	
	logVirtual: function(pMessage,pAutoExpand){
				
		if(this.virtualConsole == null){
			
			this.createLogWindow();
			
			if(pAutoExpand){
				this.showLogWindow();
			}
			
			this.logVirtual(pMessage,false);
			
			
			
		}else{
			
			this.virtualConsole.insert('-'+pMessage+'<br />');
			this.virtualConsole.scrollTop = this.virtualConsole.scrollHeight;
			
		}
		
		
	},	
	
	createLogWindow: function(){
		
		this.virtualConsole = Builder.node('div',{'style':'z-index:10000;position:fixed;height:20px;width:20px;top:20px;left:20px;opacity:0.9;border:1px solid #000000;background:#FFFFFF;padding:5px;overflow:auto;','onclick':'zap.toggleLogWindow()'});
		
		window.document.body.appendChild(this.virtualConsole);
		
	},
	
	showLogWindow: function(){
		
		this.virtualConsole.setStyle({'height':'160px','width':'400px'});
		
	},
	
	hideLogWindow: function(){
		
		this.virtualConsole.setStyle({'height':'20px','width':'20px'});
	},
	
	toggleLogWindow: function(){
		
		if(this.virtualConsole != null){
		
			if(this.virtualConsole.getStyle('height') == '20px'){
				
					this.showLogWindow();
				
			}else{
				
					this.hideLogWindow();
				
			}
		
		}else{
			
			this.createLogWindow();
			this.showLogWindow();
			
		}
	},

	
	growl: {
		
		list: new Hash(),
		ids: 0,
		timeout : 4000,
		limit:5,
		height:80,
					
		add: function(pTitle,pText,pIcon) {
								
			// count
			this.ids++;
			
			// Container
			cont = this.create(pText,pTitle,null);
						
			//add to flow
			$(document.body).insert(cont);
			
			Effect.BlindDown(cont);
			
			this.list.set(this.ids,cont);
			
			setTimeout("zap.growl.fade('"+this.ids+"')",this.timeout);
				
		},
		
		
		create: function(pText,pTitle,pIcon){
			
			var iconpath = '/skins/zap/common/';
			
			//icon
			if(empty(pIcon))
				var icon = iconpath + 'head.png';
			else
				var icon = iconpath + pIcon;
			
			var container = Builder.node('div',{'id':'zapGrowl_'+this.list.size(),'class':'zap_growl_container','style':'display:none;position:fixed;bottom:'+((this.list.size()*this.height)+10+(10*this.list.size()))+'px;right:40px;'});
			
			var content = Builder.node('div');
			
			content.appendChild( Builder.node('div',{'class':'zap_growl_icon'}));
			
			content.appendChild( Builder.node('div',{'class':'zap_growl_title'},pTitle));
			
			content.appendChild( Builder.node('div',{'class':'zap_growl_text'},pText));
			
			container.appendChild(content);
			
			return container;			
			
		},
		
		
		fade: function(pID){
			
			zap.log('Fade ID:'+pID);
			
			cont = this.list.get(pID);
			
			cont.fade(cont,{
				
				
				afterFinish: zap.growl.clear(pID)
				
			});
			
		},
		
		clear: function(pID){
			
			//cont = this.list.get(pID);
			
			//remove from flow
			//cont.remove();
			
			this.list.unset(pID);			
			
			
		}
		
	},
	
	elements : {
		
		cycle : function(pHide,pShow){
			
			hideElements = pHide;
			showElements = pShow;
			
			var hideArray = [];
			var showArray = [];
			
			// hide
			if(Object.isArray(hideElements)){
				hideArray = hideElements;
			}else{
				if(!empty(hideElements)){
					hideArray.push(hideElements);
				}
			}
			
			// show
			if(Object.isArray(showElements)){
				showArray = showElements;
			}else{
				if(!empty(showElements)){
					showArray.push(showElements);
				}
			}
			
			// hide elements
			for(var I=0;I<hideArray.size();I++){			
				if(showArray.indexOf(hideArray[I])<0){
					if($(hideArray[I]))
						$(hideArray[I]).hide()
				}
			}
			
			//show element
			if(showArray.size()>0){
				showArray.each(Element.show);
			}

		}
		

	}
	
}


var musicplayer = {
	
	music 		: 	null,
	canplay		: 	false,
	queue		: 	null,
	frame		: 	null,
	volume		:   4,
	next 		: null,
	previous	: null,
	
	list		: new Hash(),
	
	
	init: function(){
					
		soundManager = new SoundManager();
		
		soundManager.beginDelayedInit();
		
		savedVolume = readCookie('musicplayer');
		
		if(savedVolume == null){
			
			createCookie('musicplayer',this.volume,'31');

		}else{
			
			this.volume = savedVolume;
			
			if($('audioplaylist_buttons_volume_bar')){
				$('audioplaylist_buttons_volume_bar').removeClassName('media_audio_mix_buttons_volume_bar_vol4');
				$('audioplaylist_buttons_volume_bar').addClassName('media_audio_mix_buttons_volume_bar_vol'+this.volume);
			}
			
		}
		
		soundManager.setVolume(this.volume*20);	
			
		soundManager.onload = function(){
			
			this.canplay = true;
			
			if(this.queue != null){
				
				list = this.queue;
				this.play(list[0],list[1]);
							
			}
									
		}.bind(this);
		
	},
	
	play: function(pURL,pID){
		
		if(!this.canplay){
						
			this.queue = new Array(pURL,pID);	
			this.init();
			
		}else{
						
			if(!soundManager.canPlayURL(pURL)){
					
				zap.log('[canPlayURL] False');
				zap.log('[canPlayURL] URL:'+pURL);
								
			}else{
				
				if(this.music != null){
					this.music.stop();
					this.music.destruct();
				}
								
				this.music = soundManager.createSound({id:pID, url:pURL, volume:this.volume*20});
				
				this.music.options.whileplaying = function(){
															
					musicplayer.renderTimer(this);
										
				};
				
				this.music.options.whileloading = function(){
					
					musicplayer.renderLoader(this);
					
				}
				
				this.music.options.onfinish = function(){
					
					var element = $('audioplaylist_play'); 
					
					if(element.hasClassName('media_audio_mix_buttons_play'))
						element.removeClassName('media_audio_mix_buttons_play');
						
					element.addClassName('media_audio_mix_buttons_pause');
					
					this.setPosition(0);
					
					musicplayer.goNext();
					
				}
				this.music.play();
			}
			this.queue = null;
		}
	},
	
	renderLoader: function(pMusic){

		var music = pMusic;
		
		// Bar
		var bar = Math.round(160*(music.bytesLoaded / music.bytesTotal));							
		$('audioplaylist_barinner_load').style.width = bar+'px';

	},
	
	getTime: function(pMS){
		
		var allseconds = Math.round(pMS/1000);
		
		var minutes = (allseconds - (allseconds % 60)) / 60;
		
		var seconds = allseconds % 60;
		
		if(seconds < 10){
			seconds = '0'+seconds;			
		}

		return minutes+':'+seconds;
	},

	renderTimer: function(pMusic){
		
		var music = pMusic;
		
		if($('audioplaylist_barinner')){
			// Bar
			var bar = Math.round(160*(music.position / music.duration));							
			$('audioplaylist_barinner').style.width = bar+'px';
		}
		
		// Time Duration
		if($('audioplaylist_timer_duration')){
			
			if(music.loaded)
				$('audioplaylist_timer_duration').innerHTML = this.getTime(music.duration);
			else
				$('audioplaylist_timer_duration').innerHTML = this.getTime(music.durationEstimate);
		}
		
		// Time Position
		if($('audioplaylist_timer_position')){	
			$('audioplaylist_timer_position').innerHTML = this.getTime(music.position);			
		}
				
	},
	
	pause: function(pElement){
		
		var element = $(pElement);
	
		if(this.music.paused || (this.music.playState==0)){
							
			if(element.hasClassName('media_audio_mix_buttons_pause'))
				element.removeClassName('media_audio_mix_buttons_pause');
				
			element.addClassName('media_audio_mix_buttons_play');
			
			this.music.play();
						
		}else{
			
			if(element.hasClassName('media_audio_mix_buttons_play'))
				element.removeClassName('media_audio_mix_buttons_play');
				
			element.addClassName('media_audio_mix_buttons_pause');
			
			this.music.pause();	
		}
		
	},
	
	open:function(pURL){
		
		var height 		= 363;
		var width  		= 370;
		var windowname 	= 'musicplayerframe';
		
		if((this.frame==null) || this.frame.closed){
			
			if(self.name == windowname){
				
				self.location.href = pURL;
				
			}else{	
				
				var args = 'width='+width+',innerWidth='+width+',height='+height+',innerHeight='+height+',resizable=no,status=no,titlebar=no,fullscreen=no,dialog=no,location=no,toolbar=no,menubar=no';
				this.frame = window.open(pURL,windowname,args);
				this.frame.focus();
				
			}
					
		}else{
			
			this.frame.location.href = pURL;
			this.frame.focus();	
					
		}

	},
	
	// pSide: true = up, false = down
	setVolume: function(pSide){
		// Check
		var tmpvolume = parseInt(this.volume,10);
		
		if(pSide){
			tmpvolume++;
		}else{
			tmpvolume--;
		}
					
		if(tmpvolume > 0 && tmpvolume < 6){
			
			if(this.music != null)
				this.music.setVolume(tmpvolume*20);
			
			if($('audioplaylist_buttons_volume_bar')){
				$('audioplaylist_buttons_volume_bar').removeClassName('media_audio_mix_buttons_volume_bar_vol'+this.volume);
				$('audioplaylist_buttons_volume_bar').addClassName('media_audio_mix_buttons_volume_bar_vol'+tmpvolume);
			}
			
			this.volume = tmpvolume;
			createCookie('musicplayer',this.volume,'31');
		}
	},
	
	seek: function(e){
		if(this.music.playState == 1 && !this.music.paused && this.music.loaded){
			var barpos = $('audioplaylist_barinner').cumulativeOffset();
			var posX = (document.all) ? window.event.x + document.body.scrollLeft : e.pageX;
			var seekPos = Math.round(((posX - barpos.left) / 160) * this.music.duration);	
			this.music.setPosition(seekPos);
		}
	},
	
	goNext: function(){
		if(this.next != null){	
			window.document.location.href = this.next;
		}
	},
	
	goParent: function(pURL){
		if(window.opener && (window.opener != self)){
			window.opener.location.href = pURL;
			window.opener.focus();
		}
	},
	
	getVolume: function(){
		return this.volume;
	}

}


function nospam(pReceipt, pDomain){
	
         document.location.href = 'mailto:'+pReceipt+'@'+pDomain;
         
}

var instanceView = {
	
	smallpics : new Hash(),
	
	showSmallPic: function(pElement,pInfoElement){
				
		element 	= $(pElement);
		
		if(!this.smallpics.get(pInfoElement)){
			
			var infoElement = $(pInfoElement);
			
			//if(infoElement.getOffsetParent() != window.document.body)
			window.document.body.appendChild(infoElement);
			
			this.smallpics.set(pInfoElement,infoElement);
						
		}else{
			
			var infoElement = this.smallpics.get(pInfoElement);
			

		}
		
		
		infoElement.clonePosition(element,{setWidth:false,setHeight:false,offsetTop:(0-infoElement.getHeight()),offsetLeft:-90});
		infoElement.show();
		
		
	},
	
	hideSmallPic: function(pInfoElement){
		
		if(this.smallpics.get(pInfoElement)){
			
			var infoElement = this.smallpics.get(pInfoElement);
			infoElement.hide();
			
		}
		
	},
	
	showEventimagePreview: function(pID,pSize,e){
		
		if($('ivpreviewwindow')){
			$('ivpreviewwindow').remove();
		}
		
		e = e || window.e;
		
		var cursor = {x:0, y:0};
		
		if (e.pageX || e.pageY) {
			
			cursor.x = e.pageX;
			cursor.y = e.pageY;
			
		}else {
			
			var de = document.documentElement;
			var b = document.body;
			cursor.x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
			cursor.y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
			
		}
			
		document.body.appendChild(Builder.node('div',{'id':'ivpreviewwindow','style':'padding:5px;background-color:#003399;position:absolute;top:'+cursor.y+'px;left:'+cursor.x+'px;min-height:100px;min-width:100px;z-index:9999999','onclick':'this.remove();'}));

		loadIVInto('ivpreviewwindow',pID,'img',{'size':pSize});
		
		return true;
		
	}
	
	
}


var contact = Class.create({
	
	id 		: null,
	name	: '',
	parms	: null,
	
	initialize: function(pId){
		this.id = pId;
		this.parms = new Hash();
	},
	
	addParm: function(pName,pValue){
		var tmp = this.parms.set(pName,pValue);
	},
	
	delParm: function(pName){
		var tmp = this.parms.unset(pName);
	},
	
	getParm: function(pName){
		return this.parms.get(pName);
	}
	
});




var contactsLocalSearch = {
	
	selectedContacts	: null,
	searchObject 		: null,
	
	init: function(){
				
		this.purge();
			
		this.searchObject = new localSearch($('searchfield'),$('searchzone'),'div.userCell','div.ac_view_label');
		this.searchObject.afterSearch = this.sync.bind(this);
		
	},
		
	evalContact: function(pID){
		
		//check it
		
		
	},
	
	selectContact: function(pID,pReset){
				
		// check if allready in list
		if(this.selectedContacts.get(pID)){
			
			this.selectedContacts.unset(pID);
			
		}else{
	
			this.selectedContacts.set(pID,'user'+pID);
		}
		
		this.count();
			
	},
	
	selectAll: function(pElement){
		
		element = $(pElement);
						
		var state = element.checked;
		
		var visibleCount = 0;
						
		var contacts = $('bookReceiversSource').select('div.userCell');
			
		for(var I=0;I<contacts.size();I++){
			
			if(contacts[I].visible()){
				
				var tmp = contacts[I].select('input.bookCheckbox');
				
				//this.selectContact(tmp[0].value);
				if(state === true){
					this.selectedContacts.set(tmp[0].value,'user'+tmp[0].value);
				}else{
					this.selectedContacts.unset(tmp[0].value);
				}
				
				tmp[0].checked = state;
				
				if(state === true){
					
					visibleCount++;
					
				}
				
			}
	
		}
		
		this.setCount(visibleCount);
		
	},
	
	
	sync: function(){
				
		this.selectVisible();
		
	},
	
	count: function(){ // count only visible stuff
		
		var tmparray = this.selectedContacts.values();
		var visibleCount = 0;
		
		// loop selected items
		for(var I=0;I<tmparray.size();I++){
			
			if($(tmparray[I]).visible()){
				
				visibleCount++;
				
			}
		
		}
		
		this.setCount(visibleCount);
		
	},
	
	setCount: function(pCount){
		
		if($('selCount'))
			$('selCount').innerHTML = pCount;
		
		
	},
	
	selectVisible: function(){
		
		var tmparray = this.selectedContacts.values();
		var visibleCount = 0;
						
		// loop selected items
		for(var I=0;I<tmparray.size();I++){
			
			// get checkbox element
			var tmp = $(tmparray[I]).select('input.bookCheckbox');
			
			if($(tmparray[I]).visible()){
				
				tmp[0].checked = true;
				
				visibleCount++;
				
			}else{
				
				tmp[0].checked = false;
				
			}
		
		}
		
		this.setCount(visibleCount);
		
	},
	
	purge: function(){

		this.searchObject = null;
		this.selectedContacts = new Hash();

	},
	
	reset: function(){
		
		if(this.searchObject !== null){
			
			this.searchObject.reset();
			
		}else{
			
			$('searchfield').value="";
			
		}
				
	}
	
	
}

var uploadProgressBarList = [];

var uploadProgressBar = Class.create({
	
	uuid:'',
	
	formElement:null,
	barElement:null,
	barElementText:null,
	
	inputElement:null,
	
	intereval:null,
	timer:null,
	container:null,
	
	initAction:null,
	req:null,
	ticker:null,
	
	initialize : function(pFormID){
		
		if($(pFormID)){
			this.formElement = $(pFormID);
		}else{
			zap.log('[initialize] Form not found!');
			return;
		}
		
		if($('uploadProgressBar'+pFormID)){
			this.container = $('uploadProgressBar'+pFormID);
		}else{
			zap.log('[initialize] Element not found!');
			return;
		}
				
	},
	
	drawProgress: function(pPercent){
		
		calWidth = Math.round(((this.container.getWidth()-2) / 100)*pPercent);
					
		this.barElement.setStyle({'width':calWidth+'px'});
		
		this.barElementText.innerHTML = pPercent+'%';
				
	},
	
	createProgressBar: function(){
		
		// Create noew DOM Object for bar
		this.barElement = Builder.node('div',{'id':'uploadProgressBarInner'+this.formElement.id,'class':'form_upload_progressbar_inner'});
		this.barElementText = Builder.node('div',{'id':'uploadProgressBarInnerText'+this.formElement.id,'class':'form_upload_progressbar_text'});
		
		// empty container
		this.container.innerHTML='';
				
		// append new DOM objects
		this.container.appendChild(this.barElement);
		this.container.appendChild(this.barElementText);
		
		// show container
		this.container.show();
		
	},
	
	setFormAction: function(pUUID){
		
		if(this.initAction === null)
			this.initAction = this.formElement.action;	
		
		this.formElement.action = this.initAction + '?X-Progress-ID='+pUUID;
		
	},
		
	start: function(){
		
		if(empty(this.inputElement.value))
			return;
		
		// reset timer
		if(this.timer !== null)
			this.stop();
			
		// reset ajax object
		this.req = null;
			
		this.createProgressBar();
			
		this.uuid = '';
		
		// generate random progress-id
		for (i = 0; i < 32; i++) {
			this.uuid += Math.floor(Math.random() * 16).toString(16);
		}
		
		// set UUID on Form
		this.setFormAction(this.uuid);
		
		this.fetch();
		
		this.ticker = setInterval(function(){
			
			this.tick();		
			
		}.bind(this),500);
		
	},
	
	tick: function(){
		
		if((this.req != null) && (this.req.transport.readyState == 4)){
						
			this.fetch();
			
		}
				
	},

	
	update: function(peObject){
		
		//this.update()
		this.fetch();
		
	},
	
	testRandom: function(){
		
		var test = '';
		
		// generate random progress-id
		for (i = 0; i < 32; i++) {
			test += Math.floor(Math.random() * 16).toString(16);
		}
		
		return test;
		
	},
	
	fetch: function() {
		
		this.req = new Ajax.Request("/progress",{
			
			method: 'get',
			asynchronous : true,
			requestHeaders : {"X-Progress-Id":this.uuid},
			onSuccess : function(transport){ 
					this.evalReturn(transport); 
			}.bind(this),
			onFailure : function(transport){
					this.evalError(transport); 
			}.bind(this)
			
		});

	},
	
	evalReturn: function(pTransport){
				
		reqObject = pTransport.responseText.evalJSON();
		
		if(reqObject.state == "done"){
			
			this.stop();
			
			this.drawProgress(100);
			
			
			this.barElementText.innerHTML = 'Upload done!';
			
			
		}else if(reqObject.state == "starting"){
			
			
			this.barElementText.innerHTML = 'Lueden...';
			
			
		}else if(reqObject.state == "uploading"){
			
			this.drawProgress(Math.round((reqObject.received / reqObject.size)*100));
		
		}else if(reqObject.state == "error"){
			
			this.barElementText.innerHTML = 'Error code:'+reqObject.status;
			
		}else{
			
			this.barElementText.innerHTML = 'Unknow error/state!';
			
		}
		
		
	},
	
	evalError: function(pTransport){
		
		// show ERROR
		this.barElementText.innerHTML = '[ERROR] Status:'+pTransport.status;
		
	},
	
	stop: function(){
		
		clearInterval(this.ticker);
		
	}
	
});


var zapYoutubeBox = Class.create({
	
	player : null,
	config : {},
	autostart: false,
	pointer : null,
	queue : null ,
	
	initialize: function(pPlayerID,pYTID,pQueue){
		
		this.queue = [pYTID].concat(pQueue);
		
		this.pointer = 0;
		
		zap.log('[zapYoutubeBox] initialize');
		
		var tmpplayer = $(''+pPlayerID+'');
		
		this.player = tmpplayer;
		
		this.addEvent();
							
	},
	
	addEvent: function(){
		
		zap.log('[zapYoutubeBox] addEvent');
		
		this.player.addEventListener("onStateChange","onYouTubeStateChange");		
		

	},
	
	evalState : function(pState){
		
		zap.log('[zapYoutubeBox] evalState :'+pState);
		
		//ended, goto next
		if(pState == 0){
			
			this.playNext();
			
		}
		
	},
	
	playNext : function(){
		
		this.pointer++;
		
		if(this.pointer == this.queue.size())
			this.pointer = 0;
			
		zap.log('playNext pointer:'+this.pointer);
	},	
		
	playID : function(pID){
		
		 if (this.player) {
            this.player.loadVideoById(pID, 0);
          }

	},
	
	startID: function(pYTID){
		
		this.player.cueVideoById(pYTID,0);
		
	},
	
	playURL : function(pURL){
		
		 if (this.player) {
		 	this.player.loadVideoByUrl(pURL, 0);
		 }

	},
	
	play : function(){
		
		 if (this.player) {
		 	
		 	this.player.playVideo();
		 }
		
	},
	
	stop : function(){
		
		if (this.player) {
		 	
		 	this.player.stopVideo();
		 }
		
	},
	
	cueVideo : function(pID){
		
		 if (this.player) {
		 	
		 	this.player.cueVideoById(pID, 0);
		 	
		 }
		
	},
	
	swtichToNext : function(){
		
		
		
	}
		
});



zapEventImageTagging = Class.create({
	
	person 		: 0,
	peoples		: null,
	activeperson: null,
	object 		: null, 	// image wraper (div)
	objectid	: null, 	// image wraper (div)
	container 	: null, 	// where to put inputs (div)
	form 		: null, 	// formid (form)
	
	cursor			: null,
	cursorcontainer	: null,
	cursorsize  	: 60,
	
	ready		: false,
	wrap		: null,
	objOffset	: null,
	objDims	: null,
	timer : null,
	
	initialize: function(pContainer,pObject,pForm,pPeoples){
			
		this.container = $(pContainer);
		this.objectid = pObject;
		this.object = $(this.objectid);
		this.form = $(pForm);
		
		this.peoples = pPeoples;
		
		this.addEvents();
		
		this.preparePersons();
		
		this.timer = window.setInterval(function(){
			
			if(this.checkObject())
				window.clearInterval(this.timer);
			
		}.bind(this),500);
		
	},
	
	checkObject : function(){
		
		if(!$(this.objectid)){
			return false;
		}else{
			this.object = $(this.objectid);
			this.prepareForCursor();
		}
						
	},
	
	
	submitForm: function(){
		
		//this.form.submit();
		eval('anoformfunc'+this.form.identify()+'submit()');
		
	},
	
	preparePersons: function(){
		
		this.selectPerson(this.peoples.first());
		
	},
	
	selectPerson: function(){
		
		if(this.peoples.size() > 0){
		
			if(this.peoples.first().hasClassName('todo')){
				
				this.peoples.first().removeClassName('todo');
				this.peoples.first().addClassName('selected');
	
			}
		
		}else{
			
			//this.submitForm();
			this.cursor.setStyle({'border':'1px solid red'});
			
		}

	},
	
	
	tagPerson : function(pPosition){
		
		
		tmpPerson = this.peoples.shift();
		tmpInput = tmpPerson.select('input').first();
				
		tmpInput.value = pPosition['X1']+';'+pPosition['X2']+';'+pPosition['Y1']+';'+pPosition['Y2'];
		
		this.wrap.appendChild(Builder.node('div',{'id':'cursor_'+this.person,'style':'position:absolute;z-index:1;left:'+pPosition['X1']+'px;top:'+pPosition['Y1']+'px;width:'+(pPosition['X2']-pPosition['X1'])+'px;height:'+(pPosition['Y2']-pPosition['Y1'])+'px;border:1px solid lightgreen;'},this.person));
		
		if(tmpPerson.hasClassName('selected')){
			
			tmpPerson.removeClassName('selected')
			tmpPerson.addClassName('done');

		}
		
		
		this.selectPerson();
	},

	
	evalClick : function(pEvent){
						
		if(this.ready !== true){
			
			this.prepareForCursor();
		}
		
		if(this.peoples.size() > 0){
		
			positions = [];
			
			positions['X1'] = Math.min(Math.max(Event.pointerX(pEvent)-this.objOffset.left-(this.cursorsize/2),0),(this.objDims.width-this.cursorsize));
			positions['X2'] = positions['X1'] + this.cursorsize;
			positions['Y1'] = Math.min(Math.max(Event.pointerY(pEvent)-this.objOffset.top-(this.cursorsize/2),0),(this.objDims.height-this.cursorsize));
			positions['Y2'] = positions['Y1'] + this.cursorsize;
			
			this.tagPerson(positions);
		
		}else{
			
			this.submitForm();
			
		}
		
	},
	
	addEvents: function(){
		
		if(this.object !== null){
					
			this.object.observe('click',function(event){
				
				this.evalClick(event);
				
			}.bind(this));
		
		
		}
		
	},
	
	prepareForCursor: function(){
		
		if(this.ready === true)
			return ;
			
		if(empty(this.object))
			return ;
		
		
		//get img data
		imgDimensions = this.object.getDimensions();
						
		//create wrap
		this.wrap = Builder.node('div',{'id':'img_wrap'});
		this.wrap.setStyle({'height':imgDimensions.height+'px','width':imgDimensions.width+'px','z-index':'1'});
		
		// container for the cursors
		this.cursorcontainer = Builder.node('div',{'style':'position:absolute;'});
		this.cursorcontainer.setStyle({'height':imgDimensions.height+'px','width':imgDimensions.width+'px',zIndex:'99'});
		this.wrap.appendChild(this.cursorcontainer);
			
		// create cursor
		this.cursor = Builder.node('div',{'id':'img_cursor','style':'border:1px solid blue;'});
		this.cursor.absolutize();
		this.cursor.setStyle({'height':(this.cursorsize-2)+'px','width':(this.cursorsize-2)+'px',zIndex:'9'});
		this.cursor.hide();		
		this.wrap.appendChild(this.cursor);
		
		// move object an set absolute
		this.object.up().appendChild(this.wrap);
		this.wrap.appendChild(this.object);
		this.object.absolutize();
		this.object.setStyle({zIndex:'0'});
		
		// get dimensions
		this.objOffset = this.wrap.cumulativeOffset();
		this.objDims = this.wrap.getDimensions();
		
		// event hover
		this.cursorcontainer.observe('mousemove',function(event){
			
			//element = Event.element(event);
			this.moveCursorTo(event);
					
		}.bind(this));
		
		
		// event hover
		this.cursorcontainer.observe('mouseout',function(event){
			
			//element = Event.element(event);
			this.cursor.hide();
					
		}.bind(this));
		
		// event hover
		this.cursorcontainer.observe('mouseover',function(event){
			
			//element = Event.element(event);
			this.cursor.show();
					
		}.bind(this));
		
		
		this.cursorcontainer.observe('DOMMouseScroll',function(event){
					
			this.scaleCursor(event.detail*-1);
			
			event = event ? event : window.event;
			if(event.stopPropagation)
				event.stopPropagation();
			if(event.preventDefault)
				event.preventDefault();
			event.cancelBubble = true;
			event.cancel = true;
			event.returnValue = false;
			return false;
					
		}.bind(this));
		
		
		this.cursorcontainer.observe('mousewheel',function(event){
			
			var wheelData = event.detail ? event.detail : event.wheelDelta;
									
			this.scaleCursor(wheelData);
			
			event = event ? event : window.event;
			if(event.stopPropagation)
				event.stopPropagation();
			if(event.preventDefault)
				event.preventDefault();
			event.cancelBubble = true;
			event.cancel = true;
			event.returnValue = false;
			return false;
					
		}.bind(this));

		this.cursorcontainer.observe('click',function(event){
				
				this.evalClick(event);
				
		}.bind(this));
				
		this.ready = true;
		
	},
	
	
	moveCursorTo: function(pEvent){
		
		tmpX = Math.min(Math.max(Event.pointerX(pEvent)-this.objOffset.left-(this.cursorsize/2),0),(this.objDims.width-this.cursorsize));
		tmpY = Math.min(Math.max(Event.pointerY(pEvent)-this.objOffset.top-(this.cursorsize/2),0),(this.objDims.height-this.cursorsize));
					
		this.cursor.setStyle({'top':(tmpY)+'px','left':(tmpX)+'px'});

	},
	
	scaleCursor: function(pDelta){
		
		var oldSize = this.cursorsize;
		
		if(pDelta > 0){
			
			if(	
				this.cursorsize < 300 
				&& (((this.cursor.offsetTop+(this.cursorsize/2)-((this.cursorsize+40)/2))) > 0) 
				&& (((this.cursor.offsetLeft+(this.cursorsize/2)-((this.cursorsize+40)/2))) > 0)
				&& (this.cursor.offsetTop+this.cursorsize+40 < this.objDims.height)
				&& (this.cursor.offsetLeft+this.cursorsize+40 < this.objDims.width)
			){
					
				this.cursorsize = (this.cursorsize + 40);
				
			}
			
		}else if(pDelta < 0){
			
			if(this.cursorsize > 60){
				
				this.cursorsize = (this.cursorsize - 40);
				
			}
			
		}
				
		this.cursor.setStyle({'height':(this.cursorsize-2)+'px','width':(this.cursorsize-2)+'px','top':(this.cursor.offsetTop+(oldSize/2)-(this.cursorsize/2))+'px','left':(this.cursor.offsetLeft+(oldSize/2)-(this.cursorsize/2))+'px'});
			
	}
});



zapConsoleObject = Class.create({
	
	// white fader
	fader 		: null,
	faderColor  : null,
	
	// console
	container 	: null, // mein div/wrper
	conten		: null, // pointer to content area
	
	// settings
	mode		: null,
	
	initialize: function(){
		
			
		
	},
	
	build: function(){
		
		documentBody = $(window.document.body);
		
		if(empty(documentBody)){
			
			zap.log('[zapConsoleObject] Document.body empty. Wait for pageload!');
			
			return ;
			
		}
		
		// fader
		this.fader = Builder.node('div',{'style':'display:none;','class':'common_fader'});
		
		documentBody.appendChild(this.fader);
		
		//console
		this.container = Builder.node('div',{'class':'common_console','style':'display:none;'});
		
		this.container.appendChild(Builder.node('div',{'class':'top'},[
			Builder.node('div',{'class':'right'},[
			Builder.node('div',{'class':'center'}
		)])]));
				
		this.content = Builder.node('div',{'class':'center'},'');
		
		this.container.appendChild(Builder.node('div',{'class':'middle'},[
			Builder.node('div',{'class':'right'},[this.content])]));
		
		this.container.appendChild(Builder.node('div',{'class':'bottom'},[
			Builder.node('div',{'class':'right'},[
			Builder.node('div',{'class':'center'}
		)])]));
		
		documentBody.appendChild(this.container);
		
		// vars 
		this.faderColor = this.fader.getStyle('backgroundColor');
		
				
	},
	
	// fade page in, hide fader
	fadeIn: function(){
		
		this.fader.fade({duration: 0.3, to: 0.01,afterFinish:function(){
			
			this.fader.hide();			
			
		}.bind(this)});

	},
	
	fadeOut: function(){
		
		// check if set
		if(empty(this.fader))
			return;
			
		this.fader.show();
		this.fader.setStyle({height: "100%"});
		this.fader.setOpacity(0.01);
		this.fader.appear({duration: 0.3, to: 0.6});
		
	},
	
	setFaderColor: function(pColor){
		
		if(!empty(this.fader)){
			this.fader.setStyle({'backgroundColor':pColor});
			this.faderColor = pColor;
		}
		
	},
	
	pulsateFader: function(){
		
		if(!this.hasConsole())
			return;
		
		
		//colors
		this.faderColor = this.fader.getStyle('backgroundColor');
		
		errorColor = '#FF9933';
		
			
		new Effect.Morph(this.fader, {
		  style: 'background-color:'+errorColor+';',
		  duration: 0.1, // Core Effect properties
		  afterFinish: function(){
		  	
		  		new Effect.Morph(this.fader, {
		  			
		  			style: 'background-color:'+this.faderColor+';',
		  			duration: 1
		  			
		  		});
		  			  	
		  }.bind(this)
		});

		
	},
	
	
	hasConsole: function(){
		
		if(empty(this.fader))
			return false;
			
		if(empty(this.container))
			return false;
			
		if(empty(this.content))
			return false;
		
			
		return true;
		
	},
	
	// show console
	show: function(){
		
		if(!this.hasConsole())
			this.build();
		
			
		// optional
		if(arguments.length > 0){	
			var w = arguments.length > 0 ? arguments[0] : tmp.getWidth(); 
			var h = arguments.length > 1 ? arguments[1] : tmp.getHeight(); 
		}
			
		//if(this.container.visible() === false){
		/*}else{
		}*/	
		
			// fade page out
			
			
			this.fadeOut();
			
			this.showConsole();
						
			this.centerConsole();
			
		
				
	},
	
	// hide console
	hide: function(){
		
		if(!this.hasConsole())
			return;
		
		this.fadeIn();
		
		
		this.hideConsole();
		
	},
	
	
	showConsole: function(){
		
		// show console
		this.container.appear({duration: 0.6, to: 1});
		
	},
	
	
	hideConsole: function(){
		
		// hide console
		this.container.fade({duration: 0.6, to: 0 ,afterFinish:function(){
			
			this.container.hide();		
			
		}.bind(this)});
		
	},
	
	centerConsole: function(){
		
		// TODO_F, rewrite prototype-style
		size = getWindowSize();
		x = Math.round(size.get("width") - this.container.getWidth())/2;
		y = 180;
		
		this.container.setStyle({left: x + "px", top: y + "px"}); 
		
	},
	
	
	load: function(pURL){
		
		
		var parameters	= new Hash();
		if (arguments.length>1)	{
		
			if (typeof arguments[1]  == "object" && Object.isHash(arguments[1]))	{
				
				parameters	= arguments[1];
				
			}	else	{
							
				if ($(arguments[1]) && $(arguments[1]).tagName.toLowerCase() == 'form')
					parameters 	= $(arguments[1]).serialize(true);
	
			}
		
		}
		
		if(Object.isHash(parameters)){
	
			parameters.set('tctxt', 'console');
		
		}else{
			
			Object.extend(parameters, {tctxt:'console'});
			
		}
	
		this.show();
		
		new Ajax.Request(pURL, {  method:'post', parameters:parameters, onComplete: function(pTransport){
			
			this.complete(pTransport);
						
		}.bind(this)});

	},
	
	complete: function(pTransport){
		
		
		this.content.innerHTML = pTransport.responseText;
		
	},
	
	close: function(){
		
		this.container.hide();
		this.content.innerHTML = '';
		
		
	},
	
	// 
	setMode: function(pMode){
		
		
	},
	
	setSpecialMode: function(pWidth,pHeight){
		
		
	}
	
	
});

// Apend to Zap masterclass
/*Object.extend(zap,{
	
	console :  new zapConsoleObject()
	
});
*/



var dropDownEval = {
	
	open: function(event){
		
		zap.log('[dropDownEval::open]');
		
		element = Event.element(event);
		
		parentEl = element.up('div.form_dropdown');
		
		if(isset(parentEl)){
			
			zap.log('[dropDownEval::open] hasParent');
		
			parentEl.select('div.links').first().show();		
		
		}else{
			
			zap.log('[dropDownEval::open] parentNotFound');
			
		}
		
	},
	
	
	close: function(pElement,event){
		
		mainEl = $(pElement);
		
		

		element = Event.element(event);
		
		zap.log('[dropDownEval::close] Classes:'+element.classNames());
		
		parentEl = element.up('div.form_dropdown');
		
		if(stillInsideParent(event,mainEl)){
			
			zap.log('[dropDownEval::close] insideParent');

		}else{
			
			mainEl.select('div.links').first().hide();	
			
			zap.log('[dropDownEval::close] notInsideParent');
			
		}
		
		
	}
};



/* ZAP S.A 2010 
	Scroll Effects
*/
 
// Apend to Zap masterclass
Object.extend(zap,{
	// scroll over time shortct
	scroll : {
		init: function(pElement,pStyle){
			return new scrollOverTime(pElement,pStyle);
		}
	}
});



// ScrollOverTime - F.DA COSTA
//
// Intelligent Content scroller
//
scrollOverTime = Class.create({
	
	element 		: null,
	content			: null,
	effect			: null,
	buttons			: null,
	animated		: false,
	aniInvert		: false,
	interval		: null,
	waitInterval	: null,
	style			: null,
	styles			: {
		
		
		'menuboard' : {
			
			'opacity' : 0.5,
			'scrollmax' : 160,
			'side'		: 'vertical',
			'buttons' : [
				{
					'style' : 'position:absolute;display:none;top:0px;right:0px;',
					'css' : 'menuboard_up',
					'icon' : ' ',
					'event' : 'up'
				},
				{
					'style' : 'position:absolute;display:none;bottom:0px;right:0px;',
					'css' : 'menuboard_down',
					'icon' : ' ',
					'event' : 'down'
				}
			]			
			
		},
		
		'scrollbox' : {
			
			'opacity' : 0.5,
			'scrollmax' : 473,
			'side'		: 'horizontal',
			'animation' : {
				
				'side'		: 'right',
				'speed' 	: 2,
				'fade'		: false,
				'fadetime'	: 0.5
				
			},	
			'buttons' : [
				{
					'style' : '',
					'css' : 'scrollBox_left',
					'icon' : ' ',
					'event' : 'left'
				},
				{
					'style' : '',
					'css' : 'scrollBox_right',
					'icon' : ' ',
					'event' : 'right'
				}
			]
			
			
		},
		
		'topBox' : {
			
			'opacity' : 0.5,
			'scrollmax' : 230,
			'side'		: 'vertical',			
			'buttons' : [
				{
					'style' : 'display:none;',
					'css' : 'scrollBox_topbox_up',
					'icon' : ' ',
					'event' : 'up'
				},
				{
					'style' : 'display:none;',
					'css' : 'scrollBox_topbox_down',
					'icon' : ' ',
					'event' : 'down'
				}
			]			
			
		},
		
		'topScrollBox' : {
			
			'opacity' : 0.5,
			'scrollmax' : 200,
			'side'		: 'vertical',		
			'animation' : {
				
				'side'		: 'down',
				'speed'	 	: 2,
				'fade'  	: true,
				'fadetime'	: 0.5
				
			},			
			'buttons' : [
				{
					'style' : 'display:none;',
					'css' : 'scrollBox_topbox_up',
					'icon' : ' ',
					'event' : 'up'
				},
				{
					'style' : 'display:none;',
					'css' : 'scrollBox_topbox_down',
					'icon' : ' ',
					'event' : 'down'
				}
			]			
			
		}
		
	},
	
	initialize: function(pElement,pStyle,pDirect){// add pStyle
		
		this.element = $(pElement);
		this.style   = pStyle;
		
		this.buttons = [];
		
		tmpChilds = this.element.childElements();
				
		this.content = tmpChilds.first();

		if(pDirect === true){
			
			this.attachScrollbar();
			
		}else{
			
			Event.observe(window,'load',function(){
					
				this.attachScrollbar();
									
			}.bind(this));
		
		}
		
	},
	
	isReady: function(){
		
		if(empty(this.effect) || this.effect.state == "finished"){
			return true;
		}else{
			return false;			
		}
		
	},
	
	getStyle: function(){
		
		if(empty(this.styles[this.style])){
			zap.log('[attachScrollbar] Style not found!');
			return false;
		}else{
			
			return this.styles[this.style];
		}

	},

	attachScrollbar: function(){
		
		if(empty(this.content) || empty(this.element))
			zap.log('[attachScrollbar] Elements not found or not ready!');

		if(empty(this.styles[this.style])){
			zap.log('[attachScrollbar] Style not found!');
			return false;
		}
		
		needScroll = false;
		
		// vertical
		if(this.styles[this.style].side == 'vertical'){
			needScroll = (this.content.getHeight() > this.element.getHeight());			
		}
		
		// horizontal
		if(this.styles[this.style].side == 'horizontal'){
			needScroll = (this.content.getWidth() > this.element.getWidth());
		}

		if(needScroll){
			
			// loop buttons
			this.styles[this.style].buttons.each(function(section){

				tmpButton = Builder.node('div',
				{'style':section.style,'class':section.css}
				,section.icon);

				this.element.appendChild(tmpButton);

				tmpButton.observe('click',function(){
					this.move(section.event);
					
					if(this.animated){
						this.animated = false;
						this.stopAnimation();
					}
					

				}.bind(this));

				tmpButton.appear();
				
				this.buttons.push(tmpButton);

			}.bind(this));
			
			//animation
			if(isset(this.styles[this.style].animation)){
								
				this.animated = true;
				
				this.startAnimation();
				
				//add event to stop animation
				
				if(this.styles[this.style].animation.fade)
					this.addAnimationEvents();
	
			}

		}else{
			zap.log('[attachScrollbar] No Scroll needed for '+this.element.id);
		}

	},

	move: function(pWhere){
		
		if(this.isReady() === true){
		
			switch(pWhere){
				
				case"up":
					this.up();
				break;
				
				case"down":
					this.down();
				break;
				
				case"right":
					this.right();
				break;
				
				case"left":
					this.left();
				break;
	
			}
		
		}else{
			
			//zap.log('Plz w8!');
			
		}

	},
	
	
	getSizes: function(){
		
		tmpOffset = this.content.positionedOffset();
		
		tmpOffset.height = this.content.getheight();
		
		return tmpOffset;

	},
	
	up: function(){

		tmpStyle = this.getStyle();		
									
		tmpOffset = this.content.positionedOffset();
		
		tmpDistance = this.normalizeDistance(tmpOffset.top,0);
		
		if(tmpDistance.to != tmpDistance.from)		
			this.effect = new Effect.Move(this.content,{y:tmpDistance.to,mode: 'absolute'});
		else{
			
			if(this.animated){
				this.aniInvert = !this.aniInvert;
			}
			
		}
		
	},
	
	down: function(){
				
		tmpStyle = this.getStyle();		
			
		tmpOffset = this.content.positionedOffset();
		
		tmpDistance = this.normalizeDistance(tmpOffset.top,(this.element.getHeight()-this.content.getHeight()));
		
		if(tmpDistance.to != tmpDistance.from)	
			this.effect = new Effect.Move(this.content,{y:tmpDistance.to,mode: 'absolute'});
		else{
			
			if(this.animated){
				this.aniInvert = !this.aniInvert;
			}
			
		}

	},
	
	left: function(){
		
		tmpStyle = this.getStyle();		
									
		tmpOffset = this.content.positionedOffset();
		
		tmpDistance = this.normalizeDistance(tmpOffset.left,0);
				
		if(tmpDistance.to != tmpDistance.from)
			this.effect = new Effect.Move(this.content,{x:tmpDistance.to,mode: 'absolute'});
		else{
			
			if(this.animated){
				this.aniInvert = !this.aniInvert;
			}
			
		}

	},
	
	
	right: function(){
		
		tmpStyle = this.getStyle();		
			
		tmpOffset = this.content.positionedOffset();
				
		tmpDistance = this.normalizeDistance(tmpOffset.left,(this.element.getWidth()-this.content.getWidth()));
				
		if(tmpDistance.to != tmpDistance.from)	
			this.effect = new Effect.Move(this.content,{x:tmpDistance.to,mode: 'absolute'});
		else{
			
			if(this.animated){
				this.aniInvert = !this.aniInvert;
			}
			
		}
				
	},
	
	// From : actual position
	normalizeDistance: function(pFrom,pTo){
		
		tmpStyle = this.getStyle();
		
		if(tmpStyle !== false){
			
			if(pFrom >= pTo){
				tmpDistance = Math.abs(pFrom - pTo);
			}else{
				tmpDistance = Math.abs(pFrom + pTo);
			}

			if(!empty(tmpStyle.scrollmax) && (tmpDistance > tmpStyle.scrollmax)){
				
				if(pFrom >= pTo){
					
					tmpForm = pFrom - tmpStyle.scrollmax;
					
				}else{
					
					tmpForm = pFrom + tmpStyle.scrollmax;
					
				}
				
				return {'from':pFrom,'to':tmpForm};

			}else{
				return {'from':pFrom,'to':pTo};
			}
			
		}

	},
	
	
	animate: function(){
				
		if(this.aniInvert){
			tmpSide = this.invertSide(this.styles[this.style].animation.side);
		}else{
			tmpSide = this.styles[this.style].animation.side;
		}

		this.move(tmpSide);
		
		//zap.log('[animate] Side:'+tmpSide);
		
	},
	
	startAnimation: function(){
		
		this.interval = new PeriodicalExecuter(function(){
			
			if(this.styles[this.style].animation.fade)
				this.hideButtons();
				
			this.animate();
				
		}.bind(this), this.styles[this.style].animation.speed);
		
	},
	
	stopAnimation: function(){
		
		this.interval.stop();
		
		if(this.styles[this.style].animation.fade)
			this.showButtons();
		
	},
	
	
	invertSide:function(pWhere){
		
		switch(pWhere){
			
			case"up":
				return "down";
			break;
			
			case"down":
				return "up";
			break;
			
			case"left":
				return "right";
			break;
			
			case"right":
				return "left";
			break;
			
		}
		
	},
	
	hideButtons:function(){
	
		
		this.buttons.each(function(element){
			
			Effect.Fade(element,{duration:this.styles[this.style].animation.fadetime})
		
		}.bind(this));
		
		
	},
	
	showButtons: function(){
		
		this.buttons.each(function(element){
			
			Effect.Appear(element,{duration:this.styles[this.style].animation.fadetime})
		
		}.bind(this));
		
	},
	
	addAnimationEvents: function(){
		
		this.element.observe('mouseover',function(event){
				
				this.stopAnimation();
				
		}.bind(this));
		
		this.element.observe('mouseout',function(event){
				
				this.startAnimation();
				
		}.bind(this));
		
	}

});


/* ScrollBox */

zapScrollBoxCell = Class.create({
	
	id 		: null,
	element : null,
	url 	: null,
	caption : null,
	parent  : null,
	image	: null,
	ready	: null,
	
	initialize: function(pID,pElement,pData,pParent){
		
		this.id 		= pID;
		this.element 	= pElement;
		this.url 		= pData[0];
		this.caption 	= pData[1];
		this.parent 	= pParent;
		this.image		= new Image();
			
		if(!empty(this.element))
			this.addEvent();
	
	},
	
	
	addEvent: function(){
		
		$(this.element).observe('click',function(){
			
			this.loadImage();
			
		}.bind(this));
		
		$(this.image).observe('load',function(){

			this.displayImage();
				
		}.bind(this));
		
			
	},
	
	
	loadImage: function(){
		
		if(empty(this.image.src)){
					this.image.src = this.url;
			this.parent.loading();
		
		}else{
			this.parent.swtichImage(this);
		}
		
	},
	
	displayImage: function(){
		
		this.parent.swtichImage(this);

	}
	
	
	
});

zapScrollBox = Class.create({
	
	
	id			: 0,
	container 	: null,
	list 	 	: null,
	gallery		: null,
	cells		: null,
	collection  : null,
	loader		: null,
	active		: null,
	inactive	: null,
	animation	: true,
	caption		: null,
	
	initialize: function(pContainer){
		
		
		if($(pContainer))
		
			this.container = $(pContainer);
			
		else{
			
			zap.log('ERROR LOADING CONTAINER');
			return;
			
		}
		
		// init vars
		
		this.list = [];
		this.collection = new Hash();
		
		// get elements
		this.gallery = this.container.select('div.tools_scrollbox_gallery').first();
		this.gallerywrap = this.container.select('div.tools_scrollbox_gallery_container').first();
		this.loader = this.container.select('div.loader').first();
		this.cells = this.gallery.select('div.cell');
		this.caption = this.container.select('div.caption').first();
		
		
		//images
		this.active = this.container.select('div.active').first();
		this.activeIMG = this.active.select('img').first();
				
		this.inactive = this.container.select('div.inactive').first();
		this.inactiveIMG = Builder.node('img');
		this.inactive.appendChild(this.inactiveIMG);
		

		//this.loader.setOpacity(0.5);
		
	},
	
	addEvents: function(){
		
		
		for(var I=0;I<this.cells.size();I++){
			
			//zap.log(this.cells[I]);
			
			tmpElement = this.cells[I];
			
			this.collection.set(I,new zapScrollBoxCell(I,tmpElement,this.list[I],this));
			
			
		}
		
		
		this.animation = this.gallery.getWidth() > this.container.getWidth();

			
		this.container.select('div.next').first().observe('click',function(){
			this.goNext();
		}.bind(this));
		
		
		this.container.select('div.prev').first().observe('click',function(){
			this.goPrev();
		}.bind(this));
		
		
		
		
	},
	
	addCell: function(pImageSRC,pCaption){
		
		if(!empty(pImageSRC))
			this.list.push([pImageSRC,pCaption]);
		
	},
	
	loading : function(pID){
		
		//this.loader.appear({ duration: 0.5 });

	},
	
	swtichImage : function(pCell){
		
		tmpActiveIMG   = this.active.select('img').first();
		tmpInactiveIMG = this.inactive.select('img').first();

		tmpInactiveIMG.src = pCell.image.src;
		
		this.inactive.show();
		//fix
		this.inactive.setOpacity(1);
		
		new Effect.Fade(this.active, { duration: 0.2, afterFinish:function(){
			
			if(this.active.hasClassName('active'))
				this.active.removeClassName('active');
			
			tmpElement = this.inactive;
			
			this.inactive = this.active;
			this.active = tmpElement;
			
			this.active.addClassName('active');
			
		}.bind(this) });
			
		this.centerToElement(pCell.element);
		
		this.id = pCell.id;
		
		this.setCaption(pCell.caption);

	},
	
	setCaption: function(pString){
		
		if(!empty(pString)){
		
			this.caption.innerHTML = pString;
			this.caption.show();
			
		}else{
			
			this.caption.hide();
			
		}
		
	},
	
	goNext: function(){
		
		
		if(this.id < (this.cells.size()-1)){
			
			tmpCell = this.collection.get(this.id+1);
			
			tmpCell.loadImage();
			
		
		}else{
			
			tmpCell = this.collection.get(0);
			
			tmpCell.loadImage();
			
		}
		
	},
	
	goPrev: function(){
		
		if(this.id > 0){
			
			tmpCell = this.collection.get(this.id-1);
			
			tmpCell.loadImage();
			
		}else{
			
			tmpCell = this.collection.get((this.cells.size()-1));
			
			tmpCell.loadImage();
			
		}
				
	},
	
	centerToElement : function(pElement){
		
		this.animation = this.gallery.getWidth() > this.container.getWidth();
		
		if(!this.animation)
			return;		
		
		element = $(pElement);
		
		elW 		= element.getWidth();
		conW		= this.gallerywrap.getWidth();
				
		elOffset  	= element.positionedOffset()
		
		goLeft = Math.max(-this.gallery.getWidth()+conW,Math.min(0,-Math.round(elOffset.left-(conW/2)+(elW/2))));

		new Effect.Move(this.gallery, { x: goLeft, mode: 'absolute' });

	}
	
});


// Advanced Scrollbox

scrollBoxEffect = Class.create({
	
	element : null,
	
	initialize: function(pElement){
		
		this.elemenet = $(pElement);
		
	}
	
	
});

scrollBox = Class.create({
	
	container	: null,
	trigger 	: null,
	elements	: null,
	actual		: null,
	effect		: null,
	timer		: null,
	time		: 1,
	interval	: 3,
	animation 	: null,
	paused		: false,
	
	// pContainer = Element that holds cells
	// pCSSTrigger = CSS class that select cells
	initialize: function(pContainer,pCSSTrigger){
		
		this.container = $(pContainer);
		this.trigger = pCSSTrigger;
		
		this.elements = [];
		
		this.searchElements();
		
		this.actual = 0;
		
		this.animation = 'scroll';
		
		this.startAnimation();
		
	},
	
	searchElements : function(){
		
		tmpElement = this.container.select(this.trigger);
		
		if(tmpElement.size() > 0){
		
			this.elements = tmpElement;
		
		}
		
	},
	
	selectRandomElement: function(){
		
		return Math.floor(Math.random()*(this.elements.size()+1));
		
	},
	
	selectRandomAnimation: function(){
		
		animations = ['scrollright','fade','scrollleft','scrolltop','scrollbottom'];
		
		return animations[Math.floor(Math.random()*(animations.size()+1))];
		
	},
	
	nextElement: function(){
		
		if(this.actual == (this.elements.size()-1))
			return 0;
		else
			return (this.actual+1);
		
	},
	
	startAnimation: function(){
		
		this.timer =  new PeriodicalExecuter(function(){
			
			if(this.paused===true)
				return;
			
			if(this.animation == "random")
				tmpAnimation = this.selectRandomAnimation();
			else
				tmpAnimation = this.animation;
			
			switch(tmpAnimation){
				
				case"fade":
					this.fade(this.nextElement());
				break;
				
				case"scrollleft":
					this.scroll(this.nextElement(),'left');
				break;
				
				case"scrollright":
					this.scroll(this.nextElement(),'right');
				break;
				
				case"scrolltop":
					this.scroll(this.nextElement(),'top');
				break;
				
				case"scrollbottom":
					this.scroll(this.nextElement(),'bottom');
				break;
				
				case"scroll":
					this.scroll(this.nextElement(),'left');
				break;
				
				case"show":
					this.show(this.nextElement(),'left');
				break;
								
				default:
					this.fade(this.nextElement());
				break;
				
			}
				
		}.bind(this), this.interval);
		
		
	},
	
	selectNextAnimation: function(){
		
		
	},
	

	// fade from Element1 to Element2
	fade: function(pID){
			
		if(!this.prepareAnimation(pID))
			return;

		element1 = this.elements[this.actual];
		element2 = this.elements[pID];
		
		this.effect = new Effect.Appear(element2,{duration:this.time,afterFinish:function(){
				
				this.setStyle({zIndex:0});
				this.hide();
					
			}.bind(element1)
		});
			
		this.actual = pID;
	
	},
	
	scroll: function(pID,pSide){
		
		if(!this.prepareAnimation(pID))
			return;
		
		element1 = this.elements[this.actual];
		element2 = this.elements[pID];
				
		if(pSide == 'left'){
			element2.setStyle({'left':this.container.getWidth()+'px'});
		}else if(pSide == 'top'){
			element2.setStyle({'top':(0-this.container.getHeight())+'px'});
		}else if(pSide == 'bottom'){
			element2.setStyle({'top':this.container.getHeight()+'px'});
		}else{
			element2.setStyle({'left':(0-this.container.getWidth())+'px'});
		}
		
		element2.show();
		
		this.effect = new Effect.Move(element2, { x: 0, y: 0, mode: 'absolute',transition: Effect.Transitions.sinoidal, duration: this.time, afterFinish:function(){
				
				this.setStyle({zIndex:0,'left':0});
				this.hide();
					
			}.bind(element1)
		});
			
		this.actual = pID;
		
		
	},
	
	show : function(pID){
		
		if(!this.prepareAnimation(pID))
			return;

		element1 = this.elements[this.actual];
		element2 = this.elements[pID];
		
		element2.show();
		element1.hide();
		element1.setStyle({zIndex:0});;
		
		this.actual = pID;
		
	},

	prepareAnimation : function(pID){
		
			/*if(this.paused===true){
				zap.log("[scrollBox::prepareAnimation] Animation is paused");
				return false;
			}*/
		
			if(isset(this.effect) && this.effect.state != "finished"){
				zap.log("[scrollBox::prepareAnimation] Effect not ended");
				return false;
			}
				
			if(this.actual == pID){
				zap.log("[scrollBox::prepareAnimation] Object already actual");
				return false;
			}
			
			if(pID > (this.elements.size()-1)){
				
				zap.log("[scrollBox::prepareAnimation] Out of bounds");
				return false;
				
			}
			
			
			element1 = this.elements[this.actual];
			element2 = this.elements[pID];
			
			//move old element to transaction layer 
			element1.setStyle({zIndex:50});
			
			//move new element to top layer
			element2.setStyle({zIndex:100});
					
			return true;
		
	},
	
	gotoElement: function(pID,event){
		
		
		
		this.pauseAnimation();		
		this.show(pID);
		
	},
	
	pauseAnimation: function(){
		
		this.paused = true;
		
	},
	
	restartAnimation: function(){
		
		this.paused = false;
		
	},
	
	reset: function(pElement,event){
		
		element = $(pElement);
		
		if(!stillInsideParent(event,element))
			this.restartAnimation();
		
	}
	

});




/*-------------------------------------------------------------------------- 
 *		Zap MenuBook v1
 *  	(c) Zap S.A.
 *--------------------------------------------------------------------------*/


menuBookObject =  Class.create({
	
	container	: null,
	pages	 	: null,
	actual   	: null,
	active		: null,
	turner		: null,
	helper 		: null,
	fader		: {},
	cache		: null,
	ready		: true,
	
	initialize: function(pContainer,pGotoPage){
		
		this.actual = 0;
		
		this.container = $(pContainer);
		
		this.populate();
		
		this.cache = [];
		
		if(isset(pGotoPage)){
			
			section = Math.ceil(pGotoPage/2);
			
			this.go(section);
			
		}
		
	},
	
	
	populate: function(){
		
		this.pages = this.container.select('div.page');
				
		this.active = this.pages.slice(0,2);
				
		// Fader
		this.fader.container 	= 	this.container.select('div.fader').first();
		this.fader.inner 		= 	this.fader.container.select('div.inner').first();
		this.fader.shadow 		= 	this.fader.container.select('div.shadow').first();
		
		// Cleaner
		this.cleaner			= 	this.container.select('div.cleaner').first();
		
		this.addEvents();
			

	},
	
	addEvents: function(){
		
		//tabs
		$('menubook_tab_mdj').observe('click',function(){
			this.goMdj();
		}.bind(this));
		$('menubook_tab_index').observe('click',function(){
			this.goIndex();
		}.bind(this));
		$('menubook_tab_close').observe('click',deactivateConsole);
		
		this.container.select('div.next').each(function(element){
			element.observe('click',function(){
				this.next();
			}.bind(this))
		}.bind(this));
		
		this.container.select('div.prev').each(function(element){
			element.observe('click',function(){
				this.prev();
			}.bind(this))
		}.bind(this));
		
		
	},
		
	next: function(){
		

		if((((this.actual+1)*2) < this.pages.size()) && this.ready){
			
			this.ready = false;
						
			tmppages = this.pages.slice(((this.actual+1)*2),((this.actual+1)*2)+2);
						
			newPages = tmppages;
			oldPages = this.active;
						
			this.cache = [oldPages,newPages];
			
			//prepare pages in layout
			this.preparePages();
			
			//prepare fades
			this.prepareFader('right');
			
			this.turnFade('right');
			
			this.active = tmppages;
			this.actual++;
			
		}
				
	},
	
	prev: function(){
		
		if((this.actual > 0) && this.ready){
			
			this.ready = false;
			
			tmppages = this.pages.slice(((this.actual-1)*2),((this.actual-1)*2)+2);
								
			newPages = tmppages;
			oldPages = this.active;
				
			this.cache = [oldPages,newPages];
			
			//prepare pages in layout
			this.preparePages();
			
			//prepare fades
			this.prepareFader('left');
			
			this.turnFade('left');
			
			this.active = tmppages;
			
			this.actual--;
			
		}	
		
		
	},
	
	
	turnFade: function(pSide){
		
		var effectDuration = 0.8;
		

		if(pSide=="right"){

			var xVal = -17;
					
	    }else{
	    	
	    	var xVal = 384;

		}
		
		var effectList = [
		
				new Effect.Move(this.fader.container, { sync: true, x: xVal, y: 0, mode: 'absolute'}),
				new Effect.Morph(this.fader.inner, { sync: true, style : 'width:383px;'}),
				new Effect.Morph(this.cleaner, { sync: true, style : 'width:0px;'})
				//new Effect.Opacity(this.fader.shadow, { sync: true, from:1.0, to: 0.01, delay:0.5 })
				//new Effect.Fade(this.fader.shadow, { sync: true, delay:0.5 })
		];
		
		//dont fade shadow in IE
		if(!Prototype.Browser.IE)
			effectList.push(new Effect.Fade(this.fader.shadow, { sync: true, delay:0.5 }));
		
		
		new Effect.Parallel(effectList,{ 
			
		   duration: effectDuration,
		   afterFinish: function(){
		   		    	
		   	this.resetFader();
		   	
		   }.bind(this)
		   
		});
		 
		
	},
	
	preparePages : function(){
		

		oldpages = this.cache[0];

		oldpages.each(function(element){
			
			element.setStyle({zIndex:20});		
		});
		
		newpages = this.cache[1];
		
		newpages.each(function(element){
			
			element.setStyle({zIndex:15});
			element.show();
			
		});
		
	},
	
	prepareFader: function(pSide){
		
		//fader_left
		//cleaner_left
		
		oldpages = this.cache[0];
		newpages = this.cache[1];
		

		// set CSS if needed
		if(pSide == 'right'){
			if(this.cleaner.hasClassName('cleaner_left'))
				this.cleaner.removeClassName('cleaner_left');
			if(this.fader.container.hasClassName('fader_left'))
				this.fader.container.removeClassName('fader_left');
		}else{
			this.cleaner.addClassName('cleaner_left');
			this.fader.container.addClassName('fader_left');
		}
		
		this.cleaner.show();
		
		// page to move to fader
		if(pSide == 'right'){
					
			if(oldpages.size()>1){
				cleanerPage = oldpages[1];
				cleanerPage.setStyle({'left':'0px','right':'auto'});
			}
			
			faderPage = newpages[0];
			this.cleaner.even = true;
			this.fader.even = true;
			faderPage.setStyle({'left':'0px','right':'auto'});
			
			if(oldpages.size()>1)
				this.cleaner.appendChild(cleanerPage);
								
			this.cleaner.setStyle({'width':'290px','left':'384px','right':'auto'});	
			this.fader.container.setStyle({'left':'650px'});
			
		}else{

			newpages[0].setStyle({'left':'0px','right':'auto'});
			
			cleanerPage = oldpages[0];
			faderPage = newpages[1];
			
			this.cleaner.even = false;
			this.fader.even = false;
			
			faderPage.setStyle({'left':'auto','right':'0px'});
			cleanerPage.setStyle({'left':'auto','right':'0px'});
			
			this.cleaner.appendChild(cleanerPage);
							
			this.cleaner.setStyle({'width':'290px','left':'auto','right':'384px'});	
			
			this.fader.container.setStyle({'left':'52px'});
			
		}
		
		
		this.fader.container.show();
		this.fader.inner.appendChild(faderPage);
		
	},
	
	resetFader: function(){

		oldpages = this.cache[0];
		newpages = this.cache[1];

		
		//tabs
		
		//reset tabs
		
		$('menubook_tabs').select('div.tabactive').each(function(element){
			
			
			element.removeClassName('tabactive');
			
		});
		
		switch(this.actual){
		
			case 0:
				$('menubook_tab_index').addClassName('tabactive');
			break;
			
			case Math.ceil((this.pages.size()-2) / 2):
				$('menubook_tab_mdj').addClassName('tabactive');
			break;
		
		}
		
		
		//reset faded page
		newpages.each(function(element){
			element.setStyle({zIndex:20});
		});
		
		oldpages.each(function(element){
			element.setStyle({zIndex:15});
		});
		
		
		// page to move to fader
		if(!this.fader.container.hasClassName('fader_left')){
			
			if(oldpages.size()>1){
				cleanerPage = oldpages[1];
				cleanerPage.setStyle({'right':'0px'});
			}
			

			faderPage = newpages[0];
			faderPage.setStyle({'right':'0px'});

		}else{
			
			cleanerPage = oldpages[0];
			faderPage = newpages[1];
			
		}
		
		
		//move to place
		this.container.appendChild(faderPage);
		
		oldpages.each(Element.hide);
		
		oldpages.each(function(element){
			
			element.setStyle({zIndex:0});
						
		});
		
		if(oldpages.size()>1){
			this.container.appendChild(cleanerPage);
		}
		
		// clean helpers
		
		this.cleaner.hide();
		this.fader.container.hide();
		this.fader.inner.setStyle({'width':'50px'});
		this.fader.shadow.show();
		this.ready = true;
		this.cache = [];
		
	},
	
	go: function(pSection){
		
		if(this.actual == pSection)
			return; 
		
		// section to load
		section = pSection;
				
		this.ready = false;
		
		position = (section)*2;

		// slice	
		newPages = this.pages.slice(position,position+2);
		
		oldPages = this.pages.slice((this.actual*2),(this.actual*2)+2);
				
		this.cache = [oldPages,newPages];
			
		//prepare pages in layout
		this.preparePages();
		
		//prepare fades
		this.prepareFader('right');
		this.turnFade('right');
				
		this.active = newPages;
		this.actual = section;				
	},
	
	goPage: function(pPage){
		
		section = Math.ceil(pPage/2);
						
		this.go(section);
		
	},
	
	goMdj: function(){
				
		section = Math.ceil((this.pages.size()-2) / 2);
		
		this.go(section);
	},
	
	goIndex: function(){
		
		if(this.actual > 0){

			// section to load
			section = 0;
					
			this.ready = false;
												
			newPages = this.pages.slice(0,2);
			oldPages = this.active;
					
			this.cache = [oldPages,newPages];
				
			//prepare pages in layout
			this.preparePages();
			
			//prepare fades
			this.prepareFader('left');
			this.turnFade('left');
					
			this.active = newPages;
			this.actual = section;	
		
		
		}
			
	}
		
});




// -- Navigation -- Zap S.A. 2009


/* 

	Homebase navigation

*/

usernavigation = {
	
	tabs : [],
	timer : null,
	tick : null,
	tabsContainer : null,
	pagesContainer : null,
	
	init : function(){
		
		//tabsContainer
		this.tabsContainer = $('usernavigation_tabs_container');
		
		//pagesContainer
		this.pagesContainer = $('usernavigation_pages_container');
		
		//tick
		this.tick = $('usernavigation_tabs_tick');
		
		//start
		this.addTabs();
		
		
	},
	
	addTabs : function(){
		
		
		tmpTabs = this.tabsContainer.select('.usernavigation_tab');
		tmpPages = this.pagesContainer.select('div.usernavigation_page');
		
		for(var I=0;I<tmpTabs.size();I++){
			
			// create a new tab instance
			this.tabs.push(new usernavigation_tab(tmpTabs[I],tmpPages[I]));
			
		}
		
	},
	
	showElement: function(pTab){
		
		
		tmpTab = pTab;
		
		for(var I=0;I<this.tabs.size();I++){
			
			if(this.tabs[I] != tmpTab)
				this.tabs[I].hideContent();
			
		}
		
		//movetic
		this.moveTickTo(tmpTab.element);
		
		// show	
		tmpTab.showContent();

	},
	
	delayShowElement: function(pTab){
		
		
		
		
	},
	
	moveTickTo: function(pElement){
		
		element = $(pElement);
		
		if(!empty(element))
			this.tick.setStyle({'left':element.getStyle('left')});
		
		
	},
		
	addEvents:function(){
		
		
		
		
	}
	
}

usernavigation_tab = Class.create({
	
	element : null, // actual tab
	id 		: null,
	content : null,
	hidden   : [],
	
	initialize: function(pElement,pContent){
		
		this.element = $(pElement);
		this.content = $(pContent);
		
		this.id = $(pElement).identify();	
		
		this.addEvent();
				
	},
		
	addEvent: function(){
		
		this.element.observe('mouseover',function(event){
			
			this.delayMakeActive();
			
			
		}.bind(this));
		
		
		this.element.observe('mouseout',function(event){
					
			//clear timer
			clearTimeout(usernavigation.timer);
			
		}.bind(this));
		
		
		this.content.observe('mouseover',function(event){
			
			//clear timer
			clearTimeout(usernavigation.timer);
			
			//show hidden elements
			this.hidden.each(Element.show);
			
		}.bind(this));
		
		
	},
	
	makeActive: function(){
		
		usernavigation.showElement(this);
		
	},
	
	delayMakeActive: function(){
		
		usernavigation.timer = window.setTimeout(function(){
				
				//this.showContent();
				usernavigation.showElement(this);
				
		}.bind(this),150);

	},
	
	showContent: function(){
		
		this.content.show();
		
	},
	

	hideContent: function(){
		
		this.content.hide();
		
	},
	
	isContentVisible: function(){
		
		this.content.visible();
		
	}
	
});

//clear bubbling effect
unBubble = function(event){
	
	if (!event) var event = window.event;
	event.cancelBubble = true;
	if (event.stopPropagation) event.stopPropagation();

}

// hide/show Elements in parent with specifique CSS Selector
toggleHidenClassName = function(pParent,pCSSSelect,pState){
	
	if(pState){
		$(pParent).select(pCSSSelect).each(Element.show);
	}else{
		$(pParent).select(pCSSSelect).each(Element.hide);
	}
		
}

tagSlicedMenuLinks = function(){
		
	var links = $(window.document.body).select('a.slicedlink');
	
	links.each(function(element){
				
		element.observe('mouseover',function(event){
			
			toggleSlicedMenuLinks(event);
			
		});
		
	
	});
}

toggleSlicedMenuLinks = function(event,pState){
	
	var element = Event.element(event);
	
				
		var tmpElement = Builder.node('div',{'style':'position:absolute;','class':'slicedlinkhelper'},[Builder.node('a',{'href':element.href,'class':'text'},element.rel)]);
			
		tmpElement.clonePosition(element,{setWidth:false});
		
		tmpElement.observe('mouseout',function(event){
						
			var element = Event.element(event);
			
			if(!element.hasClassName('slicedlinkhelper')){
				
				parent = element.up();
				
				if(parent.hasClassName('slicedlinkhelper')){
					parent.remove();	
				}
				
			}else{
				element.remove();
			}
			
		});
		
		window.document.body.appendChild(tmpElement);
}


/* ZAPON STARTPAGE */

zaponStartpageSwtich = {
	
	tabs : new Hash(),
	lastactive : null,
	clear : true,
	timer : null,
	interval : null,
	waittime : 3000,
	
	attachEventTo : function(pElement,pElemementsArray){
		
		element = $(pElement);
		
		if(element != null){
			
			//this.tabs[element.id] = pElemementsArray;
			this.tabs.set(element.id,pElemementsArray);
						
			element.observe('mouseover',function(event){
				
				element = Event.element(event);
								
				if(!empty(element.id)){
					this.showID(element.id);
				}
					
			}.bind(this));
			
			//this.startRandom();
			
		}
				
	},
	
	goToURL: function(pElementID){
		
		element = $(pElementID);
		
		if(element.tagName == "A"){

			location.href = element.freh;
			
		}
		
	},
	
	showID: function(pID){
		
		this.show(pID);
		this.wait();
		
	},
		
	show: function(pID){
				
		var tmparray = [];
		
		//hide old
		tmparray = this.tabs.get(this.lastactive);
		tmparray.each(Element.hide);
		
		//reset
		var tmparray = [];
		
		// show new
		tmparray = this.tabs.get(pID);
		tmparray.each(Element.show);
		
		this.lastactive = pID;
			
	},
		
	stopRandom: function(){
		
		window.clearTimeout(this.interval);

	},
	
	startRandom: function(){
			
		
		this.interval = window.setInterval(function(){
			
			this.showNext();
			
		}.bind(this),this.waittime);		
				
	},
	
	showNext: function(){
				
		tmpArray = this.tabs.keys();
		
		tmpPos = tmpArray.indexOf(this.lastactive);
				
		if(tmpPos > -1){
			
			
			if((tmpPos+1) == tmpArray.length){
				
				tmpPos = 0;
			
			}else{
				
				tmpPos++;
			}

			this.show(tmpArray[tmpPos]);
		
		}
		
	},
	
	wait : function(){
				
		window.clearTimeout(this.timer);
		this.stopRandom();
		
		this.timer = window.setTimeout("zaponStartpageSwtich.clearWait()",(this.waittime*2));
				
	},
	
	clearWait: function(){
						
		this.startRandom();

	}
	
}

elementListShow = Class.create({
	
	list : null,
	lastvisible : null,
	
	initialize: function(pList){
		
		this.list = new Hash();
		
		tmpArray = [];
		tmpArray = pList;
				
		tmpArray.each(function(element){
			
			this.list.set(element.id,element);
		
		}.bind(this));
		
	},
	
	show: function(pID){
			
		if(this.lastvisible != pID){
			
			if(this.list.get(pID)){
				
				this.list.values().invoke('hide');
				
				tmpElement = this.list.get(pID);
				
				tmpElement.show();
				
			}

		}
	}
	
});


