//wm namespace and global object singleton
var mm = new Hash({
	options: new Hash({
		indexLevel:0
	}),	
	version: '0.0.1'
	, loginPollInterval: (30*1000) 	// miliseconds interval for loginpoll when loggedin   600000
	, preloadImages: [
			'/_img/icons/notice_info_ok.png'
			, '/_img/icons/warning.png'
			, '/_img/buttons/actionbutton2.png'
			, '/_img/icons/action_21x21close.png'
			, '/_img/icons/action_21x21ok.png'
		]
});
 /*
	mm.main
	main singleton object
*/

mm.main = {
	myvar: 'a string property of the main object' 
	, testMe:function() {
// dbug.log('testing the main singleton object myvar='+this.myvar);
	},
	init: function(request) {
		//if (!$defined(request)) { this.request = false; } else { this.request = request; }
		this.requestType = $defined(mm.runtime.requestType) ? mm.runtime.requestType : false ;
		this.request = $defined(mm.runtime.request) ? mm.runtime.request : false ;		
		this.bound = this.bound||{};
		this.unloading = false;
		this.setupDefaultObjects();
		this.setupDefaultEvents();
	},
	setupDefaultEvents: function() {
		// test ff animated gif
		if (Browser.Engine.gecko) {
			document.addEvent('keydown', function(e) { if (e.key=='esc') { e.preventDefault(); } });
		}		
		if (Browser.Engine.trident4) {
			// ie6 background image anti-flicker
   			document.execCommand("BackgroundImageCache",false,true);			
		}
		this.bound.beforeUnLoad = this.beforeUnLoad.bindWithEvent(this);		
		this.bound.unLoad = this.unLoad.bindWithEvent(this);			
		this.bound.resizeWin = this.resizeWin.bindWithEvent(this);
		window.onbeforeunload = this.bound.beforeUnLoad;
		window.addEvents({
			'beforeunload':this.bound.beforeUnLoad
			, 'unload':this.bound.unLoad
			,'resize':this.bound.resizeWin
		});		
		
	},
	setupDefaultObjects: function() {
		mm.notimoo = new Notimoo({
//		   parent: document.id('maintop')
		   locationVType: 'top'
		   , locationHType: 'right'
			, visibleTime: 2000
		});
		mm.noticeInfo = new Notimoo({		
			locationVType: 'top'			
			, locationHType: 'right'
			, locationVBase: 20
			, locationHBase: 20			
			, className: 'noticeInfo'
			, visibleTime: 2000
		});
		mm.noticeError = new Notimoo({		
			locationVType: 'top'			
			, locationHType: 'right'
			, locationVBase: 20
			, locationHBase: 20			
			, className: 'noticeError'
			, visibleTime: 2000
		});
		if (mm.runtime.loggedin && this.requestType == 'app') {
			this.setupAppObjects();
			this.preloadAppImages();
		} else {
			this.setupPublicObjects();			
		}
		
			//mm.signup = new mm.SignupClass({'signupContainer':'wmSignupContainer', 'multiplier':mm.runtime.signup.multiplier});
	},
	setupPublicObjects: function() {
		//mm.login = new mm.LoginClass({'loginContainer':'wmLoginContainer', 'requestType':mm.runtime.context.requestType, 'multiplier':mm.runtime.login.multiplier});		
// dbug.log('main setupPublicObjects request = '+this.request);


		mm.homeTabs = new mm.Tabs('div.tabsContainer div.tabPanel', 'div.tabsContainer ul.tabButtons li', {
			useFade: true, useHover: true, fadeProps:{duration:400, transition:'circ:in:out'}
		});	

		if (this.request != 'verify' && this.request != 'quit') {
			mm.login = new mm.LoginClass({multiplier:mm.runtime.login.multiplier, requestType:mm.runtime.context.requestType});
		} else {
			//mm.verify = new mm.VerifyClass({multiplier:mm.runtime.verify.multiplier});
			if (this.request == 'verify') {
				this.setupVerifyForm();
			}
		}
		if(this.request == 'signup') {
			mm.signup = new mm.SignupClass({multiplier:mm.runtime.signup.multiplier});			
		}
		mm.overlayAll = new mm.OverlayAllClass({'element':'mmOverlayAll'});					
		var dialogLinks = $$('a.dialogLink');
		if (dialogLinks.length > 0) {
			dialogLinks.each(function(link) {
				var href = link.get('href');
				link.set('href', '#');
				link.addEvent('click', function(e) {
					e.stop();
					mm.overlayAll.showPublicDialog(href);
				});
			});
		}
		
// dbug.log('REQUEST = '+this.request);
//		if (this.request == 'index') {
			var screenThumbs = $$('a.screenshotThumb');
// dbug.log('screenthumbs = '+screenThumbs);			
			if (screenThumbs.length > 0) {
				screenThumbs.each(function(th) {
					th.setStyle('opacity',0.5).set('tween', {duration:700, transition:'expo:out'});
					th.addEvents({
						'mouseenter':function(e) { th.fade(1); }
						, 'mouseleave':function(e) { th.fade(0.5); }
					});
				});
			}
//		}		
		var hash = '';
		if (window.location.hash != '') { hash = window.location.hash; }
//		if (hash !='') { alert(hash); }
		if (hash == '#video') {
			Mediabox.open.delay(1000, Mediabox, ['https://www.youtube.com/watch?v=6PqcG5kqAPI', '', '853 505']);	
		}
		if (hash == '#subscribe') {
			mm.overlayAll.showPublicDialog.delay(1000, mm.overlayAll, '/subscribe');
		}
		if (hash == '#voorwaarden' || hash == '#terms') {
			mm.overlayAll.showPublicDialog.delay(1000, mm.overlayAll, '/terms');
		}			
		
		this.setupTwitterLatest();
		
	}
	
	, setupTwitterLatest:function() {
			var slideShow = false;
			var twitterSlides = document.id('twitterSlides');
			var myEffect = new Fx.Morph('twitterSlides', {duration: 700, transition: Fx.Transitions.Sine.easeOut, unit:'%'});

			if (twitterSlides) {
				new Request.TwitterSearch('moneymedic', {
					url:'https://twitter.com/search.json?q={term}&rpp=50'
					, onSuccess: function(rJson, rText) {
		//	dbug.log(rJson);		
						if (rJson.results) {
							twitterSlides.empty();
							rJson.results.each(function(tweet) {
								var randomDuration = 5000;
								var randomFontSize = 20; // + (Math.random()*12);
								var randomTop = 0 + Math.random()*200;
								//transition:crossFade duration:5000
								var twContainer = new Element('div', {'class':'tweetContainer '});
								var us = '<a href="http://twitter.com/'+tweet.from_user+'" target="_blank" style="color: #737373; font-style:normal;">'+tweet.from_user+':</a>';
								var imgsrc = tweet.profile_image_url;
								var imgtag = '<a href="http://twitter.com/'+tweet.from_user+'" target="_blank"><img src="/_rimg/'+imgsrc+'" class="twitterUserImage" border="0" /></a> ';
								//var theText = imgtag+'&nbsp;'+us+'&nbsp;&nbsp;<em>"'+tweet.text+'</em>"';
								var theText = us+'&nbsp;&nbsp;<em>"'+tweet.text+'</em>"';  // no image because of ssl conflicts 
								//.setStyles({'font-size':randomFontSize}).
								var twText = new Element('div', {'class':'tweetText'}).set('html',theText ).inject(twContainer);
								twContainer.inject(twitterSlides).setStyles({'top':randomTop+'px'});
							});

							slideShow =  new SlideShow('twitterSlides',{
								delay: 10000
								, duration: 1500
								, autoplay: true
								, transition: 'fadeThroughBackground'
								, onShow: function() {
		//dbug.log('show');							
									//myEffect.start({'width':'40%', 'opacity':0.4});
								}
								, onShowComplete: function () {
		//dbug.log('showComplete');			

									//var randomWidth = 40 + (Math.random()*60);
			//						twitterSlides.tween('width', randomWidth+'%');
									//myEffect.start({'width':[ '40%' ,randomWidth+'%'], 'opacity':[0.4,1] });							
								}
							});				
						}
					}
					, onRequest: function() {
		//	dbug.log('starting twitter request');				
					}
				}).send();
			}		
	}
	, setupAppObjects: function() {
		mm.overlayAll = new mm.OverlayAllClass({'element':'mmOverlayAll'});		
		mm.loginPoll = new mm.LoginPollClass({interval:mm.loginPollInterval});
		
	//	mm.roar = new Roar({position: 'upperRight'});
		//mm.loginPoll = new mm.LoginPollClass({interval:mm.loginPollInterval});
		mm.ajax = new mm.AjaxControllerClass({});
		if (mm.runtime.noticeInfo) {
			mm.noticeInfo.show({title:mm.runtime.noticeInfo});
		}
		if (mm.runtime.noticeError) {
			mm.noticeError.show({title:mm.runtime.noticeError});
		}		
		if (mm.runtime.highlightId) {
// dbug.log('>>> highlightId = '+mm.runtime.highlightId);
		}				

		
	},
	setupVerifyForm:function() {
// dbug.log('setupVerifyForm');
		this.verifyFormContainer = document.id('verifyFormContainer');
		this.verifyForm = document.id('verifyForm');
		this.verifyForm.addEvent('submit', function(e) { return false; });		
		this.verifyHidden = this.verifyForm.getElement('#verify_doverify');
		this.verifyFormkey = this.verifyForm.getElement('#verify_formkey');
		this.verifyHash = this.verifyForm.getElement('#verify_hash');	
		this.signupNoticeIconOk = document.id('signupNoticeIconOk');
		this.signupNoticeIconInfo = document.id('signupNoticeIconInfo');
		this.signupNoticeIconLoading = document.id('signupNoticeIconLoading');
		this.signupNoticeIconError = document.id('signupNoticeIconError');				
		this.signupNoticeIcons = [this.signupNoticeIconOk, this.signupNoticeIconInfo,this.signupNoticeIconLoading,this.signupNoticeIconError];
		this.signupNoticeText = document.id('signupNoticeText');						
		this.submitVerifyForm.delay(3000,this);			
	},
	submitVerifyForm:function() {
		var qs = this.verifyForm.toQueryString();
		var qsdata = qs.parseQueryString(); 
//dbug.log('org formkey = '+qsdata.formkey+ ' multiplier = '+mm.runtime.verify.multiplier+' new multiplied key = '+(qsdata.formkey * mm.runtime.verify.multiplier));		
		qsdata.formkey = qsdata.formkey * mm.runtime.verify.multiplier;
		if (qsdata.hash) {
			qsdata.hash = Base64.encode(qsdata.formkey+qsdata.hash+qsdata.formkey);
		}
// dbug.log(qsdata);		
		new Request.JSON({
			url: '/_x/verify'
			, data: qsdata
			, method: 'post'
			, link: 'ignore'			
			, noCache: true
			, onSuccess: function(rJson, rText) {
				this.verifyRequestSucces.delay(3000, this, [rJson, rText]);
			}.bind(this)
			, onRequest: function() {
				this.verifyRequestStart();
			}.bind(this)
			, onFailuer: function() {
				this.verifyRequestFailure();
			}.bind(this)
		}).send();		
	},
	verifyRequestSucces:function(rJson, rText) {
// dbug.log('verifyRequestSucces:');
// dbug.log(rJson);
		this.signupNoticeIcons.each(function(icon) {
			icon.setStyle('display','none');
		});
		if (rJson.verify) {
			this.signupNoticeIconOk.setStyle('display','block');
			if ($defined(rJson.verify.portal) && rJson.verify.portal!='') {
				this.signupNoticeText.set('html', '<strong>Uw account is succesvol geverifieerd.</strong> U wordt nu automatisch doorgestuurd.');										
				(function() { window.location.href = rJson.verify.portal+'login'; }).delay(3000,this);				
			} else {
				this.signupNoticeText.set('html', '<strong>Uw account is succesvol geverifieerd.</strong> U wordt nu automatisch doorgestuurd.');										
				(function() { window.location.href = 'https://www.moneymedic.eu/login'; }).delay(3000,this);				
			}
		} else {
			this.signupNoticeIconInfo.setStyle('display','block');
			if (mm.runtime.loggedin && mm.runtime.auth.portal!='') {
// dbug.log('loggedin, portal = '+mm.runtime.auth.portal);					
				(function() { window.location.href = mm.runtime.auth.portal; }).delay(3000,this);
			} else {			
				this.signupNoticeText.set('html', '<strong>Uw account is reeds geverifieerd.</strong> U wordt nu automatisch doorgestuurd.');			
				(function() { window.location.href = 'https://www.moneymedic.eu/login'; }).delay(3000,this);						
			}
		}
	},
	verifyRequestStart:function() {
		this.signupNoticeIcons.each(function(icon) {
			icon.setStyle('display','none');
		});
		this.signupNoticeIconLoading.setStyle('display','block');	
		//this.signupNoticeText.set('html', 'Accountgegevens verifieren.');			
	},
	verifyRequestFailure:function() {
		this.signupNoticeIcons.each(function(icon) {
			icon.setStyle('display','none');
		});
		this.signupNoticeIconError.setStyle('display','block');
		this.signupNoticeText.set('html', 'De verificatie is niet gelukt.');	
	},
	validateAccountNumber:function(num, giro) {
		if (!$defined(giro)) { giro = false; }
		num = num.replace(/\D/, "");
		if (num=='123456789' || num=='1234567890' || num.toInt() == 0) { return false; }
		if (giro) {
			//giro?
			if (num.length >=3 && num.length < 8 ) {
				return true;
			} else {
				return false;				
			}			
		} else {
			if (num.length >= 9 ) {
				// verwijder alle tekens die geen cijfers zijn

				aantal_tekens = num.length;
				var som=0;
				// loop door de 9 cijfers met de 11 proef formule
				for (i=1; i<10; i++) {
					var getal = num.charAt(i-1).toInt();
					som += getal*(10-i);
				} 
				// geef resultaat van check terug
				if (som % 11==0 && (aantal_tekens==9 || aantal_tekens==10)) {
					return true;
				} else {
					return false;
				}		
			} else {
				return false;
			}			
		}
	},	
	preloadAppImages:function() {
		mm.preloadImages.each(function(img) {
// dbug.log('preloading app images:'+img);			
			new Image().src = img;
		},this);
	},
	logout: function() {
		//alert('logout');
		mm.overlayAll.showDialog('logout', 'logout_confirm');
	},
	logoutCleanup: function() {
		mm.runtime.loggedin = false;		
		mm.loginPoll.stopPoller();
		// delete cookie
		if ($defined(mm.runtime.auth.cookieName) && mm.runtime.auth.cookieName!='') {
			Cookie.dispose(mm.runtime.auth.cookieName);
		}		
	},	
	beforeUnLoad: function(e) {
		// everything returned from this function will be interpreted as a string in the onbeforeunload confirm dialog, cannot be surpressed !
		    //return 'you leaving?'
		// if (mm.overlayAll.isOpen) { mm.overlayAll.hide(); }	
		// NOT SUPPORTED BY OPERA !	
		/*
dbug.log('wmMain beforeUnLoad');		
		if (mm.runtime.loggedin && (mm.runtime.auth.uniqueName == mm.runtime.context.designerUniqueName)) {
			mm.overlayAll.show(true);  // immediately 	
			if (mm.overlayAll.isDialogOpen)	{ mm.overlayAll.hideDialog(false); }	
			mm.overlayAll.showNotice('loading', mm.lang.notice.loading_confirmunload);
			mm.overlayAll.hide.delay(5000,mm.overlayAll);
			return 'beforeunloadstring?';
			//mm.unloadcheck = 'ja';
//dbug.log(mm.unloadcheck);						
		}
		*/
// dbug.log('unloading');		
		this.unloading = true;
	},
	unLoad: function(e) {
		// LAST PLACE TO DO ANYTHING, BUT SHOULDN'T TAKE too LONG
// dbug.log('wmMain unLoad');		
		if (!mm.runtime.loggedin) {
			if ($defined(mm.runtime.auth.cookieName) && mm.runtime.auth.cookieName!='') {
				Cookie.dispose(mm.runtime.auth.cookieName);
			}
		}
	},
	resizeWin: function(e) {
// dbug.log('wmMain resizeWin');		
	}
	
	
	
};

// extending the main object to have events
$extend(mm.main, new Events());

mm.main.addEvent('test', function() {
	this.testMe();
}); mm.utils = {
	
	queryStringToObject:function(qs) {
		var res = new Hash({});
		if (qs == null) qs = location.search.substring(1, location.search.length);
		if (qs.length == 0) return;

	// Turn <plus> back to <space>
	// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
		qs = qs.replace(/\+/g, ' ');
		var args = qs.split('&'); // parse out name/value pairs separated via &

	// split out each name=value pair
		for (var i = 0; i < args.length; i++) {
			var pair = args[i].split('=');
			var name = decodeURIComponent(pair[0]);

			var value = (pair.length==2)
				? decodeURIComponent(pair[1])
				: name;
			if (value == null || value == 'null') { value = ''; }
			res.set(name, value);
//dbug.log('queryStringToObject name='+name+' value='+value);			
		}		
		return res;
	}

}; FormValidator.add('validate-wmpassword', {
    errorMsg: 'The password does not match the password criteria',
    test: function(element){
        if (element.value.length < 8) return false;
        else return true;
    }
});  
/*
SimpleSelectStyle v.1.2
Simple select tag styling; cosmetic only.
 
Author: Ben Stilson
 
Required:
- CSS class for styling the alternate "select" span / select tags
- option select_class must be defined with CSS class name
- specify a select width, either in the CSS class or directly to the select tag
- use only with single line selects (size=1/default)
 
Optional:
- to use with all selects in an entire form, provide the form id for the option form_id
- left_padding is used to add left padding (indent) before the text in the span element, defaults to 3px
 
Demo:
http://vault.hanover.edu/~stilson/simpleselectstyle/
mooForum:
http://www.mooforum.net/scripts12/simpleselectstyle-t1053.html

*/
mm.SelectStyledClass = new Class(
{
    Implements: Options,
   
    options : {   
		parentEl : false, // element
		default_class : '',
        select_class : '',
        form_id : '',
        left_padding : 5,
		border_radius: 3
    },
   
    initialize: function(options) {
        this.setOptions(options);
		if ($chk(this.options.select_class)) {          
			if ($chk(this.options.parentEl)) {
				this.selects = $(this.options.parentEl).getElements('select[class~='+this.options.select_class+']');
			} else {			
            	this.selects = $chk($(this.options.form_id)) ? $(this.options.form_id).getElements('select') : $$('select.'+this.options.select_class) ;
			}
            this.selects.each(this.style_selects.bind(this));
        }
    },
   
    style_selects : function(select_el)
    {      
		var parents = select_el.getParents();
		parents.each(function(parent) {
			var old_display = parent.getStyle('display');			
			if (old_display=='none') {
				parent.setStyle('display','block').store('tmp_old_display_select_styled', old_display);
			}
		});
		select_el.setStyles({'display':'block'});
		var size = select_el.getSize();
		var select_el_height = size.y;
        var select_el_width = size.x;   
        var value = select_el.getFirst().get('value');     
        var text = select_el.getFirst().get('text');
   
        select_el.getElements('option').each(function(o){ if(o.selected == true){ value = o.get('value'); text = o.get('text'); } });
       
        var span = new Element('span',{'class':this.options.select_class}).set('text',text).inject(select_el,'before').setStyles({'z-index':0,'cursor':'pointer','width':select_el_width - this.options.left_padding,'display':'inline-block','height':select_el_height,'line-height':select_el_height,'overflow':'hidden','position':'relative','padding-left':this.options.left_padding});
       
        select_el.addClass(this.options.select_class).setProperty('size',1).setStyles({'display':'block','width':select_el_width + span.getStyle('border-left-width').toInt() + span.getStyle('border-right-width').toInt(),
'opacity':.01,'display':'inline-block','position':'relative','margin-left':-(select_el_width + span.getStyle('border-left-width').toInt() + span.getStyle('border-right-width').toInt())}).addEvent('change',function(){span.set('text',this.options[this.options.selectedIndex].get('text'));});

		parents.each(function(parent) {
			//var old_display = parent.getStyle('display');
			var old_display = parent.retrieve('tmp_old_display_select_styled');
			if ($defined(old_display)) {
				parent.setStyle('display',old_display);
			}
		});

    }   
});
 mm.AccountnameClass = new Class({

	Implements : [Options],
	options : {
		container : false 		// string id or element 
		, inputElement : false	// string id or element
		, notAllowed : [' ','/','\\','>','<','"','\'','*','&','?','!','@','#','$','~','`','±','§','[',']','{','}','=','+', "'",'_']
		//, notAllowed : [' ','/','>','<','"','*','&','?','!','@','#','$','~','`','±','§','[',']','{','}','=','+', "'"]
		, specialChars : ['!','@','#','$','%','^','&','*','?','_','~','(',')','{','}','[',']','-','+','=','±','§','|',',','.']		// special
		, previewPrefix : ''
		, previewSuffix : '.moneymedic.eu'
	},
	initialize: function(options) {
		this.setOptions(options);
		this.element = ($type(this.options.container) == 'string') ? document.id(this.options.container) : this.options.container ;
		this.inputElement = ($type(this.options.inputElement) == 'string') ? document.id(this.options.inputElement) : this.options.inputElement ;
		this.bound = {
			preview : this.preview.bind(this)
			, keypress : this.keypress.bindWithEvent(this)
			, keyup : this.keyup.bindWithEvent(this)
		};		
		this.realName = '';
		this.isAvailable = false;
		this.lastTime = 0;
		this.ajaxTimer = false;
		this.setupElements();
		this.setupEvents();		
	},	
	setupElements: function() {
		this.hidden = new Element('input', {'id':'signup_account_real','type':'hidden', 'name':'account_real', 'value':''}).inject(this.inputElement, 'after');
		var container = new Element('div', {'class':''}).inject(this.element);
		this.previewName = new Element('span', {'class':'mmAccountNamePreview'}).set('html',this.options.previewPrefix+''+this.options.previewSuffix).inject(container);
		this.previewLoading = new Element('span', {'class':'mmAccountNamePreviewLoading'}).set('html', '&nbsp; &nbsp;').setStyle('background-position','-100px 0px').inject(this.previewName,'after');				
	},
	setupEvents: function() {
		this.inputElement.addEvents({
			'keypress': this.bound.keypress
			, 'keyup' : this.bound.keyup
			, 'blur' : this.bound.preview
		});
		this.req = new Request.JSON({
			url: '/_x/accountname'
			, method: 'post'
			, link: 'cancel'
			, noCache: true
			, onSuccess: function(rJson, rText) {
				this.availableRequestSucces(rJson, rText);	//(rJson, rText);
			}.bind(this)
			, onRequest: function() {
				this.availableRequestStart();
			}.bind(this)
			, onFailuer: function() {
				this.availableRequestFailure();
			}.bind(this)
		});	
		
	},
	keypress:function(e) {
		//
//dbug.log('keypress e.key = '+e.key);		
		if (e.key.test(/\W/)) {
//dbug.log('non WORD CHAR'); 
			if (e.key != '-') {
				e.stop();
			}
		}		
		if (e.key == 'space' || this.options.notAllowed.contains(e.key) || ['up','down','left','right'].contains(e.key)) { 
//dbug.log('pressed not allowed');			
			e.stop(); 
		}	
	},
	keyup:function(e) {
		//e.key == 'space' || 
		if (e.key == 'space' || this.options.notAllowed.contains(e.key)) { 
			e.stop(); 
		} else {
			this.preview();
		}		
	},
	resetPreview: function() {
		this.isAvailable = false;
//dbug.log('accountName resetPreview isAvalable = false');		
		this.availableRequestEnd();
		this.oldName = '';
		this.inputElement.set('value', '').removeClass('unavailable').removeClass('validation-failed');
		this.hidden.set('value','');
		var p = this.options.previewPrefix;
//		p += '<span style="color:#ffffff; font-size:10px;">your_account_name</span>';
		p += this.options.previewSuffix;		
		this.previewName.set('html',p);
	},	
	preview: function() {
// dbug.log('preview ');		
		var isCorrect = false;
		var oldName = this.realName;
		this.realName = this.clean(this.inputElement.get('value'));	
		if (oldName == this.realName) { return false; }
		if (this.realName =='') { this.resetPreview(); return false; }
		if (this.realName.length > 2) {
			this.isAvailable = false;			
// dbug.log('accountName preview isAvalable = false');					
			this.previewLoading.setStyle('background-position','center left');			
			isCorrect = true;
			//var now = time();			
			$clear(this.ajaxTimer);
			this.ajaxTimer = this.checkAvailable.delay(500,this);
			//if (now - this.lastTime)
			//this.checkAvailable();
		} 
		var color, erroricon;
		erroricon = this.inputElement.retrieve('errorIcon');		
// dbug.log('erroricon = '+erroricon);		
		if (isCorrect) { 
			color = '#ffffff'; 
			if (erroricon) { erroricon.setStyles({'display':'block','background-position':'0px -24px'}).retrieve('mmTip').hide(); }
			this.inputElement.removeClass('unavailable','none').removeClass('validation-failed');
		} else { 
			color = '#EA1C00'; 
			if (erroricon) { erroricon.setStyles({'display':'block','background-position':'0px 0px'}); }			
			this.inputElement.addClass('unavailable').addClass('validation-failed');			
		}
		var p = this.options.previewPrefix;
		//p += '<span style="color:'+color+'; font-size:10px;">'+this.realName+'</span>';
		p += this.options.previewSuffix;
		this.hidden.set('value', this.realName);
		this.previewName.set('html', p);
				
	},
	clean:function(name) {
//dbug.log(name.test(/^[a-zA-Z0-9-_]+$/));
		['\\*', '\\/', '>', '<','"', '\'', '&', '\\?','!','@','#','\\$','%','~','`','±','§','\\[','\\]','\\(','\\)','\\{','\\}','=','\\+','\\^'].each(function(c) {
			var str = new RegExp(c,'g'); 
//dbug.log('cleanstr = '+str);			
			name = name.replace(str,'');	
		}); 
//dbug.log('clean name ='+name);		
		name = name.replace(/_+/g,'-');
		name = name.replace(/ +/g,'-');
		name = name.replace(/\.+/g,'-');
		name = name.replace(/\,+/g,'-');		
		name = name.replace(/-+/g,'-');		
		name = name.replace(/'+/g,'');		
		name = name.replace(/&+/g,'');				
		name = name.tidy();
		name = name.standardize();
		name = name.toLowerCase();
		return name;		
	},
	checkAvailable:function() {
		this.req.cancel();
		this.req.send('checkname='+this.realName+'&docheckname='+1);	
	},
	availableRequestStart:function() {
		//this.previewLoading.setStyle('display','inline');	
		this.previewLoading.setStyle('background-position','center left');						
	},
	availableRequestEnd:function() {
		this.previewLoading.setStyle('background-position','-100px 0px');					
		//this.previewLoading.setStyle('display','none');		
	},	
	availableRequestSucces:function(rJson, rText) {
//dbug.log(rJson);
		this.availableRequestEnd();
		var color, erroricon;
		erroricon = this.inputElement.retrieve('errorIcon');		
		if (rJson.available) {
			this.isAvailable = true;
//dbug.log('account name isAvailable='+this.isAvailable);			
			color = '#ffffff';					
			if (erroricon) { erroricon.setStyles({'display':'block','background-position':'0px -24px'}).retrieve('mmTip').hide(); }
			this.inputElement.removeClass('unavailable').removeClass('validation-failed');
		} else {
			color = '#EA1C00';
			if (erroricon) { erroricon.setStyles({'display':'block','background-position':'0px 0px'}); }	
			this.inputElement.addClass('unavailable').addClass('validation-failed');								
		}
		
		var p = this.options.previewPrefix;
//dbug.log( 'isCorrect = '+isCorrect +' isAvailable = '+this.isAvailable);		
		//p += '<span style="color:'+color+'; font-size:10px;">'+this.realName+'</span>';
		p += this.options.previewSuffix;

		this.previewName.set('html', p);		
	},
	availableRequestFailure:function() {
		this.availableRequestEnd();		
//dbug.log('availableRequestFailure');		
	}	
	
}); /*
Script: modalizer.js
	Defines Modalizer: functionality to overlay the window contents with a semi-transparent layer that prevents interaction with page content until it is removed

License:
	http://www.clientcide.com/wiki/cnet-libraries#license
*/
mm.ModalizerClass = new Class({
	defaultModalStyle: {
		display:'block',
		position:'fixed',
		top:0,
		left:0,	
		'z-index':5000,
		'background-color':'#333',
		opacity:0.8
	},
	setModalOptions: function(options){
// dbug.log('modalizerclass setModalOptions');		
		this.modalOptions = $merge({
			//width:(window.getScrollSize().x),
			width:(window.getSize().x),
			//height:(window.getScrollSize().y),
			height:(window.getSize().y),
			elementsToHide: 'select, embed' + (Browser.Engine.trident ? '': ', object'),
			hideOnClick: true,
			modalStyle: {},
			updateOnResize: true,
			layerId: 'modalOverlay',
			tweenDuration: 700,
			tweenTransition: 'expo:in:out',
			onModalHide: $empty,
			onModalShow: $empty
		}, this.modalOptions, options);		
		this.layer().set('tween', {duration: this.modalOptions.tweenDuration, transition: this.modalOptions.tweenTransition, link:'ignore', onComplete:function() { this.tweenFadeComplete(); }.bind(this) });						
		return this;
	},
	tweenFadeComplete: function() {
		if (this.layer().getStyle('opacity')==0) {
			this.layer().setStyles({'display':'none'});
		}
	},
	layer: function(){
		if (!this.modalOptions.layerId) { this.setModalOptions(); }
		return document.id(this.modalOptions.layerId) || new Element('div', {id: this.modalOptions.layerId}).inject(document.body);
	},
	resize: function(){
		if (this.layer()) {
			this.layer().setStyles({
				//width:(window.getScrollSize().x),
				width:(window.getSize().x),
				//height:(window.getScrollSize().y)
				height:(window.getSize().y)
			});
//dbug.log('height = '+window.getSize().y);			
		}
	},
	setModalStyle: function (styleObject){
		this.modalOptions.modalStyle = styleObject;
		this.modalStyle = $merge(this.defaultModalStyle, {
			//width:this.modalOptions.width,
			//height:this.modalOptions.height
			width: '100%',
			height: '100%'
		}, styleObject);
		if (this.layer()) this.layer().setStyles(this.modalStyle);
		return(this.modalStyle);
	},
	modalShow: function(options){
		this.setModalOptions(options);
//document.body.setStyle('overflow','hidden');
		this.layer().setStyles(this.setModalStyle(this.modalOptions.modalStyle));
		if (Browser.Engine.trident4) this.layer().setStyle('position','absolute');
		this.layer().removeEvents('click').addEvent('click', function(){
			this.modalHide(this.modalOptions.hideOnClick);
		}.bind(this));
		this.bound = this.bound||{};
		if (!this.bound.resize && this.modalOptions.updateOnResize) {
			this.bound.resize = this.resize.bind(this);
			window.addEvent('resize', this.bound.resize);
		}
		
		if ($type(this.modalOptions.onModalShow)  == "function") this.modalOptions.onModalShow();
		this.togglePopThroughElements(0);
		//this.layer().setStyle('display','block');
		this.layer().setStyles({'display':'block','opacity':0}).fade(this.modalOptions.modalStyle.opacity);
		return this;
	},
	modalHide: function(override, force){
		if (override === false) return false; //this is internal, you don't need to pass in an argument
		this.togglePopThroughElements(1);
		if ($type(this.modalOptions.onModalHide) == "function") this.modalOptions.onModalHide();
		//this.layer().setStyle('display','none');
		this.layer().fade(0);		

		if (this.modalOptions.updateOnResize) {
			this.bound = this.bound||{};
			if (!this.bound.resize) this.bound.resize = this.resize.bind(this);
			window.removeEvent('resize', this.bound.resize);
		}
//document.body.setStyle('overflow','auto');		
		return this;
	},
	togglePopThroughElements: function(opacity){
		if (Browser.Engine.trident4 || (Browser.Engine.gecko && Browser.Platform.mac)) {
			$$(this.modalOptions.elementsToHide).each(function(sel){
				sel.setStyle('opacity', opacity);
			});
		}
	}
}); mm.PasswordmaskClass = new Class({

	Implements : [Options],
	options : {
		inputElement : false	// string id or element
		, notAllowed : [' ','/','\\','>','<','"','\'']
		, specialChars : ['!','@','#','$','%','^','&','*','?','_','~','(',')','{','}','[',']','-','+','=','±','§','|',',','.']		// special
		, duration : 1000
		, tweenDuration : 200
		, tweenTransition : 'expo:out' 
		, offset: {x:-21,y:3}
	},
	initialize: function(options) {
		this.setOptions(options);
		this.bound = {			
			keypress : this.keypress.bindWithEvent(this)
			, tweenComplete : this.tweenCompleteChar.bind(this)
		};		
		this.setupElements();
		this.setupEvents();
	},
	setupElements: function() {		
		this.inputElement = ($type(this.options.inputElement) == 'string') ? document.id(this.options.inputElement) : this.options.inputElement ;		
		this.charElement = new Element('div', {'class':'mmPasswordMaskChar'}).inject(this.inputElement, 'after');	
		this.inputElement.store('mmPasswordMaskChar', this.charElement);
	},
	reposition: function() {
		var pos = this.inputElement.getCoordinates(this.inputElement.getOffsetParent());
//dbug.log('reposition offsParent = '+this.inputElement.getOffsetParent());
//dbug.log(JSON.encode(pos));		
		this.charElement.setStyles({left:(pos.right+this.options.offset.x+2)+'px', top:(pos.top+this.options.offset.y)+'px', 'height':(pos.height-8)+'px', 'line-height':(pos.height-8)+'px'});				
	},
	setupEvents: function() {
		//this.bound.validate = this.validate.bindWithEvent(this);
		this.charElement.set('tween', {'transition':this.options.tweenTransition, 'duration':this.options.tweenDuration, 'link':'cancel', onComplete:this.bound.tweenComplete});								
		this.inputElement.addEvents({
			'keypress' : this.bound.keypress
		});
	},
	keypress: function(e) {
		if (e.key == 'space' || this.options.notAllowed.contains(e.key)) { 
//dbug.log('no space');			
			e.stop(); 
		} else {
			if (e.key != 'space' && e.key != 'backspace' && e.key != 'enter') { // && e.key != 'up' && e.key != 'down' && e.key != 'left' && e.key != 'right' && e.key != 'delete' && e.key != 'esc') {
				this.showChar(String.fromCharCode(escape(e.code)));				
				this.hideChar.delay(this.options.duration,this);
			}			
		}
	},	
	showChar: function(char) {
		this.reposition();
		this.charElement.set('html',char).setStyle('display','block').fade('in');		
	},
	hideChar: function() {
		this.charElement.fade('out');		
	},
	tweenCompleteChar: function() {		
		if (this.charElement.getStyle('opacity')==0) {
//dbug.log('tweencomplete');			
			this.charElement.set('html', '').setStyle('display','none');
		}		
	}
	
}); mm.PasswordstrengthClass = new Class({

	Implements : [Options],
	options : {
		container : false 		// string id or element
		, inputElement : false	// string id or element
		, notAllowed : [' ','/','\\','>','<','"','\'']
		, specialChars : ['!','@','#','$','%','^','&','*','?','_','~','(',')','{','}','[',']','-','+','=','±','§','|',',','.']		// special
		, toolTips : new Hash({
			 'length' : 'Inidcates your password is at least 8 characters long and contains lowercase characters.'
			, 'upper' : 'Indicates your password contains uppercase characters.'
			, 'digit' : 'Indicates your password contains digits.'
			, 'special' : 'Indicates your password contains special characters.'
			, 'meter' : 'Password strength indicator, \'good\' = at least 8 characters and 1 out of the 3 extra requirements.'
			, 'verdict' : 'Only \'good\' or \'strong\' passwords are accepted.' 
		  })
		, labels : new Hash({
			  'length' : '8 characters, min. 1 lowercase letter'
			, 'upper' : 'at least 1 uppercase character'
			, 'digit' : 'at least 1 digit'
			, 'special' : 'at least 1 special non-word character'
		})
	},
	initialize: function(options) {
		this.setOptions(options);
		this.element = ($type(this.options.container) == 'string') ? document.id(this.options.container) : this.options.container ;
		this.inputElement = ($type(this.options.inputElement) == 'string') ? document.id(this.options.inputElement) : this.options.inputElement ;
//dbug.log('pw strength element ='+this.element.get('id'));		
// dbug.log('pw strength input ='+this.inputElement.get('id'));		
		this.bound = {
			validate : this.validate.bindWithEvent(this)
			, keypress : this.keypress.bindWithEvent(this)
		};
		this.score = 0;
		this.verdict = false;
		this.setupElements();
		this.setupEvents();		
	},
	setupElements: function() {		
		this.lblLength = new Element('p', {'class':'mmPasswordStrengthRule'}).set('html', mm.lang.label.passwordstrength_length).inject(this.element);
		this.lblUpper = new Element('p', {'class':'mmPasswordStrengthRule'}).set('html', mm.lang.label.passwordstrength_upper).inject(this.element);		
		this.lblDigit = new Element('p', {'class':'mmPasswordStrengthRule'}).set('html', mm.lang.label.passwordstrength_digit).inject(this.element);		
		this.lblSpecial = new Element('p', {'class':'mmPasswordStrengthRule'}).set('html', mm.lang.label.passwordstrength_special).inject(this.element);				
	},
	setupEvents: function() {
		//this.bound.validate = this.validate.bindWithEvent(this);

		this.inputElement.addEvents({
			'keypress' : this.bound.keypress
			, 'keyup' : this.bound.validate
			, 'blur' : this.bound.validate
		});		
	},
	keypress: function(e) {
		if (e.key == 'space' || this.options.notAllowed.contains(e.key)) { 
// dbug.log('no space');			
			e.stop(); 
		}
	},
	validate: function() {
		this.score = 0;
		this.verdict = false;
// dbug.log('pw validating');	
		var pass = this.inputElement.get('value');


		this.countScore(pass);
		if (this.score < 5) {		
			this.verdict = 'weak';			
		} else if (this.score == 5) {
			this.verdict = 'medium';
		} else if (this.score == 6) {
			this.verdict = 'good';
		} else if (this.score >= 7) {
			this.verdict = 'strong'; 
		}

		this.setImageFromVerdict();
		this.setTextFromVerdict();
	},
	setIcon: function(which, on) {
// dbug.log('setIcon: '+which+' on='+on);		
		var pos;
		if (on==true) { pos = '0px -16px'; } else { pos = '0px 0px'; }
//		this.pwIcons.get(which).setStyle('background-position', pos);
	},
	countScore: function(str) {
		this.score = 0;
		/*
		this.score += this.matchUpper(str) ? 1 : 0 ;
		//this.score += this.matchLower(str) ? 1 : 0 ;		
		this.score += this.matchDigit(str) ? 1 : 0 ;				
		this.score += this.matchNonword(str) ? 1 : 0 ;		
		*/
		if (str.length > 7 && this.matchLower(str)) {
			this.score += 5;
			// this.setIcon('length', true);	
			this.lblLength.addClass('on');
		} else {
			// this.setIcon('length', false);						
			this.lblLength.removeClass('on');
		}
		if (this.matchUpper(str)) {
			this.score += 1;
			// this.setIcon('upper', true);
			this.lblUpper.addClass('on');
		} else {
			this.lblUpper.removeClass('on');
			// this.setIcon('upper', false);
		}
		if (this.matchDigit(str)) {
			this.score += 1;
			// this.setIcon('digit', true);
			this.lblDigit.addClass('on');
		} else {
			// this.setIcon('digit', false);
			this.lblDigit.removeClass('on');
		}		
		if (this.matchNonword(str)) {
			this.score += 1;
			// this.setIcon('special', true);
			this.lblSpecial.addClass('on');
		} else {
//			this.setIcon('special', false);
			this.lblSpecial.removeClass('on');
		}		
	},
	matchUpper: function(str) {
		return str.test(/[A-Z]/);
	},
	matchLower: function(str) {
		return str.test(/[a-z]/);		
	},
	matchDigit: function(str) {
		return str.test(/\d/);
	},
	matchNonword: function(str) {
		// str.test((/.[!,@,#,$,%,^,&,*,?,_,~]/)); //(special chars)
		return str.test(/\W/);
	},
	setImageFromVerdict: function() {
		var newpos = '0px 0px';
		switch(this.verdict) {
			case 'weak' : 
				newpos = '0px -16px';
			break;
			case 'medium' : 
				newpos = '0px -32px';
			break;
			case 'good' : 
				newpos = '0px -48px';
			break;
			case 'strong' : 
				newpos = '0px -64px';
			break;							
		}

//		this.strengthMeter.setStyle('background-position',newpos);
	},
	setTextFromVerdict:function() {
		var verdictStr = '';
		var errorIcon = this.inputElement.retrieve('errorIcon', false);
// dbug.log('errorIcon = '+errorIcon);		
		switch (this.verdict) {
			case 'weak' :
				verdictStr += '<span style="color:#ea1c00;">'+this.verdict+'</span>';
				if (errorIcon) { errorIcon.setStyles({'display':'block', 'background-position':'0px 0px'}); }
				this.inputElement.store('isValid',false).addClass('validation-failed');
			break;
			case 'medium' :
				verdictStr += '<span style="color:#dd9700;">'+this.verdict+'</span>';				
				if (errorIcon) { errorIcon.setStyles({'display':'block', 'background-position':'0px 0px'}); }				
				this.inputElement.store('isValid',false).addClass('validation-failed');				
			break;
			case 'good' :			
				verdictStr += '<span style="color:#8bc53e;">'+this.verdict+'</span>';
				if (errorIcon) { errorIcon.setStyles({'display':'block', 'background-position':'0px -24px'}); }				
				this.inputElement.store('isValid',true).removeClass('validation-failed');				
			break;
			case 'strong' :
				verdictStr += '<span style="color:#8bc53e;">'+this.verdict+'</span>';			
				if (errorIcon) { errorIcon.setStyles({'display':'block', 'background-position':'0px -24px'}); }				
				this.inputElement.store('isValid',true).removeClass('validation-failed');								
			break;
		}
		// this.strengthText.set('html', verdictStr);
	}
	
	
}); mm.Tips = new Class ({
	
	Extends: Tips,

	attach: function(elements){
		var read = function(option, element){
			if (option == null) return '';
			return $type(option) == 'function' ? option(element) : element.get(option);
		};
		$$(elements).each(function(element){
			var title = read(this.options.title, element);
			element.erase('title').store('tip:native', title).retrieve('tip:title', title);
			element.retrieve('tip:text', read(this.options.text, element));
			
			var events = ['enter', 'leave'];
			if (!this.options.fixed) events.push('move');
			
			events.each(function(value){
				element.addEvent('mouse' + value, element.retrieve('tip:' + value, this['element' + value.capitalize()].bindWithEvent(this, element)));
			}, this);
			element.store('mmTip', this);
		}, this);
		
		return this;
	},

	detach: function(elements){
		$$(elements).each(function(element){
			['enter', 'leave', 'move'].each(function(value){
				element.removeEvent('mouse' + value, element.retrieve('tip:' + value) || $empty);
			});
			
			element.eliminate('tip:enter').eliminate('tip:leave').eliminate('tip:move');
			
			if ($type(this.options.title) == 'string' && this.options.title == 'title'){
				var original = element.retrieve('tip:native');
				if (original) element.set('title', original);
			}
			element.store('mmTip', false);			
		}, this);
		
		return this;
	}	
	
	
}); mm.Tabs = new Class({ 
  Implements: [Options, Events], 
  options: { 
    selectedTabCssClass: 'selected', 
    selectedSectionCssClass: 'selected', 
    firstShow: 0, 
	useFade: true,
	fadeProps: {duration:700, transition: 'quad:out'},
	useHover: true, 
 	onShow: $empty, 
    onHide: $empty
  }, 
  tabs: [], 
  initialize: function(containers, tabs, options){ 
    this.setOptions(options); 
    containers = $$(containers); 
//dbug.log(containers.length);
    $$(tabs).each(function(tab, index){ 
//dbug.log('tab '+index);
      this.addSection(tab, containers[index]); 
    }, this); 
    this.show(this.options.firstShow); 
  }, 
  addSection: function(tab, container) { 
    this.tabs.include(tab); 
    tab.store('container', container).setStyle('cursor','pointer'); 
	if (this.options.useFade) {
		container.set('tween', {duration: this.options.fadeProps.duration, transition: this.options.fadeProps.transition});
	}
    this.attach(tab); 
  }, 
  attach: function(tab){ 
    tab.addEvent('click', function(event){ 
      event.preventDefault(); 
      this.show(this.tabs.indexOf(tab)); 
	  if (tab.get('href')!='') {
		window.location.hash = tab.get('href');
	 }
    }.bind(this)); 
	if (this.options.useHover) {
	    tab.addEvent('mouseenter', function(event){ 
	      event.preventDefault(); 
	      this.show(this.tabs.indexOf(tab)); 
	    }.bind(this));		
	}
  }, 
  show: function(index){ 
    if (this.current === index) { return; }
    this.tabs.each(function(tab, i){ 
      var container = tab.retrieve('container'); 
      if (index === i) { 
        tab.addClass(this.options.selectedTabCssClass); 
        container.addClass(this.options.selectedSectionCssClass); 
        container.setStyle('display', 'block'); 
		if (this.options.useFade) {
			container.setStyles({'opacity':0}).fade(1);
		}
        this.fireEvent('onShow', [i, tab, container]); 
      } else { 
        tab.removeClass(this.options.selectedTabCssClass); 
        container.removeClass(this.options.selectedSectionCssClass); 
        container.setStyle('display', 'none'); 
        if (this.current === i || !$chk(this.current)) {
          this.fireEvent('onHide', [i, tab, container]);
		} 
      } 
    }, this); 
    this.current = index; 
  } 
});
mm.TabsAjax = new Class({ 
  Extends: mm.Tabs, 
  options: { 
    cache: true, 
    urls: [], 
    requestOptions: {} 
  },
  show: function(index, force){ 
    var tab = this.tabs[index]; 
    var url = this.options.urls[index] || 
              tab.get('href'); 
    if (!url || force ||  
       (this.options.cache && tab.retrieve('loaded'))) { 
      this.parent(index); 
    } else { 
      this.fetchTabContent(index, url); 
    } 
  }, 
  fetchTabContent: function(index, url) { 
    var tab = this.tabs[index]; 
    var container = tab.retrieve('container'); 
    var request = tab.retrieve('tabAjax'); 
    if (!request) { 
      request = new Request.HTML( 
        $merge(this.options.requestOptions, { 
          update: container, 
          url: url 
        }) 
      ).addEvent('onSuccess', function(){ 
        tab.store('loaded', true); 
        this.show(index, true); 
      }.bind(this)); 
      tab.store('tabAjax', request); 
    } 
    request.send(); 
  } 
});
 /*
UvumiTools TextArea v1.1.0 http://tools.uvumi.com/textarea.html

Copyright (c) 2008 Uvumi LLC

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

mm.TextareaGrow = new Class({

	Implements:Options,

	options:{
		resizeDuration:100,		//animation duration of progress bar and resizing, in milliseconds		
		minSize: false,			//minimum height in pixels you can reduce the textarea to. If set to false, the default value, the original textarea's height will be used as a minimum				
		catchTab: false		//if the textarea should override the tab default event and insert a tab in the text. Default is true, but if you're not going to support it on the back-end, you should disable it		
	},

	initialize: function(el, options){
		this.setOptions(options);
		//each textarea will have its own elements, all storred in arrays
		this.dummy = false;
		this.textarea = document.id(el); //the textarea element.		
		//window.addEvent('domready',this.domReady.bind(this));
		this.setupElements();
	},
	setupElements:function() {
		this.tEffect = new Fx.Tween(this.textarea,{
			duration:this.options.resizeDuration,
			link:'cancel'
		});		
		this.textarea.setStyle('overflow','hidden');
		//if minimum size option is false, we use the original size as minimum.
		if(!this.options.minSize){
			this.options.minSize = this.textarea.getSize().y;
		}		
		this.dummy = this.textarea.clone().setStyles({
				'width':this.textarea.getStyle('width').toInt(),
				'position':'absolute',
				'top':0,
				'height':this.options.minSize,
				'left':-3000
				, 'visibility':'hidden'
		}).store('height',0); //.inject($(document.body));
		this.dummy.erase('name').inject(this.textarea, 'after');
		this.textarea.addEvents({
			'keydown':this.onKeyPress.bindWithEvent(this,[this.options.catchTab]), // here and like on all the other events, we must use bindWithEvent because we pass an additionnal parameter beside the event object
			'keyup':this.onKeyPress.bindWithEvent(this),
			'focus':this.startObserver.bind(this),
			'blur':this.stopObserver.bind(this)
		});		
		var value = this.textarea.get('value');
		this.previousLength = value.length;		
		this.dummy.set('value',value);
		this.textarea.setStyle('height',0);				
		var height = (this.dummy.getScrollSize().y>this.options.minSize?this.dummy.getScrollSize().y:this.options.minSize);
		if(this.dummy.retrieve('height')!=height){
			this.dummy.store('height',height);
			this.textarea.setStyle('height',height);
		}		
		this.update();
	},
		
	onKeyPress: function(event,tab) {
		if(tab && event.key == "tab"){
			event.preventDefault();
			this.insertTab();
		}
		if(!event.shift && !event.control && !event.alt && !event.meta){
			this.update();
		}
		this.startObserver();
	},
	
	startObserver:function(){
		$clear(this.observer);
		this.observer = this.observe.periodical(500,this);
	},
	
	stopObserver:function(){
		$clear(this.observer);
	},
	
	observe:function(){
		if(this.textarea.get('value').length != this.previousLength){
			this.previousLength = this.textarea.get('value').length;
			this.update();
		}
	},

	
	update:function(){
		var value = this.textarea.get('value');
		this.previousLength = value.length;
		this.updateHeight(value);
	},
	
	updateHeight: function(value){
		this.dummy.set('value',value);
		var height = (this.dummy.getScrollSize().y>this.options.minSize?this.dummy.getScrollSize().y:this.options.minSize);
		if(this.dummy.retrieve('height')!=height){
			this.dummy.store('height',height);
			this.tEffect.start('height',height);
		}
	},
	
	insertTab: function(i){
		if(Browser.Engine.trident) {
			var range = document.selection.createRange();
			range.text = "\t";
		}else{
			var start = this.textarea.selectionStart;
			var end = this.textarea.selectionEnd;
			var value = this.textarea.get('value');
			this.textarea.set('value', value.substring(0, start) + "\t" + value.substring(end, value.length));
			start++;
			this.textarea.setSelectionRange(start, start);
		}
	}
}); mm.AjaxControllerClass = new Class({
	Implements : [Options, Events]
	, options : {
		test:'oi'
		, tooltipDelays : {show: 500, hide: 1}	
		, ajaxDelay: 500	
		, highlightIdColor: '#def0da'
	}
	, initialize:function(options) {
		this.setOptions(options);
//dbug.log('ajaxController init');		
		this.ajaxReady(); // initial ajaxReady for document
	}
	, domReady:function() {
		
	}
	, ajaxReady:function(container) {
//dbug.log('ajaxReady: '+mm.runtime.request + ' container = '+container);		
		if (!$defined(container)) { container = document.body; }
	
		// page specific stuff:
		if (mm.runtime.request=='invoice' && (container == document.body)) {
//dbug.log('ajaxReady_invoice');			
			this.ajaxReady_invoice();
		} else if (mm.runtime.request=='settings' && (container == document.body)) {
			this.ajaxReady_settings();
		} else if (mm.runtime.request=='purchase' && (container == document.body)) {
			this.ajaxReady_purchase();
		} 
//dbug.log('ajaxReady container = '+container);
		var ajaxTableContainers = container.getElements('div.ajaxTableContainer');
		if (ajaxTableContainers.length > 0) {
			this.getAjaxTables(ajaxTableContainers);
		}
	
		var ajaxTables = container.getElements('table.ajaxTable');
		if (ajaxTables.length > 0) {
			this.setupAjaxTables(ajaxTables);
		}	

		var ajaxStatsContainers = container.getElements('div.ajaxStatsContainer');
		if (ajaxStatsContainers.length > 0) {
			this.getAjaxStatsContainers(ajaxStatsContainers);
		}
		var statsPeriodLinks = container.getElements('a[class~=statsPeriodLink]');
		if (statsPeriodLinks.length > 0) {
			this.setupStatsPeriodLinks(statsPeriodLinks);
		}
		var graphSelect = document.id('graphSelect');
		if (graphSelect) {
			this.setupGraphSelect(graphSelect);
		}
		
		var bargraphContainers = container.getElements('div.bargraphContainer');
		if (bargraphContainers.length > 0) {
			this.setupBargraphContainers(bargraphContainers);
		}		
		
		var piechartContainers = container.getElements('div.piechartContainer');
		if (piechartContainers.length > 0) {
			this.setupPiechartContainers(piechartContainers);
		}		
		
		var disabledLinks = container.getElements('a.disabled');
		if (disabledLinks.length > 0) {
			disabledLinks.each(function(link) {
				link.addEvent('click', function(e) {
					e.stop();
				});
			},this);
		}
		
		var dialogLinks = container.getElements('a.dialogLink');
		if (dialogLinks.length > 0) {
			this.setupDialogLinks(dialogLinks);
		}
		var dialogConfirmLinks = container.getElements('a.dialogConfirmLink');
		if (dialogConfirmLinks.length > 0) {
			this.setupDialogConfirmLinks(dialogConfirmLinks);
		}
		
		var ajaxPageSaveDialogLinks = container.getElements('a.ajaxPageSaveDialogLink');
		if (ajaxPageSaveDialogLinks.length > 0) {
			this.setupAjaxPageSaveDialogLinks(ajaxPageSaveDialogLinks);
		}
		var ajaxPageSaveLinks = container.getElements('a.ajaxPageSaveLink');
		if (ajaxPageSaveLinks.length > 0) {
			this.setupAjaxPageSaveLinks(ajaxPageSaveLinks);
		}
		
		var fancyUploadSingleLinks = container.getElements('a.fancyUploadSingleLink');
		if (fancyUploadSingleLinks.length > 0) {
			this.setupFancyUploadSingleLinks(fancyUploadSingleLinks);
		}
		var infoToggleLinks = container.getElements('a.infoToggleLink');
		if (infoToggleLinks.length > 0) {
			this.setupInfoToggleLinks(infoToggleLinks);
		}
		var tooltips = container.getElements('.mmTooltip');
		if (tooltips.length > 0) {
//dbug.log(this.options.tooltipDelays);			
			new mm.Tips(tooltips, {className:'mmTip', text: function(el){ return false; }, showDelay:this.options.tooltipDelays.show, hideDelay:this.options.tooltipDelays.hide});				
		}
		var mmradios = container.getElements('.mmRadio');
		if (mmradios.length > 0) {
			this.setupStyledRadios(mmradios);
		}
		
		var switches = container.getElements('input[type=checkbox][class=mmSwitch]');
		if (switches.length > 0) {
			switches.each(function(el) {
				var checkId = el.get('id');
				if ($defined(checkId)) {
//dbug.log('checkId = '+checkId);					
					switch(checkId) {
						case 'periodic_endless' :
							new mm.Switch(el,{
								onSwitch: function(onoff, checkbox) {
									var periodic_times = document.id('periodic_times');
									var periodic_times_display = document.id('periodic_times_display');									
									var periodic_times_min = document.id('periodic_times_min');
									var periodic_times_container = document.id('periodic_times_container');																		
									if (periodic_times_container && periodic_times && periodic_times_display && periodic_times_min) {
										if (onoff) {
											periodic_times.set('value', -1);
											periodic_times_display.set('disabled', true).addClass('disabled').removeClass('focused');
											periodic_times_container.setStyle('display','none');											
										} else {
											periodic_times_container.setStyle('display','inline-block');											
											var min = periodic_times_min.get('value').toInt();
											var now = periodic_times_display.get('value').toInt();
											if (now < min) {
												periodic_times_display.set('value', min);
											}
											periodic_times.set('value', periodic_times_display.get('value'));											
											periodic_times_display.set('disabled', false).removeClass('disabled');
										}
									}
//dbug.log('times = '+periodic_times.get('value'));
								}
							});													
						break;
						default : 
							new mm.Switch(el,{});						
						break;
					}
				} else {
					new mm.Switch(el,{});
				}
			});		
		}
		
		var toggleDivLinks = container.getElements('.toggleDivLink');
		if (toggleDivLinks.length > 0) {
			this.setupToggleDivLinks(toggleDivLinks);
		}
		var toggleDivChildrenLinks = container.getElements('.toggleDivChildrenLink');
		if (toggleDivChildrenLinks.length > 0) {
			this.setupToggleDivChildrenLinks(toggleDivChildrenLinks);
		}
		var textareas = container.getElements('textarea.mmTextarea');
		if (textareas.length > 0) {
			textareas.each(function(ta) {
				new mm.TextareaGrow(ta, {minSize:30});				
			});
		}
		
		var invoiceEditAreas = container.getElements('.invoiceEditArea');
		if (invoiceEditAreas.length > 0) {
			this.setupInvoiceEditAreas(invoiceEditAreas);
		}
		
		var editSpans = container.getElements('span.editSpan');
		if (editSpans.length > 0) {
			this.setupEditSpans(editSpans);
		}
		
		var editSpanTexts = container.getElements('.editSpanText');
		if (editSpanTexts.length > 0) {
			this.setupEditSpanTexts(editSpanTexts);
		}
		
		var editSpanSelects = container.getElements('.editSpanSelect');
		if (editSpanSelects.length > 0) {
			this.setupEditSpanSelects(editSpanSelects);
		}
		
		var sortables = container.getElements('.sortable');
		if (sortables.length > 0) {
			sortables.each(function(el) {
				var sortable = new Sortables(el,{
					revert: { duration: 500, transition: 'circ:out' }					
				});
				el.store('sortable', sortable);
			});
		}

		var datePickerInputs = container.getElements('input[type=text][class~=datepicker]');
		if (datePickerInputs.length > 0) {
			this.initDatePickers(datePickerInputs, container);
		}

		var focusInputs = container.getElements('input[type=text][class~=inputText]', 'input[type=password][class~=inputText]');
		if (focusInputs.length > 0) {
			focusInputs.each(function(input) {
				new InputFocus(input, {
					'focusedClass':'focused'
				});
			});
		}
		var focusTextareas = container.getElements('textarea[class~=inputTextarea]');
		if (focusTextareas.length > 0) {
			focusTextareas.each(function(textarea) {
				new InputFocus(textarea, {
					'focusedClass':'focused'
				});
			});
		}		


		// TABCONTAINERS LAST BECAUSE THEY HIDE STUFF
		var tabContainers = container.getElements('div.mmTabsContainer');
		if (tabContainers.length > 0) {
			this.setupTabContainers(container);
		}
		
		var subtabContainers = container.getElements('div.mmSubTabsContainer');
		if (subtabContainers.length > 0) {
			this.setupSubTabContainers(subtabContainers);
		}

	}
	, ajaxReady_settings:function() {
		var form = document.id('settingsForm');
		var btw_tariff_list	= document.id('btw_tariff_list');
		if (btw_tariff_list) {
			 //var sortable = new Sortables(btw_tariff_list,{});
			//btw_tariff_list.store('sortable', sortable);
			var lastLi = btw_tariff_list.getLast('li');
			btw_tariff_list.getElements('li').each(function(item) {
				if (item != lastLi) {
					item.setStyle('cursor', 'move');
				}
			});		
			//sortable.removeItems(lastLi);		
			var btw_tariff_list_add = document.id('btw_tariff_list_add');
			var btw_tariff_list_add_btn = document.id('btw_tariff_list_add_btn');
			btw_tariff_list_add_btn.addEvent('click', function(e) {
				e.stop();
				if (btw_tariff_list_add && btw_tariff_list_add.get('value') != '') {
					var val = btw_tariff_list_add.get('value');	
					var newli = new Element('li', {}).setStyle('cursor','move');
					var newspan = new Element('span', {}).set('html',val+' %');
					var delbtn = new Element('span', {}).setStyles({'position':'absolute','diplay':'block','text-align':'center','top':'-8px','right':'2px'}).set('html', 'x');		
					var newhidden = new Element('input', {'type':'hidden', 'name':'btw_tariff[]'}).set('value',(val.toFloat()/100));
					newhidden.inject(newli);
					newspan.inject(newli,'bottom');
					delbtn.inject(newli,'bottom');		
					newli.inject(lastLi, 'before');
					//btw_tariff_list.retrieve('sortable').addItems(newli);
					btw_tariff_list_add.set('value', '');
					delbtn.addEvent('click', function(e) {
						e.stop();
						//var thisli = delbtn.g
						newli.destroy();
					});
				}

			});		
		}
		
		// COLOR BUTTON:
		var colorInput = document.id('branding_background');
		var fontColorInput = document.id('branding_color');
		var fontColorSelect = document.id('branding_color');
		if (colorInput) {
			new mm.Color(colorInput, {
				autoFontColor:false
				, alwaysOpen: true
				, onChange:function(hex,fontcolor) {
					//fontColorInput.set('value', fontcolor);
					var headers = $$('table.invoiceProductsTableHeader');
					if (headers.length > 0) {
						headers.each(function(header) {
							header.getElements('tr').each(function(el) {
								el.setStyles({'background-color':hex});
								//,'color':fontcolor
							});
							header.getElements('td').each(function(el) {
								el.setStyles({'background-color':hex});								
							});
						});
					}
					this.checkAjaxPageFormChanged(colorInput.getParent('form'));
				}.bind(this) 
			});			
		}
		if (fontColorSelect) {
			//init color: 
			var fontColor = fontColorSelect.get('value');
			if (fontColor != '') { colorInput.setStyle('color',fontColor); }
						
			fontColorSelect.addEvent('change', function(e) {
				var fontColor = this.get('value')
				colorInput.setStyle('color',fontColor);
				var headers = $$('table.invoiceProductsTableHeader');
				if (headers.length > 0) {
					headers.each(function(header) {
						header.getElements('tr').each(function(el) {
							el.setStyles({'color':fontColor});
						});
						header.getElements('td').each(function(el) {
							el.setStyles({'color':fontColor});							
						});
					});
				}
				
			});
		}
		
		// BRANDING TITLEPOS:
//		invoiceSection_1
		var radiosPos = document.getElements('input[type=radio][name=branding_titlepos]');
		if (radiosPos.length > 0) {
			radiosPos.each(function(radioPos) {
				radioPos.addEvent('click', function(e) {
//dbug.log('radioPos value = '+radioPos.get('value'));	
					//e.stop();
					var leftright = radioPos.get('value');
					var sections_1 = $$('.invoiceSection_1');
					var sections_2 = $$('.invoiceSection_2');					
					
					sections_1.each(function(section){
						var invoiceTitle = section.getElement('.invoiceTitle');
						var invoiceLogo = section.getElement('.invoiceLogo');						
						if (leftright == 1) {
							invoiceTitle.setStyle('float','right');
							invoiceLogo.setStyle('float','left');							
						} else {
							invoiceTitle.setStyle('float','left');							
							invoiceLogo.setStyle('float','right');														
						}
						/*
						var tr_1 = section.getElement('table.invoiceTable').getElement('tr');
						var invoiceTitle = tr_1.getElement('td.invoiceTitle');
						var invoiceLogo = tr_1.getElement('td.invoiceLogo');						
						if (leftright == 1) {
							invoiceTitle.inject(tr_1, 'bottom');
							invoiceLogo.inject(tr_1, 'top');		
						} else {
							invoiceTitle.inject(tr_1, 'top');
							invoiceLogo.inject(tr_1, 'bottom');																
						}							
						invoiceTitle.setStyle('width','35%');
						invoiceLogo.setStyle('width','35%');
						*/							
											
					});		
					
					sections_2.each(function(section) {
						var tr_2 = section.getElement('table.invoiceTable').getElement('tr');					
						var invoiceDetailsClient = tr_2.getElement('td.invoiceDetailsClient');			
						var invoiceDetailsAccount = tr_2.getElement('td.invoiceDetailsAccount');						
						if (leftright == 1) {
							invoiceDetailsClient.inject(tr_2,'bottom');
							invoiceDetailsAccount.inject(tr_2,'top');							
						} else {
							invoiceDetailsClient.inject(tr_2,'top');
							invoiceDetailsAccount.inject(tr_2,'bottom');							
						}																	
						invoiceDetailsClient.setStyle('width','35%');
						invoiceDetailsAccount.setStyle('width','35%');						
					});
						
				});
			});
		}
		
		// BRANDING SHOW CLIENT NUM:
		var radiosClientnr = document.getElements('input[type=radio][name=branding_show_client_nr]');
		if (radiosClientnr.length > 0) {
			radiosClientnr.each(function(radioClientnr) {
				radioClientnr.addEvent('click', function(e) {
					var show = radioClientnr.get('value');
//dbug.log('show client nr = '+show);
					var sections_3 = $$('.invoiceSection_3');					
					sections_3.each(function(section) {
						var showDivs = section.getElements('div.show_client_nr');
						if (showDivs.length > 0) {
							showDivs.each(function(showDiv) {
								if (show==1) {
									showDiv.setStyle('display','block');
								} else {
									showDiv.setStyle('display','none');									
								}
							});
						}
					});
				});
			});
		}
		
		/*
		var invoice_nr_prefix = document.id('invoice_nr_prefix');
		var invoice_nr_count = document.id('invoice_nr_count');
		var invoice_nr_preview = document.id('invoice_nr_preview');				
		var invoice_nr_editbtn = document.id('invoice_nr_editbtn');
		if (invoice_nr_prefix && invoice_nr_count && invoice_nr_preview) {
			invoice_nr_prefix.addEvents({
				'keyup': this.settingsInvoiceNrPreview.bind(this, invoice_nr_prefix)
				, 'blur': this.settingsInvoiceNrPreview.bind(this, invoice_nr_prefix)
			});
			invoice_nr_count.addEvents({
				'keyup': this.settingsInvoiceNrPreview.bind(this, invoice_nr_count)
				, 'blur': this.settingsInvoiceNrPreview.bind(this, invoice_nr_count)
			});			
			if (invoice_nr_editbtn)	{
				invoice_nr_editbtn.addEvent('click', function(e) {
					e.stop();
					invoice_nr_prefix.set('disabled',false).removeClass('disabled');
					invoice_nr_count.set('disabled',false).removeClass('disabled');					
					invoice_nr_editbtn.setStyle('display','none');
					invoice_nr_prefix.focus();
				}.bind(this));
			}
		}
		*/

		var settings_upload_logo_link = document.id('settings_upload_logo_link');
		if (settings_upload_logo_link) {
			this.setupSettingsUploadLogoLink(settings_upload_logo_link);
		}
		
		var bank_account_nr = document.id('bank_account_nr');
		var settingsBankAccountTypes = document.getElements('input[type=radio][class~=settings_bank_account_type]');
		var bank_account_holder = document.id('bank_account_holder');		
		if (bank_account_nr) {
			bank_account_nr.addEvents({
				'focus': function(e) {
					this.settingsCheckBankAccountNr(settingsBankAccountTypes, bank_account_nr);
				}.bind(this)			
				,'blur': function(e) {
					this.settingsCheckBankAccountNr(settingsBankAccountTypes, bank_account_nr);
				}.bind(this)
				, 'keyup': function(e) {
					this.settingsCheckBankAccountNr(settingsBankAccountTypes, bank_account_nr);				
				}.bind(this)
			});
			this.settingsCheckBankAccountNr(settingsBankAccountTypes, bank_account_nr);
			settingsBankAccountTypes.each(function(btype) {
				btype.addEvent('click', function(e) { 
					this.settingsCheckBankAccountNr(settingsBankAccountTypes, bank_account_nr);
				}.bind(this));
			},this);					
		}

		
		
		var address = document.id('address');
		var address_postal_num = document.id('address_postal_num');
		var address_postal_alpha = document.id('address_postal_alpha');		
		var address_city = document.id('address_city');	
		if (address_postal_num && address_postal_alpha && address_city) {
			address_postal_num.addEvent('keyup', function(e) {
				if (address_postal_num.get('value').length == 4) {
					if (form.retrieve('formValidator').test('minLength',address_postal_num) && form.retrieve('formValidator').test('maxLength',address_postal_num) && form.retrieve('formValidator').test('validate-integer',address_postal_num)) {
						address_postal_alpha.focus();
					}
				}
			}.bind(this));			
		}			
		
		var post_address = document.id('post_address');
		var post_address_postal_num = document.id('post_address_postal_num');
		var post_address_postal_alpha = document.id('post_address_postal_alpha');		
		var post_address_city = document.id('post_address_city');
		
		var contact_address = document.id('contact_address');
		var contact_address_postal_num = document.id('contact_address_postal_num');
		var contact_address_postal_alpha = document.id('contact_address_postal_alpha');		
		var contact_address_city = document.id('contact_address_city');		
		
		var copy_address_post = document.id('copy_address_post');
		var copy_address_contact = document.id('copy_address_contact');
		if(copy_address_post) {
			copy_address_post.addEvent('click', function(e) {
				e.stop();
				post_address.set('value', address.get('value'));
				post_address_postal_num.set('value', address_postal_num.get('value'));				
				post_address_postal_alpha.set('value', address_postal_alpha.get('value'));				
				post_address_city.set('value', address_city.get('value'));	
				
				if (post_address.get('value')!='') { post_address.removeClass('validation-failed'); }
				if (post_address_postal_num.get('value')!='') { post_address_postal_num.removeClass('validation-failed'); }											
				if (post_address_postal_alpha.get('value')!='') { post_address_postal_alpha.removeClass('validation-failed'); }											
				if (post_address_city.get('value')!='') { post_address_city.removeClass('validation-failed'); }																
				this.checkAjaxPageFormChanged(form);				
			}.bind(this));
		} 
		if(copy_address_contact) {
			copy_address_contact.addEvent('click', function(e) {
				e.stop();
				contact_address.set('value', address.get('value'));
				contact_address_postal_num.set('value', address_postal_num.get('value'));				
				contact_address_postal_alpha.set('value', address_postal_alpha.get('value'));				
				contact_address_city.set('value', address_city.get('value'));		
				if (contact_address.get('value')!='') { contact_address.removeClass('validation-failed'); }
				if (contact_address_postal_num.get('value')!='') { contact_address_postal_num.removeClass('validation-failed'); }
				if (contact_address_postal_alpha.get('value')!='') { contact_address_postal_alpha.removeClass('validation-failed'); }
				if (contact_address_city.get('value')!='') { contact_address_city.removeClass('validation-failed'); }																		
				this.checkAjaxPageFormChanged(form);				
			}.bind(this));
		}		
		
		var doc_kvk_upload_link = document.id('doc_kvk_upload_link');
		var doc_id_upload_link = document.id('doc_id_upload_link');
		var doc_contract_upload_link = document.id('doc_contract_upload_link');		
		var uploadajaxurl = '/_x/account_docs';
		[doc_kvk_upload_link, doc_id_upload_link, doc_contract_upload_link].each(function(uploadLink){
			if (uploadLink) {
				var linkId = uploadLink.get('id');
				var progressBar = false;
				var loader = false;
				var deleteBtn = false;
				var fileDisplay = false;
				if ($defined(linkId) && linkId != '') {
					progressBar = document.id(linkId+'_progress');
					loader = document.id(linkId+'_loader');				
					fileDisplay = document.id(linkId+'_filename');
					deleteBtn = document.id(linkId+'_delete');				
				}
				var rel = uploadLink.get('rel');
				var ajaxUpdate = uploadLink.hasClass('ajaxUpdate');
				var alt = uploadLink.get('alt');
				if ($defined(rel) && rel!='') {
					var uploadtype = rel;
					var hiddenUploadFile = false;
					if ($defined(alt) && alt!='') {
						hiddenUploadFile = document.id(alt);
					}
					if (deleteBtn) {
						deleteBtn.addEvent('click', function(e){
							e.stop();
							// var oldFile = hiddenUploadFile.get('value');
							hiddenUploadFile.set('value','');
							if (fileDisplay) {
								fileDisplay.empty();
								fileDisplay.set('html', '<span class="" style="background-color:#FFCCCC; padding:4px;"">Geen document gevonden.</span>');	
							}
							deleteBtn.setStyle('display','none');
							// uploadLink.setStyle('display','inline-block');
							// uploadLink.retrieve('uploadSwf').setStyle('display','block');							
							new Request.JSON({
								url:uploadajaxurl
								, method: 'post'
								, data: {'doc_id':uploadtype, 'document':''}
								, onRequest: function() {

								}
								, onFailure: function() {

								}
								, onSuccess: function(rJson, rText) {
// dbug.log(rJson);							
									if (rJson.saved) {					
										// ok
									}
								}							
							}).send();

						});
					}
					var flashurl = '/uploaddoc';
					var extraData = {
						'uploadtype':uploadtype
						, 'username':mm.runtime.auth.username
					};
	//dbug.log('setupFancyUploadSingleLinks :'+flashurl);				
					var swf = new Swiff.Uploader({
						path: '/_img/plugins/fancyupload/Swiff.Uploader.swf',
						//url: 'https://wmadmin:k4n44lw3g@vic.moneymedic.eu/uploadsingle',
						url: flashurl,
						data: extraData,
						verbose: false,
						queued: false,
						multiple: false,
						target: uploadLink,
						instantStart: true,
						typeFilter: {
							'Bestanden (*.jpg, *.jpeg, *.gif, *.png, *.pdf, *.doc, *.txt, *.rtf, *.docx, *.xls, *.xlsx, *.zip, *.rar, *.gz)': '*.jpg; *.jpeg; *.gif; *.png; *.pdf; *.doc; *.txt; *.rtf; *.docx; *.xls; *.xlsx; *.zip; *.rar; *.gz'
						},
						fileSizeMax: 4 * 1024 * 1024,
						onSelectSuccess: function(files) {
							if (Browser.Platform.linux) window.alert('Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nSince you are prepared now, the upload will start right away ...');
	//dbug.log('Starting Upload', 'Uploading <em>' + files[0].name + '</em> (' + Swiff.Uploader.formatUnit(files[0].size, 'b') + ')');
							this.setEnabled(false);
						},
						onBeforeStart: function() {
	//dbug.log('onBeforeStart');								
							if (deleteBtn) { deleteBtn.setStyle('display','none'); }						
							if (loader) { loader.setStyle('display', 'block'); }
						},					
						onSelectFail: function(files) {
alert('' + files[0].name + ' is te groot. Selecteer een bestand kleiner dan 4 Mb. (Error: #' + files[0].validationError + ')');
						},
						appendCookieData: true,
						onQueue: function() {
							if (!swf.uploading) return;
							var size = Swiff.Uploader.formatUnit(swf.size, 'b');
							if (progressBar) {
								progressBar.set('html', '<span class="small">' + swf.percentLoaded + '% of ' + size + '</span>');
							}
							//link.set('html', );						
						},
						onFileComplete: function(file) {

	//dbug.log('filecomplete: response = ');
	//dbug.log(JSON.decode(file.response.text));						
							if (file.response.error) {
alert('Uploading ' + this.fileList[0].name + ' failed, please try again. (Error: #' + this.fileList[0].response.code + ' ' + this.fileList[0].response.error + ')');
							} else {
								//var md5 = JSON.decode(file.response.text, true).hash; // secure decode

								//log.alert('Successful Upload', 'an MD5 hash was created from <em>' + this.fileList[0].name + '</em>: <code>' + md5 + '</code>.<br />gravatar.com generated a fancy and unique monsterid for it, since we did not save the image.');

								//var img = $('demo-portrait');
								//img.setStyle('background-image', img.getStyle('background-image').replace(/\w{32}/, md5));
								//img.highlight();
	//dbug.log('upload succes');							
								rJson = JSON.decode(file.response.text);
							}
							var finalfilename = false;
							if ($defined(rJson.uploadtype) && $defined(rJson.filename)) {
								finalfilename = rJson.filename;
							}
							if (hiddenUploadFile && finalfilename) {
								hiddenUploadFile.set('value',finalfilename );
							}
							if (fileDisplay && finalfilename) {
								var finalfilelink = '<img border="0" class="vmiddle statusIcon " src="/_img/icons/status/status_3.png"  /> <a href="/_f/'+mm.runtime.auth.username+'/'+finalfilename+'">'+rJson.filename.substr(11)+'</a>';
								fileDisplay.set('html', finalfilelink);
								if (deleteBtn) { deleteBtn.setStyle('display','inline-block'); }															
							}			
							if (progressBar) {
								progressBar.set('html', '');
							}			
							file.remove();
							this.setEnabled(true);								

								new Request.JSON({
									url:uploadajaxurl
									, method: 'post'
									, data: {'doc_id':rJson.uploadtype, 'document':finalfilename}
									, onRequest: function() {

									}
									, onFailure: function() {

									}
									, onSuccess: function(rJson, rText) {
// dbug.log(rJson);							
										if (rJson.saved) {					
											// ok
										}
									}							
								}).send();		
								
							if (fileDisplay && finalfilename) {
								// uploadLink.setStyle('display','none');
								// uploadLink.retrieve('uploadSwf').setStyle('display','none');
							}				

						},
						onComplete: function() {
							//link.set('html', 'klik again');
							if (loader) { loader.setStyle('display', 'none');  }						

						}
					});
					// uploadLink.store('uploadSwf', swf.box);
					// Button state
					uploadLink.addEvents({
						click: function() {
							return false;
						},
						mouseenter: function() {
							this.addClass('hover');
							swf.reposition();
						},
						mouseleave: function() {
							this.removeClass('hover');
							this.blur();
						},
						mousedown: function() {
							this.focus();
						}
					});									
				
				}
			}
				
		});
		
			
		
	}
	, settingsCheckBankAccountNr:function(settingsBankAccountTypes, settingsBankAccountNr) {
		var value = 0;
		settingsBankAccountTypes.each(function(btype, index) {
// dbug.log('radio	index='+index+' checked = '+btype.get('checked')+' value = '+btype.get('value'));		
			if (btype.get('checked')) {
				value = btype.get('value').toInt();
			}
		},this);
		var giro = false;
		if (value === 2) {
			// giro
			giro = true;
		} 
		var num = settingsBankAccountNr.get('value');
		var hasLetters = num.test(/\D/);
		if (hasLetters) {
			num = num.replace(/\D/, "");		
			settingsBankAccountNr.set('value', num);
		}
		var valid = mm.main.validateAccountNumber(num, giro);
				
		if (valid) {
			settingsBankAccountNr.removeClass('validation-failed');
			settingsBankAccountNr.store('notValidated', false);	
			this.hideFailedValidationOnTabs(settingsBankAccountNr.getParent('form'), settingsBankAccountNr);				
		} else {
			settingsBankAccountNr.addClass('validation-failed');
			settingsBankAccountNr.store('notValidated', true);		
			this.showFailedValidationOnTabs(settingsBankAccountNr, settingsBankAccountNr.getParent('form'));																	
		}
// dbug.log('checkBankAccountNr giro='+giro+' num='+num+' valid='+valid);		
	}
	, settingsInvoiceNrPreview:function(inputEl) {
		var invoice_nr_prefix = document.id('invoice_nr_prefix');
		var invoice_nr_count = document.id('invoice_nr_count');
		var invoice_nr_preview = document.id('invoice_nr_preview');
		var prefix = invoice_nr_prefix.get('value');
		var count = invoice_nr_count.get('value').trim().toInt();
		if (isNaN(count)) { count = 0; }
		var count = sprintf("%05d",''+count);
		invoice_nr_preview.set('html', prefix+count);		
	}
	, ajaxReady_purchase:function() {
		var updPurchase = false;
		var newPurchase = false;
		var update_purchase = document.id('update_purchase');
		var new_purchase = document.id('new_purchase');	
		if (update_purchase) { if (update_purchase.get('value') == 1) { updPurchase = true; } }
		if (new_purchase) { if (new_purchase.get('value') == 1) { newPurchase = true; } }			
		if (newPurchase || updPurchase) {
			var clientSelect = document.id('selectClient');
			var clientTextarea = document.id('client_static_text');
			if (clientSelect) {
				clientSelect.addEvents({
					'change':function(e) {
						var client_id = clientSelect.get('value');
//dbug.log('clientSelect change: '+clientSelect.get('value'));		
						if (client_id == '') { 
							clientTextarea.set('value', '');
							clientTextarea.addClass('validation-failed');
							return false; 
						} else {
							if (clientTextarea.hasClass('validation-failed')) {
								clientTextarea.removeClass('validation-failed');
							}							
						}
						var ajaxurl = '/_x/clientdetails';
						var postdata = {id:client_id}
						new Request.JSON({
							url: ajaxurl
							, method: 'post'
							, data: postdata
							, onRequest: function() {

							}
							, onFailure: function() {

							}
							, onSuccess: function(rJson, rText) {	
								var newText = '';
								 if (rJson.name_company) { newText += rJson.name_company; }
								 if (rJson.name_contact) { newText += "\n" + rJson.name_contact; }							
								// if (rJson.address) { newText += "\n" + rJson.address; }
								// if (rJson.postal_num || rJson.postal_alpha || rJson.city) {
								// 	newText += "\n";
								// 	if (rJson.postal_num) { newText +=  rJson.postal_num; }	
								// 	if (rJson.postal_alpha) { newText +=  ' '+rJson.postal_alpha; }									
								// 	if (rJson.city) { newText +=  ' '+rJson.city; }								
								// }							
								if (rJson.country_code) {	
									var purchase_btw_total_invoice_display = document.id('purchase_btw_total_invoice_display');																
									var purchase_btw_total_invoice = document.id('purchase_btw_total_invoice');
									var purchase_exbtw_row = document.id('purchase_exbtw_row');
									var purchase_btw_row = document.id('purchase_btw_row');									
									var purchase_total_invoice_display_btw_label = document.id('purchase_total_invoice_display_btw_label');
									var purchase_nobtw_info = document.id('purchase_nobtw_info');
									var purchase_btw_editarea = document.id('purchase_btw_editarea');
									if (rJson.country_code == 'NL') {
										if (rJson.address_nl && $chk(rJson.address_nl)) { newText += "\n" + rJson.address_nl; }
										if (rJson.address_num_nl && $chk(rJson.address_num_nl)) { newText += ' '+rJson.address_num_nl; }
										if (rJson.address_num_extra_nl && $chk(rJson.address_num_extra_nl)) { newText += ' '+rJson.address_num_extra_nl; }										
										if (rJson.postal_num_nl || rJson.postal_alpha_nl || rJson.city_nl) {
											newText += "\n";
											if (rJson.postal_num_nl && $chk(rJson.postal_num_nl)) { newText +=  rJson.postal_num_nl; }	
											if (rJson.postal_alpha_nl && $chk(rJson.postal_alpha_nl)) { newText +=  ' '+rJson.postal_alpha_nl; }									
											if (rJson.city_nl && $chk(rJson.city_nl)) { newText +=  ' '+rJson.city_nl; }								
										}
										purchase_exbtw_row.setStyle('display','block');
										purchase_btw_row.setStyle('display','block');				
										purchase_total_invoice_display_btw_label.setStyle('display','inline');																
										purchase_nobtw_info.setStyle('display','none');
										if (purchase_btw_editarea) { purchase_btw_editarea.setStyle('display','inline-block'); }																		
									} else {
										if (rJson.address_1_int && $chk(rJson.address_1_int)) { newText += "\n" + rJson.address_1_int; }									
										if (rJson.address_2_int && $chk(rJson.address_2_int)) { newText += "\n" + rJson.address_2_int; }
										if (rJson.postal_int && $chk(rJson.postal_int)) { newText += "\n" + rJson.postal_int; }										
										if (rJson.city_int && $chk(rJson.city_int)) { newText += "\n" + rJson.city_int; }
										if (rJson.state_int && $chk(rJson.state_int)) { 
											if (rJson.city_int && $chk(rJson.city_int)) {
												newText += " " + rJson.state_int; 
											} else {
												newText += "\n" + rJson.state_int; 
											}
										}			
										purchase_btw_total_invoice.set('value', 0);
										purchase_btw_total_invoice_display.set('value',0)
										this.calcPurchaseTotals(purchase_btw_total_invoice_display); 
										purchase_exbtw_row.setStyle('display','none');
										purchase_btw_row.setStyle('display','none');										
										purchase_total_invoice_display_btw_label.setStyle('display','none');
										purchase_nobtw_info.setStyle('display','block');										
										if (purchase_btw_editarea) { purchase_btw_editarea.setStyle('display','none'); }
									}
									if (rJson.country) { newText += "\n" + rJson.country; }							
								}																					
								clientTextarea.set('value', newText);
	//dbug.log(recipient_email.get('value'));							
							}.bind(this)
						}).send();
					}.bind(this)
				});
			}

			if (window.location.hash != '') {
				if (window.location.hash.contains('client_')) {
					var hashAr = window.location.hash.split('_');
					var clientId = hashAr[1].toInt();
//	dbug.log('client id = '+clientId);
					if (clientId) {
						this.invoiceSelectClient(clientId);
					}
				}
			}			
		}

		var purchase_exbtw_total_invoice = document.id('purchase_exbtw_total_invoice');
		var purchase_btw_total_invoice = document.id('purchase_btw_total_invoice');
		var purchase_total_invoice = document.id('purchase_total_invoice');
		var purchase_exbtw_total_invoice_display = document.id('purchase_exbtw_total_invoice_display');
		var purchase_btw_total_invoice_display = document.id('purchase_btw_total_invoice_display');
		var purchase_total_invoice_display = document.id('purchase_total_invoice_display');
						
		if (newPurchase) {	
			if (purchase_exbtw_total_invoice_display && purchase_btw_total_invoice_display && purchase_total_invoice_display && purchase_exbtw_total_invoice && purchase_btw_total_invoice && purchase_total_invoice) {
				purchase_btw_total_invoice_display.store('hiddenInput',purchase_btw_total_invoice).addEvents({
					'change':this.changePurchaseBtwTotal.bind(this, purchase_btw_total_invoice_display)
					,'keyup':this.changePurchaseBtwTotal.bind(this, purchase_btw_total_invoice_display)
					,'blur':this.changePurchaseBtwTotal.bind(this, [purchase_btw_total_invoice_display,true])					
				});
				purchase_total_invoice_display.store('hiddenInput',purchase_total_invoice).addEvents({
					'change':this.changePurchaseTotal.bind(this, purchase_total_invoice_display)
					,'keyup':this.changePurchaseTotal.bind(this, purchase_total_invoice_display)
					,'blur':this.changePurchaseTotal.bind(this, [purchase_total_invoice_display,true])					
				});
				purchase_exbtw_total_invoice_display.store('hiddenInput', purchase_exbtw_total_invoice);
			}
		} else if (updPurchase) {
//			if (purchase_exbtw_total_invoice_display && purchase_btw_total_invoice_display && purchase_total_invoice_display && purchase_exbtw_total_invoice && purchase_btw_total_invoice && purchase_total_invoice) {
//dbug.log('adding events for the totals');			
				var purchase_btw_total_invoice_editbtn = document.id('purchase_btw_total_invoice_editbtn');
				purchase_btw_total_invoice_editbtn.addEvent('click', function(e) { e.stop(); this.editablePurchaseBtwTotal(purchase_btw_total_invoice_display); }.bind(this) );
				var purchase_total_invoice_editbtn = document.id('purchase_total_invoice_editbtn');
				purchase_total_invoice_editbtn.addEvent('click', function(e) { e.stop(); this.editablePurchaseTotal(purchase_total_invoice_display); }.bind(this) );
				purchase_btw_total_invoice_display.store('hiddenInput',purchase_btw_total_invoice).addEvents({
					'change':this.changePurchaseBtwTotal.bind(this, purchase_btw_total_invoice_display)
					,'keyup':this.changePurchaseBtwTotal.bind(this, purchase_btw_total_invoice_display)
					,'blur':this.changePurchaseBtwTotal.bind(this, [purchase_btw_total_invoice_display,true])	
					,'click':this.editablePurchaseBtwTotal.bind(this, purchase_btw_total_invoice_display)									
				});
				purchase_total_invoice_display.store('hiddenInput',purchase_total_invoice).addEvents({
					'change':this.changePurchaseTotal.bind(this, purchase_total_invoice_display)
					,'keyup':this.changePurchaseTotal.bind(this, purchase_total_invoice_display)
					,'blur':this.changePurchaseTotal.bind(this, [purchase_total_invoice_display,true])					
					,'click':this.editablePurchaseTotal.bind(this, purchase_total_invoice_display)
				});
				purchase_exbtw_total_invoice_display.store('hiddenInput', purchase_exbtw_total_invoice);
//			}			
		} else {
			// when purchase is locked:
			var purchase_id = document.id('purchase_id');
			if (purchase_id) {
				var p_id = purchase_id.get('value').toInt();
			} 
			var purchase_is_paid = document.id('purchase_is_paid');
			var purchase_date_paid = document.id('purchase_date_paid');
			if (purchase_is_paid && purchase_date_paid && p_id > 0) {
				var ajaxurl = '/_x/purchase_set_paid';

				purchase_is_paid.addEvent('click',function(e){
					var checked = purchase_is_paid.get('checked');
					var is_paid = checked ? 1 : 0 ;
					var date_paid = purchase_date_paid.get('value');
					
					new Request.JSON({
						url:ajaxurl
						, method: 'post'
						, data: {'purchase_id':p_id, 'is_paid':is_paid, 'date_paid':date_paid}
						, onRequest: function() {

						}
						, onFailure: function() {

						}
						, onSuccess: function(rJson, rText) {
dbug.log(rJson);							
							if (rJson.saved) {
								var purchase_status_display = document.id('purchase_status_display');
								if (rJson.posted && purchase_status_display && $defined(rJson.posted.is_paid) && $defined(rJson.posted.date_paid)) {
									if (rJson.posted.is_paid.toInt() == 1) {
										var dated = new Date(rJson.posted.date_paid * 1000);
										purchase_status_display.set('text', mm.lang.status_purchase[rJson.posted.is_paid.toInt()]+': '+dated.format('%d-%m-%Y'));
									} else {
										purchase_status_display.set('text', mm.lang.status_purchase[rJson.posted.is_paid.toInt()]);
									}
								}
							} else {
								mm.noticeError.show({title:'fout bij opslaan'});
							}
						}
					}).send();
				}.bind(this));
				
				// different ajax datepicker:
				
				var next = purchase_date_paid.getNext('input[type=text][class~=timepicker]');
				var timePickerElement = false; 
				if ($defined(next)) { timePickerElement = next; }; 
				var startTimestamp = false;
				var initialStringVallue = false;
				var minimumDate = false;
				var maximumDate = false;			
				var altT = purchase_date_paid.get('alt');		
				if (altT!='') { 
					var extra = JSON.decode(altT);
					if (extra && extra.timestamp) { startTimestamp = extra.timestamp; }
					if (extra && extra.initialString) { initialStringVallue = extra.initialString; }	
					if (extra && extra.minDate) { 
						minimumDate = { date:extra.minDate, format:'U' }; 
	//dbug.log('MINDATE = '+extra.minDate);									
					}
					if (extra && extra.maxDate) { maximumDate = { date:extra.maxDate, format:'U'};  }

				}
				var toggleEl = null;
				var calendarImg = purchase_date_paid.getNext('img[class~=datepickerimg]');
	//dbug.log('calendarImg = '+calendarImg);			
				if (calendarImg) {
					toggleEl = calendarImg;
				}
				var calendar = new DatePicker(purchase_date_paid, {
					pickerClass: 'datepicker_dashboard',
				            inputOutputFormat: 'U'
				            , format: 'd-m-Y'
							, days: ['Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag']
							, months: ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'October', 'November', 'December']
				            , allowEmpty: false
							, toggleElement: toggleEl
							, debug: false
							, timePicker: false
							, startView: 'month'
							, startDate: startTimestamp
							, timePickerEl: timePickerElement
							, initialString: initialStringVallue	// input initial value other than a date formatted string
							, minDate: minimumDate
							, maxDate: maximumDate
							, onSelect: function() {
	//							alert(input.get('value'));
	//dbug.log('datepicker select');	
						var checked = purchase_is_paid.get('checked');
						var is_paid = checked ? 1 : 0 ;
						var date_paid = purchase_date_paid.get('value');

						new Request.JSON({
							url:ajaxurl
							, method: 'post'
							, data: {'purchase_id':p_id, 'is_paid':is_paid, 'date_paid':date_paid}
							, onRequest: function() {

							}
							, onFailure: function() {

							}
							, onSuccess: function(rJson, rText) {
	dbug.log(rJson);							
								if (rJson.saved) {
									var purchase_status_display = document.id('purchase_status_display');
									if (rJson.posted && purchase_status_display && $defined(rJson.posted.is_paid) && $defined(rJson.posted.date_paid)) {
										if (rJson.posted.is_paid.toInt() == 1) {
											var dated = new Date(rJson.posted.date_paid * 1000);
											purchase_status_display.set('text', mm.lang.status_purchase[rJson.posted.is_paid.toInt()]+': '+dated.format('%d-%m-%Y'));
										} else {
											purchase_status_display.set('text', mm.lang.status_purchase[rJson.posted.is_paid.toInt()]);
										}
									}
								} else {
									mm.noticeError.show({title:'fout bij opslaan'});
								}
							}
						}).send();	
						
								
							}.bind(this)
				      });			
				} // purchase paid
				
				
				var uploadLink = document.id('purchase_upload_link');
				if (uploadLink) {
					var uploadajaxurl = '/_x/purchase_attachment';
								var linkId = uploadLink.get('id');
								var progressBar = false;
								var loader = false;
								var deleteBtn = false;
								var fileDisplay = false;
								if ($defined(linkId) && linkId != '') {
									progressBar = document.id(linkId+'_progress');
									loader = document.id(linkId+'_loader');				
									fileDisplay = document.id(linkId+'_filename');
									deleteBtn = document.id(linkId+'_delete');				
								}
								var rel = uploadLink.get('rel');
								var ajaxUpdate = uploadLink.hasClass('ajaxUpdate');
								var alt = uploadLink.get('alt');
								if ($defined(rel) && rel!='') {
									var uploadtype = rel;
									var hiddenUploadFile = false;
									if ($defined(alt) && alt!='') {
										hiddenUploadFile = document.id(alt);
									}

									if (deleteBtn) {
										deleteBtn.addEvent('click', function(e){
											e.stop();
											hiddenUploadFile.set('value','');
											if (fileDisplay) {
												fileDisplay.empty();	
											}
											deleteBtn.setStyle('display','none');
											
											new Request.JSON({
												url:uploadajaxurl
												, method: 'post'
												, data: {'purchase_id':p_id, 'document':''}
												, onRequest: function() {

												}
												, onFailure: function() {

												}
												, onSuccess: function(rJson, rText) {
						dbug.log(rJson);							
													if (rJson.saved) {					
														// ok
													}
												}							
											}).send();
																						
										});
									}

									//https://'+mm.runtime.auth.username+'.moneymedic.eu
									//?__fmedic__='+mm.runtime.session_id
									var flashurl = '/uploadsingle';
									var extraData = {
										'uploadtype':uploadtype
										, 'username':mm.runtime.auth.username
									};
					//dbug.log('setupFancyUploadSingleLinks :'+flashurl);				
									var swf = new Swiff.Uploader({
										path: '/_img/plugins/fancyupload/Swiff.Uploader.swf',
										//url: 'https://wmadmin:k4n44lw3g@vic.moneymedic.eu/uploadsingle',
										url: flashurl,
										data: extraData,
										verbose: false,
										queued: false,
										multiple: false,
										target: uploadLink,
										instantStart: true,
										typeFilter: {
											'Bestanden (*.jpg, *.jpeg, *.gif, *.png, *.pdf, *.doc, *.txt, *.docx, *.xls, *.xlsx)': '*.jpg; *.jpeg; *.gif; *.png; *.pdf; *.doc; *.txt; *.docx, *.xls, *.xlsx'
										},
										fileSizeMax: 2 * 1024 * 1024,
										onSelectSuccess: function(files) {
											if (Browser.Platform.linux) window.alert('Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nSince you are prepared now, the upload will start right away ...');
					//dbug.log('Starting Upload', 'Uploading <em>' + files[0].name + '</em> (' + Swiff.Uploader.formatUnit(files[0].size, 'b') + ')');
											this.setEnabled(false);
										},
										onBeforeStart: function() {
					//dbug.log('onBeforeStart');								
											if (deleteBtn) { deleteBtn.setStyle('display','none'); }						
											if (loader) { loader.setStyle('display', 'block'); }
										},					
										onSelectFail: function(files) {
					alert('' + files[0].name + ' is te groot. Selecteer een afbeelding kleiner dan 2 Mb. (Error: #' + files[0].validationError + ')');
										},
										appendCookieData: true,
										onQueue: function() {
											if (!swf.uploading) return;
											var size = Swiff.Uploader.formatUnit(swf.size, 'b');
											if (progressBar) {
												progressBar.set('html', '<span class="small">' + swf.percentLoaded + '% of ' + size + '</span>');
											}
											//link.set('html', );						
										},
										onFileComplete: function(file) {

					//dbug.log('filecomplete: response = ');
					//dbug.log(JSON.decode(file.response.text));						
											if (file.response.error) {
					alert('Uploading ' + this.fileList[0].name + ' failed, please try again. (Error: #' + this.fileList[0].response.code + ' ' + this.fileList[0].response.error + ')');
											} else {
												//var md5 = JSON.decode(file.response.text, true).hash; // secure decode

												//log.alert('Successful Upload', 'an MD5 hash was created from <em>' + this.fileList[0].name + '</em>: <code>' + md5 + '</code>.<br />gravatar.com generated a fancy and unique monsterid for it, since we did not save the image.');

												//var img = $('demo-portrait');
												//img.setStyle('background-image', img.getStyle('background-image').replace(/\w{32}/, md5));
												//img.highlight();
					//dbug.log('upload succes');							
												rJson = JSON.decode(file.response.text);
											}
											var finalfilename = false;
											if ($defined(rJson.uploadtype) && $defined(rJson.filename)) {
												finalfilename = rJson.uploadtype+'/'+rJson.filename;
											}
											if (hiddenUploadFile && finalfilename) {
												hiddenUploadFile.set('value',finalfilename );
											}
											if (fileDisplay && finalfilename) {
												var finalfilelink = '<a href="/_f/'+mm.runtime.auth.username+'/'+finalfilename+'">'+rJson.filename.substr(11)+'</a>';
												fileDisplay.set('html', finalfilelink);
												if (deleteBtn) { deleteBtn.setStyle('display','inline-block'); }							
											}			
											if (progressBar) {
												progressBar.set('html', '');
											}			
											file.remove();
											this.setEnabled(true);
				
												new Request.JSON({
													url:uploadajaxurl
													, method: 'post'
													, data: {'purchase_id':p_id, 'document':finalfilename}
													, onRequest: function() {

													}
													, onFailure: function() {

													}
													, onSuccess: function(rJson, rText) {
dbug.log(rJson);							
														if (rJson.saved) {					
															// ok
														}
													}							
												}).send();						

										},
										onComplete: function() {
											//link.set('html', 'klik again');
											if (loader) { loader.setStyle('display', 'none');  }						

										}
									});

									// Button state
									uploadLink.addEvents({
										click: function() {
											return false;
										},
										mouseenter: function() {
											this.addClass('hover');
											swf.reposition();
										},
										mouseleave: function() {
											this.removeClass('hover');
											this.blur();
										},
										mousedown: function() {
											this.focus();
										}
									});
							}
	
					}  // uploadLink		

			} // locked
	}
	, editablePurchaseBtwTotal:function(input) {
		if (!input.retrieve('isEditable', false)) {
			input.store('isEditable', true).addClass('isEditable').set('readonly',false).removeClass('disabled').set('disabled', false);									
			var purchase_btw_total_invoice_editbtn = document.id('purchase_btw_total_invoice_editbtn');			
			purchase_btw_total_invoice_editbtn.setStyle('display','none');
			input.focus();
		} 		
	}
	, editablePurchaseTotal:function(input) {
		if (!input.retrieve('isEditable', false)) {
//			input.store('isEditable', false).setStyles({'background-color':'transparent'}).set('readonly',true);
			input.store('isEditable', true).addClass('isEditable').set('readonly',false).removeClass('disabled').set('disabled', false);									
			var purchase_total_invoice_editbtn = document.id('purchase_total_invoice_editbtn');			
			purchase_total_invoice_editbtn.setStyle('display','none');
			input.focus();			
		} 
	}
	, changePurchaseBtwTotal:function(input,blur) {
		var value = input.get('value');
		var valreplaced = value.replace(/\,/g,'.');	
		var hiddenInput = input.retrieve('hiddenInput');	
		hiddenInput.set('value',valreplaced.toFloat());
		if (blur) {
			input.set('value', valreplaced.toFloat().numberFormat(2,',',''));
			var update_purchase = document.id('update_purchase');
			if (update_purchase) { 
				if (update_purchase.get('value') == 1) { 
					input.store('isEditable', false).removeClass('isEditable').set('readonly',true).addClass('disabled').set('disabled', true);
					var purchase_btw_total_invoice_editbtn = document.id('purchase_btw_total_invoice_editbtn');			
					purchase_btw_total_invoice_editbtn.setStyle('display','inline-block');					
				} 
			}			
		}		
		this.calcPurchaseTotals(input);		
	}
	, changePurchaseTotal:function(input, blur) {
		var value = input.get('value');
		var valreplaced = value.replace(/\,/g,'.');	
		var hiddenInput = input.retrieve('hiddenInput');	
		hiddenInput.set('value',valreplaced.toFloat());		
		if (blur) {
			input.set('value', valreplaced.toFloat().numberFormat(2,',',''));
			var update_purchase = document.id('update_purchase');
			if (update_purchase) { 
				if (update_purchase.get('value') == 1) { 
					input.store('isEditable', false).removeClass('isEditable').set('readonly',true).addClass('disabled').set('disabled', true);
					var purchase_total_invoice_editbtn = document.id('purchase_total_invoice_editbtn');			
					purchase_total_invoice_editbtn.setStyle('display','inline-block');					
				} 
			}			
		}
		this.calcPurchaseTotals(input);		
	}
	, calcPurchaseTotals:function(frominput) {
//dbug.log('calcPurchaseTotals');		
		var purchase_exbtw_total_invoice_display = document.id('purchase_exbtw_total_invoice_display');
		var purchase_btw_total_invoice_display = document.id('purchase_btw_total_invoice_display');
		var purchase_total_invoice_display = document.id('purchase_total_invoice_display');
		var purchase_exbtw_total_invoice = document.id('purchase_exbtw_total_invoice');
		var purchase_btw_total_invoice = document.id('purchase_btw_total_invoice');
		var purchase_total_invoice = document.id('purchase_total_invoice');	
		var total = purchase_total_invoice.get('value');
		var btw = purchase_btw_total_invoice.get('value');
		var ex = (total - btw).toFloat();
		purchase_exbtw_total_invoice.set('value',ex);	
		purchase_exbtw_total_invoice_display.set('html', ex.round(2).numberFormat(2,',',''));
	}
	, ajaxReady_invoice:function() {
		// only invoice view specific ajaxReady function
		var updConcept = false;
		var updEstimate = false;		
		var newConcept = false;
		var isConcept = false;
		var isEstimate = false;		
		var hasEstimate = false;
		var hasReminder_1 = false;
		var hasReminder_2 = false;
		var hasReminder_3 = false;				
		var update_concept = document.id('update_concept');
		var update_estimate = document.id('update_estimate');	
		var new_concept = document.id('new_concept');		
		var is_concept = document.id('is_concept');	
		var is_estimate = document.id('is_estimate');			
		var has_estimate = document.id('has_estimate');
		var has_reminder_1 = document.id('has_reminder_1');			
		var has_reminder_2 = document.id('has_reminder_2');
		var has_reminder_3 = document.id('has_reminder_3');				
		if (has_estimate) { if (has_estimate.get('value') == 1) { hasEstimate = true; } }
		if (update_concept) { if (update_concept.get('value') == 1) { updConcept = true; } }
		if (update_estimate) { if (update_estimate.get('value') == 1) { updEstimate = true; } }		
		if (new_concept) { if (new_concept.get('value') == 1) { newConcept = true; } }
		if (is_concept) { if (is_concept.get('value') == 1) { isConcept = true; } }
		if (is_estimate) { if (is_estimate.get('value') == 1) { isEstimate = true; } }		
		if (has_reminder_1) { if (has_reminder_1.get('value') == 1) { hasReminder_1 = true; } }		
		if (has_reminder_2) { if (has_reminder_2.get('value') == 1) { hasReminder_2 = true; } }		
		if (has_reminder_3) { if (has_reminder_3.get('value') == 1) { hasReminder_3 = true; } }						
		
		
				
		// client select, product select etc
		if ( (isConcept && (newConcept || updConcept)) || (isEstimate && updEstimate) ) {
			var clientSelect = document.id('selectClient');
			var clientTextarea = document.id('client_static_text');
			if (clientSelect) {
				clientSelect.addEvents({
					'change':function(e) {
						var client_id = clientSelect.get('value');
// dbug.log('clientSelect change: '+clientSelect.get('value'));		
						if (client_id == '') { 
							clientTextarea.set('value', '');
							clientTextarea.addClass('validation-failed');
							return false; 
						} else {
							if (clientTextarea.hasClass('validation-failed')) {
								clientTextarea.removeClass('validation-failed');
							}							
						}
						var ajaxurl = '/_x/clientdetails';
						var postdata = {id:client_id};
						new Request.JSON({
							url: ajaxurl
							, method: 'post'
							, data: postdata
							, onRequest: function() {

							}
							, onFailure: function() {

							}
							, onSuccess: function(rJson, rText) {	
								var newText = '';
								if (rJson.name_company) { newText += rJson.name_company; }
								if (rJson.name_contact) { newText += "\n" + rJson.name_contact; }							
								if (rJson.country_code) {								
									if (rJson.country_code == 'NL') {
										if (rJson.address_nl && $chk(rJson.address_nl)) { newText += "\n" + rJson.address_nl; }
										if (rJson.address_num_nl && $chk(rJson.address_num_nl)) { newText += ' '+rJson.address_num_nl; }
										if (rJson.address_num_extra_nl && $chk(rJson.address_num_extra_nl)) { newText += ' '+rJson.address_num_extra_nl; }										
										if (rJson.postal_num_nl || rJson.postal_alpha_nl || rJson.city_nl) {
											newText += "\n";
											if (rJson.postal_num_nl && $chk(rJson.postal_num_nl)) { newText +=  rJson.postal_num_nl; }	
											if (rJson.postal_alpha_nl && $chk(rJson.postal_alpha_nl)) { newText +=  ' '+rJson.postal_alpha_nl; }									
											if (rJson.city_nl && $chk(rJson.city_nl)) { newText +=  ' '+rJson.city_nl; }								
										}
									} else {
										if (rJson.address_1_int && $chk(rJson.address_1_int)) { newText += "\n" + rJson.address_1_int; }									
										if (rJson.address_2_int && $chk(rJson.address_2_int)) { newText += "\n" + rJson.address_2_int; }
										if (rJson.postal_int && $chk(rJson.postal_int)) { newText += "\n" + rJson.postal_int; }										
										if (rJson.city_int && $chk(rJson.city_int)) { newText += "\n" + rJson.city_int; }
										if (rJson.state_int && $chk(rJson.state_int)) { 
											if (rJson.city_int && $chk(rJson.city_int)) {
												newText += " " + rJson.state_int; 
											} else {
												newText += "\n" + rJson.state_int; 
											}
										}										
									}
									if (rJson.country) { newText += "\n" + rJson.country; }							
								}
								clientTextarea.set('value', newText);
								var recipient_email = document.id('recipient_email');
								if (rJson.email) {
									recipient_email.set('value', rJson.email);
								} else {
									recipient_email.set('value', '');								
								}
								var client_nr_display = document.id('client_nr_display');
								var client_nr_label = document.id('client_nr_label');
								if (client_nr_display && client_nr_label) {
									if (rJson.debit_nr_display && $chk(rJson.debit_nr_display)) {
										client_nr_display.set('html', rJson.debit_nr_display).setStyle('display','block');
										client_nr_label.setStyle('display','block');										
									} else {
										client_nr_display.setStyle('display','none');
										client_nr_label.setStyle('display','none');										
									}
								}
	//dbug.log(recipient_email.get('value'));							
							}
						}).send();
					}.bind(this)
				});
				var clientSelectOptions = clientSelect.getElements('option');
				if (clientSelectOptions.length == 1) {
					clientSelect.addEvent('click', function(e) {
						e.stop();
						mm.overlayAll.showDialog('/client');
						clientSelect.blur();
					}.bind(this));
				}
			}
		}
		
		/*
		// INVOICE TITLE
		var editTitleBtn = document.id('invoice_title_btn');
		var spanTitle = document.id('invoice_title_span');
		var hiddenTitle = document.id('invoice_title');
		if (editTitleBtn && spanTitle && hiddenTitle) {
			editTitleBtn.addEvent('click', function(e) {
				e.stop();
				var oldtitle = spanTitle.get('text');				
				spanTitle.set('text','');
				var input = new Element('input', {'class':'w400'}).set('value',oldtitle).inject(spanTitle);
				editTitleBtn.setStyle('display', 'none');				
				input.addEvent('blur', function(e) {
					var newtitle = this.get('value');
					this.destroy();
					spanTitle.set('text', newtitle);
					hiddenTitle.set('value', newtitle);
					editTitleBtn.setStyle('display', 'inline-block');
//dbug.log('new hidden title = '+document.id('invoice_title').get('value'));					
				}.bind(input));
				input.focus();
			});
		}
		*/
		if (newConcept || updConcept || updEstimate) {
			// PRODUCTS TABLE		
			var invoiceProductsTable = document.id('invoiceProductsTable');
			var invoiceProductRows = invoiceProductsTable.getElements('tr[class~=invoiceProductRow]');		
dbug.log('product rows length = '+invoiceProductRows.length);			
			var rowBtn = document.id('invoice_product_row_btn');
			var all_products_json = document.id('all_products_json');
			var all_btw_json = document.id('all_btw_json');
				mm.products = new Hash({});
				mm.btw = new Hash({});
				var prArray = JSON.decode(all_products_json.get('value'));
				var btwArray = JSON.decode(all_btw_json.get('value'));
	//dbug.log(prArray);			
	//dbug.log(btwArray);			
				prArray.each(function(product){
					var t = product.list_title;
					if (t == '') {
						t = product.title;
					}
					var prHash = new Hash({title:t, price:product.price, btw_tariff:product.btw_tariff, description:product.description});
					mm.products.set(product.id, prHash);
				});
				btwArray.each(function(btw) {
					var btwHash = new Hash({id:btw.id, tariff:btw.tariff});
					mm.btw.set(btw.tariff, btwHash);
				});
	//dbug.log(mm.btw);
			all_products_json.destroy();
			all_btw_json.destroy();
		}

		
		if (invoiceProductsTable && (updConcept || newConcept || updEstimate)) {			
			
			// PRODUCT TR ROWS
			if (invoiceProductRows.length > 0) {
				invoiceProductRows.each(function(row){
					row.addEvents({
						'outerClick': this.deactivateInvoiceProductRow.bind(this,row)
						, 'click' : this.activateInvoiceProductRow.bind(this,row)
						, 'mouseenter': this.enterInvoiceProductRow.bind(this, row)
						, 'mouseleave': this.leaveInvoiceProductRow.bind(this, row)						
					});
				},this);
			}
			
			var productsSortable = new Sortables(invoiceProductsTable.getElement('tbody'), {
				handle: 'div.invoiceProductRowHandle'
				, constrain:true
				, clone: false
				, opacity: 0.4
				, revert: { duration: 500, transition: 'circ:out' } 
				
			});
			invoiceProductsTable.store('sortable', productsSortable);
			
			// PRODUCT SELECTS
			var invoiceProductSelects = invoiceProductsTable.getElements('select[class~=invoiceProductSelect]');
			if (invoiceProductSelects.length > 0) {
				invoiceProductSelects.each(function(sel){
//dbug.log('hier een select');					
					var parentRow = sel.getParent('tr.invoiceProductRow');										
					var productTitle = sel.options[sel.selectedIndex].text; //.get('text');
//dbug.log('title = '+productTitle);
					var productSpan = new Element('span', {'class':'invoiceProductSelectDisplaySpan', 'html':productTitle }).inject(sel, 'after');					
					//productSpan.set('text', sel.options[sel.selectedIndex].get('text'));
					sel.store('displaySpan', productSpan).store('isEditable', false);
					sel.addEvent('change', this.changeInvoiceProductSelect.bind(this,sel));
					var productOptions = sel.getElements('option');
					if (productOptions.length == 1) {
						sel.addEvent('click', function(e) {
							e.preventDefault();
							mm.overlayAll.showDialog('/product', {'parentRow':parentRow});							
							sel.blur();
						}.bind(this));
					}
					sel.setStyle('display','none');
					productSpan.addEvent('click', this.activateInvoiceProductRow.bind(this,parentRow));
/*	
					sel.addEvent('change', function(e) {
						var parentRow = sel.getParent('tr.invoiceProductRow');
						var newProductId = sel.get('value');
dbug.log('change, new id='+newProductId);						
						var productSelectHidden = parentRow.getElement('input[class~=invoiceProductSelectHidden]');
						productSelectHidden.set('value', mm.products.get(newProductId).get('title'));
					});*/

				},this);
			}
			var invoiceProductAdds = invoiceProductsTable.getElements('a.invoiceProductAdd');
			if (invoiceProductAdds.length > 0) {
				invoiceProductAdds.each(function(link) {
					var parentRow = link.getParent('tr.invoiceProductRow');												
					link.set('href', '#');
					link.addEvent('click', function(e) {
						e.stop();
//						parentRow.removeEvents('outerClick');						
						mm.overlayAll.showDialog('/product', {'parentRow':parentRow});
					});
				});
			}
			// PRODUCT QUANTITY INPUTS
			var invoiceProductQuantitys = invoiceProductsTable.getElements('input[class~=invoiceProductQuantity]');			
			if (invoiceProductQuantitys.length > 0) {
				invoiceProductQuantitys.each(function(input){
					var parentRow = input.getParent('tr.invoiceProductRow');					
					var invoiceProductQuantityDisplaySpan = new Element('span', {'class':'invoiceProductQuantityDisplaySpan w20 txt-center'}).set('html', input.get('value')).inject(input, 'after');
					input.store('displaySpan', invoiceProductQuantityDisplaySpan).setStyle('display','none');
					input.addEvents({
						'change':this.changeInvoiceProductQuantity.bind(this, input)
						,'keyup':this.changeInvoiceProductQuantity.bind(this, input)
						,'blur':this.changeInvoiceProductQuantity.bind(this, [input,true])						
					});
					invoiceProductQuantityDisplaySpan.addEvent('click', this.activateInvoiceProductRow.bind(this,parentRow));
				},this);
			}
			// PRODUCT PRICE INPUTS			
			var invoiceProductPrices = invoiceProductsTable.getElements('input[class~=invoiceProductPrice]');			
			if (invoiceProductPrices.length > 0) {
				invoiceProductPrices.each(function(input){
					var parentRow = input.getParent('tr.invoiceProductRow');					
					var invoiceProductPriceDisplaySpan = new Element('span', {'class':'invoiceProductPriceDisplaySpan wp80 txt-right'}).set('html', input.get('value')).inject(input, 'after');
					input.store('displaySpan', invoiceProductPriceDisplaySpan).setStyle('display','none');					
					input.addEvents({
						'change':this.changeInvoiceProductPrice.bind(this, input)
						,'keyup':this.changeInvoiceProductPrice.bind(this, input)
						,'blur':this.changeInvoiceProductPrice.bind(this, [input,true])						
					});
					var invoiceProductCurrencyPrice = input.getPrevious('span.invoiceProductCurrency');
//dbug.log('invoiceProductCurrencyPrice = '+invoiceProductCurrencyPrice);					
					input.store('displayCurrency', invoiceProductCurrencyPrice);
					invoiceProductPriceDisplaySpan.addEvent('click', this.activateInvoiceProductRow.bind(this,parentRow));	
				},this);
			}		
			// PRODUCT BTW SELECTS
			var invoiceProductBtws = invoiceProductsTable.getElements('select[class~=invoiceProductBtw]');	
			if (invoiceProductBtws.length > 0) {
				invoiceProductBtws.each(function(sel){
					var parentRow = sel.getParent('tr.invoiceProductRow');					
					var invoiceProductBtwDisplaySpan = new Element('span', {'class':'invoiceProductBtwDisplaySpan w40 txt-center'}).set('html', sel.options[sel.selectedIndex].text).inject(sel, 'after');					
					sel.store('displaySpan', invoiceProductBtwDisplaySpan).store('isEditable', false);					
					invoiceProductBtwDisplaySpan.addEvent('click', this.activateInvoiceProductRow.bind(this,parentRow));					
					sel.setStyle('display','none').addEvent('change', this.changeInvoiceProductBtw.bind(this, sel));
				},this);
			}
			//PRODUCT DESCRIPTIONS
			var invoiceProductDescriptions = invoiceProductsTable.getElements('textarea[class~=invoiceProductDescription]');	
			if (invoiceProductDescriptions.length > 0) {
				invoiceProductDescriptions.each(function(textarea) {
					var parentRow = textarea.getParent('tr.invoiceProductRow');	
					var textareaGrow = new mm.TextareaGrow(textarea, {minSize:30});
//					var textarea = new Element('textarea', {'class':'editSpanTextarea wp100'}).set('value',oldcnt.replace(/\<br\>/g,"\r")).inject(editSpanText);
					var cnt = textarea.get('value').replace(/\n/g,'<br>');					
					var invoiceProductDescriptionDisplaySpan = new Element('div', {'class':'invoiceProductDescriptionDisplaySpan wp100'}).set('html', cnt).inject(textarea, 'after');				
					textarea.store('textareaGrow', textareaGrow).store('displaySpan', invoiceProductDescriptionDisplaySpan).setStyle('display','none');
					invoiceProductDescriptionDisplaySpan.addEvent('click', this.activateInvoiceProductRow.bind(this,parentRow));
				},this);
			}
			//PRODUCT TOTALS INPUTS
			var invoiceProductTotals = invoiceProductsTable.getElements('input[class~=invoiceProductTotal]');	
			if (invoiceProductTotals.length > 0) {
				invoiceProductTotals.each(function(input) {
					var parentRow = input.getParent('tr.invoiceProductRow');
					var invoiceProductCurrencyTotal = input.getPrevious('span.invoiceProductCurrency');										
					input.store('displayCurrency', invoiceProductCurrencyTotal);					
				},this);
			}
		}
		// ADD PRODUCT ROW BTN
		if (invoiceProductsTable && rowBtn && (updConcept || newConcept || updEstimate)) {
			rowBtn.addEvent('click', function(e) {
				//e.stop();
				e.preventDefault();
//dbug.log('rowBtn click');				
				var lastRow = invoiceProductsTable.getFirst('tbody').getLast('tr');
				var newRow = lastRow.clone(true);
				
				var invoiceProductRows = invoiceProductsTable.getElements('tr[class~=invoiceProductRow]');
				if (invoiceProductRows.length > 0) {
					invoiceProductRows.each(function(row){									
						//this.deactivateInvoiceProductRow(row);
					},this);
				}				
				newRow.store('isEditable', true).addClass('invoiceProductRowEditable').addEvents({
					'outerClick': this.deactivateInvoiceProductRow.bind(this,newRow)
					, 'click' : this.activateInvoiceProductRow.bind(this,newRow)
					, 'mouseenter': this.enterInvoiceProductRow.bind(this, newRow)
					, 'mouseleave': this.leaveInvoiceProductRow.bind(this, newRow)					
				});
				
//hier
				var lastCell = newRow.getLast('td');
//				var deleteBtn = new Element('a', {'href':'#','class':'invoiceProductDeleteBtn'}).inject(lastCell);
//				deleteBtn.setStyles({'diplay':'block', 'position':'absolute','width':'24px','height':'24px','text-align':'center','right':'-32px'}).set('html','X');

				//newRow.cloneEvents(lastRow); // need to happen for each el with events
				
				var lastProductSelect = lastRow.getElement('select[class~=invoiceProductSelect]');
				var lastProductSelectHidden = lastRow.getElement('input[class~=invoiceProductSelectHidden]');				
				var lastProductQuantityHidden = lastRow.getElement('input[class~=invoiceProductQuantityHidden]');				
				var lastProductQuantity = lastRow.getElement('input[class~=invoiceProductQuantity]');
				var lastProductDescription = lastRow.getElement('textarea[class~=invoiceProductDescription]');
				var lastProductBtw = lastRow.getElement('select[class~=invoiceProductBtw]');
				var lastProductPriceHidden = lastRow.getElement('input[class~=invoiceProductPriceHidden]');				
				var lastProductPrice = lastRow.getElement('input[class~=invoiceProductPrice]');
				var lastProductTotal = lastRow.getElement('input[class~=invoiceProductTotal]');				
				
				var newProductSelect = newRow.getElement('select[class~=invoiceProductSelect]');
				var newProductAddBtn = newRow.getElement('a.invoiceProductAdd');
				var newProductDeleteBtn = newRow.getElement('a.invoiceProductDeleteBtn');
				newProductDeleteBtn.addEvent('click',function(e) {
					e.stop();
					this.deleteInvoiceProductRow(newRow);
				}.bind(this));				
				var newProductSelectDisplaySpan = newRow.getElement('span[class~=invoiceProductSelectDisplaySpan]');				
				var newProductSelectHidden = newRow.getElement('input[class~=invoiceProductSelectHidden]');				
				var newProductQuantity = newRow.getElement('input[class~=invoiceProductQuantity]');
				var newProductQuantityDisplaySpan = newRow.getElement('span[class~=invoiceProductQuantityDisplaySpan]');
				var newProductQuantityHidden = newRow.getElement('input[class~=invoiceProductQuantityHidden]');				
				var newProductDescription = newRow.getElement('textarea[class~=invoiceProductDescription]');
				var newProductDescriptionDisplaySpan = newRow.getElement('div[class~=invoiceProductDescriptionDisplaySpan]');
				var newProductBtw = newRow.getElement('select[class~=invoiceProductBtw]');
				var newProductBtwDisplaySpan = newRow.getElement('span[class~=invoiceProductBtwDisplaySpan]');				
				var newProductPrice = newRow.getElement('input[class~=invoiceProductPrice]');
				var newProductPriceDisplaySpan = newRow.getElement('span[class~=invoiceProductPriceDisplaySpan]');	
				var newProductPriceHidden = newRow.getElement('input[class~=invoiceProductPriceHidden]');				
				var newProductTotal = newRow.getElement('input[class~=invoiceProductTotal]');
				var newProductTotalCurrency = newProductTotal.getPrevious('span.invoiceProductCurrency');
				newProductTotal.store('displayCurrency', newProductTotalCurrency);
				var newProductCurrencyPrice = newProductPrice.getPrevious('span.invoiceProductCurrency');
				newProductPrice.store('displayCurrency', newProductCurrencyPrice);	
							
				
				
				//newProductSelect.cloneEvents(lastProductSelect);
				//newProductBtw.cloneEvents(lastProductBtw);
				//new mm.TextareaGrow(newProductDescription, {minSize:30});
				newProductSelect.addEvent('change', this.changeInvoiceProductSelect.bind(this,newProductSelect));
				newProductSelect.store('displaySpan', newProductSelectDisplaySpan);
				newProductSelectDisplaySpan.setStyle('display', 'none').addEvent('click', this.activateInvoiceProductRow.bind(this,newRow));
				newProductSelect.setStyle('display','inline-block');
				newProductBtw.addEvent('change', this.changeInvoiceProductBtw.bind(this, newProductBtw));
				newProductBtw.store('displaySpan', newProductBtwDisplaySpan);
				newProductBtwDisplaySpan.setStyle('display', 'none').addEvent('click', this.activateInvoiceProductRow.bind(this,newRow));
				newProductQuantity.store('displaySpan',newProductQuantityDisplaySpan);
				newProductQuantityDisplaySpan.setStyle('display','none').addEvent('click', this.activateInvoiceProductRow.bind(this,newRow)).set('text',1);
				newProductPrice.store('displaySpan', newProductPriceDisplaySpan);
				newProductPriceDisplaySpan.setStyle('display','none').addEvent('click', this.activateInvoiceProductRow.bind(this,newRow));
				newProductDescription.setStyle('display','inline-block').store('displaySpan', newProductDescriptionDisplaySpan);	
				newProductDescriptionDisplaySpan.setStyle('display','none').addEvent('click', this.activateInvoiceProductRow.bind(this,newRow));
				newProductQuantity.addEvents({
					'change':this.changeInvoiceProductQuantity.bind(this, newProductQuantity)
					,'keyup':this.changeInvoiceProductQuantity.bind(this, newProductQuantity)
					,'blur':this.changeInvoiceProductQuantity.bind(this, [newProductQuantity,true])
				});
				newProductPrice.addEvents({
					'change':this.changeInvoiceProductPrice.bind(this, newProductPrice)
					,'keyup':this.changeInvoiceProductPrice.bind(this, newProductPrice)
					,'blur':this.changeInvoiceProductPrice.bind(this, [newProductPrice,true])
				});				
				newProductAddBtn.set('href','#').addEvent('click',function(e){
					e.stop();
//					newRow.removeEvents('outerClick');
					mm.overlayAll.showDialog('/product', {'parentRow':newRow});
				});				

				newProductDescription.set('value', '').setStyles({'height':'30px'});
				newRow.set('tween',{duration:250,transition:'circ:out'}).setStyles({opacity:0}).inject(lastRow,'after').fade(1);
				var textareaGrow = new mm.TextareaGrow(newProductDescription, {minSize:30});
				newProductDescription.store('textareaGrow', textareaGrow);								
				newProductSelect.set('value','').fireEvent('change');
								
				this.calcInvoiceTotals();				
				invoiceProductsTable.retrieve('sortable').addItems(newRow);
				this.activateInvoiceProductRow.delay(10,this,[newRow,true]);
				rowBtn.setStyle('display','none');
			}.bind(this));
		}
		if (newConcept || updConcept || updEstimate) {
			/*
			var checkbox_is_periodic = document.id('checkbox_is_periodic');
			var invoice_is_periodic_properties = document.id('invoice_is_periodic_properties');
			if (checkbox_is_periodic && invoice_is_periodic_properties) {
				checkbox_is_periodic.addEvent('click', function(e) {
					if (checkbox_is_periodic.get('checked')==true) {
						invoice_is_periodic_properties.removeClass('none');
					} else {
						invoice_is_periodic_properties.addClass('none');						
					}
				});
			}
			*/
			var invoice_types = document.getElements('input[type=radio][name=invoice_type]');
			invoice_types.each(function(radio) {
				radio.addEvent('click', function(e) {
					var invoiceForm = radio.getParent('form.invoiceForm');
					var invoice_types_radios = invoiceForm.getElements('input[type=radio][name=invoice_type]');
					invoice_types_radios.each(function(iradio) {
						if (iradio.get('checked')) {
							invoiceForm.store('invoice_type', iradio.get('value'));
						}
					});
					this.changeInvoiceType(invoiceForm.retrieve('invoice_type'));
				}.bind(this));
				// setting start value
				var invoiceForm = radio.getParent('form.invoiceForm');
				if (radio.get('checked')) {
					invoiceForm.store('invoice_type', radio.get('value'));
				}					
			},this);
			
		}

		
		if (newConcept && !updConcept && invoiceProductRows.length == 1  ) {
			var firstRow = invoiceProductRows[0];
			var firstProduct = firstRow.getElement('select[class~=invoiceProductSelect]');
			/*
			if (firstProduct) {
				firstProduct.fireEvent('change');
				this.deactivateInvoiceProductRow.delay(50,this,invoiceProductRows[0]);			
			}
			*/
			var lastCell = firstRow.getLast('td');
			var deleteBtn = new Element('a', {'href':'#','class':'invoiceProductDeleteBtn'}).set('html','<img border="0" src="/_img/icons/payment_delete.png"/>').inject(lastCell);
//			deleteBtn.setStyles({'diplay':'block', 'position':'absolute','width':'24px','height':'24px','text-align':'center','right':'-32px'}).set('html','X');
			deleteBtn.addEvent('click',function(e) {
				e.stop();
				this.deleteInvoiceProductRow(firstRow);
			}.bind(this));			
			this.hideProductRowInputs(invoiceProductRows[0]);
			//this.activateInvoiceProductRow.delay(50,this, invoiceProductRows[0]);
		} else if (updConcept || updEstimate){
			invoiceProductRows.each(function(row,i){
//dbug.log('productRow:'+i+' change');				
				var productSel = row.getElement('select[class~=invoiceProductSelect]');
				//productSel.fireEvent('change'); 											
				this.deactivateInvoiceProductRow.delay(10,this,invoiceProductRows[i]);	
				this.calcInvoiceTotals();
//				if (i!=0) {
					var lastCell = row.getLast('td');
					var deleteBtn = new Element('a', {'href':'#','class':'invoiceProductDeleteBtn'}).set('html','<img border="0" src="/_img/icons/payment_delete.png"/>').inject(lastCell);
					deleteBtn.addEvent('click',function(e) {
						e.stop();
						this.deleteInvoiceProductRow(row);
					}.bind(this));				
//				}						
			},this);

		}
		
		if (!newConcept) {
			var duplicate_invoice_links = document.getElements('a[class~=duplicate_invoice_link]');
			if (duplicate_invoice_links.length > 0) {
				duplicate_invoice_links.each(function(duplicate_invoice_link) {
					var href = duplicate_invoice_link.get('href');
					duplicate_invoice_link.set('href', '#');
					if (href.charAt(0)=='/') { href = href.substr(1,href.length); }											
					var ajaxurl = '/_x/'+href;
					duplicate_invoice_link.addEvent('click', function(e) {
						e.stop();
						new Request.JSON({
							url: ajaxurl
							, method: 'post'
							, onRequest: function() {
								mm.overlayAll.show();
								mm.overlayAll.showNotice('loading', mm.lang.notice_info.saving);							
							}
							, onFailure: function() {
							//	if (overlay) { overlay.setStyles({'display':'none'});	}		
								mm.overlayAll.hide(true);
							}
							, onSuccess: function(rJson, rText) {
// dbug.log(rJson);			
								if (rJson.saved) {
									if ($defined(rJson.insert_id)) {
										window.location.href = '/invoice/'+rJson.insert_id;
									} else {
										window.location.href = '/invoices#concepts';
									}	
								} else {
									mm.overlayAll.hide(true);								
									mm.noticeError.show({title:'fout bij dupliceren'});
								}
							}
						}).send();
					});
				});
			}
		}
		
		var auto_send_reminder = document.id('auto_send_reminder');
		if (auto_send_reminder) {
			auto_send_reminder.addEvent('click', function(e) {
				var ch = (auto_send_reminder.get('checked')) ? 1 : 0 ; 
				var invoice_id = document.id('invoice_id').get('value').toInt();
//dbug.log('change auto_send_reminder to : '+ch);
				var chdata = {'invoice_id':invoice_id, 'do_send' : ch};
				var ajaxurl = '/_x/auto_send_reminder';
				new Request.JSON({
					url: ajaxurl
					, method: 'post'
					, data: chdata
					, onRequest: function() {
						
					}
					, onFailure: function() {
					//	if (overlay) { overlay.setStyles({'display':'none'});	}							
					}
					, onSuccess: function(rJson, rText) {
//dbug.log(rJson);						
					}					
				}).send();
			});
		}
		
//dbug.log(window.location.hash);		
		if (window.location.hash != '') {
			if (window.location.hash.contains('client_')) {
				var hashAr = window.location.hash.split('_');
				var clientId = hashAr[1].toInt();
//dbug.log('client id = '+clientId);
				if (clientId) {
					this.invoiceSelectClient(clientId);
				}
			}
		}
		
		/*
		var section_5 = document.body.getElement('.invoiceSection_5');
		var oldHeight = section_5.getStyle('height');		
		section_5.setStyles({'height': 'auto', 'min-height':oldHeight});		
		*/		
		var contentCenterInvoice = document.body.getElement('.contentCenterInvoice');
		var oldCheight = contentCenterInvoice.getStyle('height');
		contentCenterInvoice.setStyles({'height':'auto','min-height':oldCheight});
				
	}
	, changeInvoiceType:function(invoice_type) {		
//dbug.log('changeInvoiceType to : '+invoice_type);		
		var invoiceTypeMultiplier = 1;
		if (invoice_type=='credit') { invoiceTypeMultiplier = -1; }
		var invoiceProductsTable = document.id('invoiceProductsTable');
		var invoiceProductRows = invoiceProductsTable.getElements('tr[class~=invoiceProductRow]');
		if (invoiceProductRows.length > 0) {
			invoiceProductRows.each(function(parentRow) {				
				this.updateInvoiceTypeProductRowPrices(parentRow, invoiceTypeMultiplier);
			},this);
		}		
	}
	, updateInvoiceTypeProductRowPrices:function(parentRow, invoiceTypeMultiplier) {
//dbug.log('updateInvoiceTypeProductRowPrices mult:'+invoiceTypeMultiplier);		
		var productPrice = parentRow.getElement('input[class~=invoiceProductPrice]');
		var productPriceHidden = parentRow.getElement('input[class~=invoiceProductPriceHidden]');		
		var newprice = Math.abs(productPriceHidden.get('value').toFloat());
		if (invoiceTypeMultiplier == 1) {
			productPriceHidden.set('value', newprice);
		} else {
			newprice = newprice * invoiceTypeMultiplier;
			productPriceHidden.set('value', newprice);			
		}
		var displayPrice = newprice.round(2).numberFormat(2, ',','');
		productPrice.retrieve('displaySpan').set('html', displayPrice);
		productPrice.set('value', displayPrice);		
		this.calcInvoiceProductRow(parentRow);		
	}
	, deleteInvoiceProductRow:function(parentRow) {
		var invoiceProductsTable = document.id('invoiceProductsTable');
		var invoiceProductRows = invoiceProductsTable.getElements('tr[class~=invoiceProductRow]');
		if (invoiceProductRows.length > 1) {		
			parentRow.removeEvents();
			parentRow.destroy();
			this.checkInvoiceProductRowsAddDelete();
			this.calcInvoiceTotals();
			this.calcInvoiceProductRowsHeight();		
		}
	}
	, invoiceSelectClient:function(clientId) {
		var clientSelect = document.id('selectClient');
		var options = clientSelect.getElements('option');
		var found = false;
		options.each(function(option) {
			if (option.get('value')==clientId) {
				found = true;
			}				
		});
		if (found) {
			clientSelect.set('value', clientId);
			clientSelect.fireEvent('change');
		}
	}
	, invoiceProductRowFocus:function() {
//dbug.log('invoiceProductRowFocus');		
	}
	, invoiceProductRowBlur:function() {
//dbug.log('invoiceProductRowBlur');		
	}	
	, enterInvoiceProductRow:function(parentRow) {
		var invoiceProductsTable = document.id('invoiceProductsTable');
		var invoiceProductRows = invoiceProductsTable.getElements('tr[class~=invoiceProductRow]');		
		parentRow.addClass('invoiceProductRowEditable');
		if (invoiceProductRows.length > 1 && !parentRow.retrieve('isEditable',false)) {		
			var handle = parentRow.getElement('div.invoiceProductRowHandle');
//			var handleSize = parentRow.getSize().y-parentRow.getStyle('border-bottom-width').toInt() - (handle.getParent('td').getStyle('padding-top').toInt() + handle.getParent('td').getStyle('padding-bottom').toInt());			
			handle.setStyle('display','block'); //.setStyle('height', handleSize);
			parentRow.getElement('a.invoiceProductDeleteBtn').setStyle('display','inline-block');
		}
	}
	, leaveInvoiceProductRow:function(parentRow) {
		if (!parentRow.retrieve('isEditable',false)) {
			parentRow.removeClass('invoiceProductRowEditable');		
			parentRow.getElement('div.invoiceProductRowHandle').setStyle('display','none');			
			parentRow.getElement('a.invoiceProductDeleteBtn').setStyle('display','none');			
		}
	}	
	, activateInvoiceProductRow:function(parentRow, isNew) {
		if (parentRow.retrieve('isEditable', false)) { 
			/*
			var productSelect = parentRow.getElement('select[class~=invoiceProductSelect]');			
			if (productSelect.get('value') != '') {
				return false; 
			} */
			return false; 
		}
		if (!$defined(isNew)) { isNew = false; }
//dbug.log('activateInvoiceProductRow isNew = '+isNew);		
		var invoiceProductsTable = document.id('invoiceProductsTable');
		var invoiceProductRows = invoiceProductsTable.getElements('tr[class~=invoiceProductRow]');
		if (invoiceProductRows.length > 0) {
			invoiceProductRows.each(function(row){					
				if (row != parentRow) {								
//dbug.log('row ja');					
					this.deactivateInvoiceProductRow(row, isNew);
				} else {
//dbug.log('row nee');					
				}
			},this);
		}				
		parentRow.store('isEditable', true).addClass('invoiceProductRowEditable');
		var productSelect = parentRow.getElement('select[class~=invoiceProductSelect]');
		var invoiceProductAdd = parentRow.getElement('a.invoiceProductAdd');
		var productQuantity = parentRow.getElement('input[class~=invoiceProductQuantity]');				
		var productPrice = parentRow.getElement('input[class~=invoiceProductPrice]');
		var productBtw = parentRow.getElement('select[class~=invoiceProductBtw]');
		var productDescription = parentRow.getElement('textarea[class~=invoiceProductDescription]');
		var productTotal = parentRow.getElement('input[class~=invoiceProductTotal]');	
//		this.addDeactivateToRow.delay(200, this, parentRow);
		var rowBtn = document.id('invoice_product_row_btn');				
		if (rowBtn) {
			//rowBtn.setStyle('display','none');
		}
		var deleteBtn = parentRow.getElement('a.invoiceProductDeleteBtn');
		var handle = parentRow.getElement('div.invoiceProductRowHandle');
		if (deleteBtn && handle) {
//dbug.log('should be hiding delete btn');			
			deleteBtn.setStyle('display','none');
			handle.setStyle('display','none');
		}
		if (productSelect.get('value') == '') {
			isNew = true;
		} 
		if (isNew) {
			this.hideProductRowInputs(parentRow);	
		} else {
			productSelect.setStyle('display', 'inline-block');
			productSelect.retrieve('displaySpan').setStyle('display', 'none');
			invoiceProductAdd.setStyle('display', 'inline-block');
			productQuantity.setStyle('display', 'inline-block');		
			productQuantity.retrieve('displaySpan').setStyle('display','none');		
			productPrice.setStyle('display','inline-block').retrieve('displaySpan').setStyle('display','none');		
			productPrice.retrieve('displayCurrency').setStyle('display','inline-block');
			productBtw.setStyle('display','inline-block').retrieve('displaySpan').setStyle('display','none');			
			productDescription.setStyle('display','inline-block').retrieve('displaySpan').setStyle('display','none');
			productDescription.retrieve('textareaGrow').update();		
			productTotal.setStyle('display','inline-block').retrieve('displayCurrency').setStyle('display','inline-block');		
			//parentRow.getElement('div.invoiceProductRowHandle').setStyle('display','block');														
		}
	}

	, deactivateInvoiceProductRow:function(parentRow, isNew) {
		if (parentRow.retrieve('isEditable', true)) { 
			if (!$defined(isNew)) { isNew = false; }		
// dbug.log('deactivateInvoiceProductRow isNew = '+isNew);				
			parentRow.store('isEditable', false).removeClass('invoiceProductRowEditable');		
			var productSelect = parentRow.getElement('select[class~=invoiceProductSelect]');
			productSelect.setStyle('display', 'none');
			productSelect.retrieve('displaySpan').setStyle('display', 'inline-block');
			var invoiceProductAdd = parentRow.getElement('a.invoiceProductAdd');
			invoiceProductAdd.setStyle('display', 'none');			
			var productQuantity = parentRow.getElement('input[class~=invoiceProductQuantity]');				
			productQuantity.setStyle('display','none');
			productQuantity.retrieve('displaySpan').setStyle('display', 'inline-block');
			var productPrice = parentRow.getElement('input[class~=invoiceProductPrice]');
			productPrice.setStyle('display','none').retrieve('displaySpan').setStyle('display','inline-block');
			var productBtw = parentRow.getElement('select[class~=invoiceProductBtw]');
			productBtw.setStyle('display','none').retrieve('displaySpan').setStyle('display','inline-block');	
			var productDescription = parentRow.getElement('textarea[class~=invoiceProductDescription]');
			productDescription.setStyle('display','none').retrieve('displaySpan').set('html',productDescription.get('value').replace(/\n/g,'<br>')).setStyle('display','block');								
			parentRow.getElement('div.invoiceProductRowHandle').setStyle('display','none');
			if (productSelect.get('value') == '') {
				this.hideProductRowInputs(parentRow);
			}
			this.calcInvoiceProductRowsHeight();
			this.checkInvoiceProductRowDelete.delay(100,this,[parentRow,productSelect, isNew]);
			var rowBtn = document.id('invoice_product_row_btn');				
			if (rowBtn ) {
				rowBtn.setStyle('display','inline-block');
			}
			this.checkInvoiceProductRowsAddDelete();
			var invoiceForm = document.id('invoiceForm');
			var total_price_in = invoiceForm.retrieve('total_price_in',-999999999999);	
			var minimum_ideal_amount_input = invoiceForm.getElement('#minimum_ideal_amount');		
			var minimum_ideal_amount = minimum_ideal_amount_input.get('value').toFloat();
			var no_ideal_possible = document.id('no_ideal_possible');
			if (no_ideal_possible) {
				if (total_price_in.toFloat() <= minimum_ideal_amount && total_price_in != -999999999999) {
					no_ideal_possible.setStyle('display','block');
				} else {
					no_ideal_possible.setStyle('display','none');					
				}
			}
//dbug.log('hier check met ideal minimum? : min ='+minimum_ideal_amount+' en current = '+total_price_in.toFloat() );			
		}
	}
	, checkInvoiceProductRowsAddDelete:function() {
		var invoiceProductsTable = document.id('invoiceProductsTable');
		var invoiceProductRows = invoiceProductsTable.getElements('tr[class~=invoiceProductRow]');		
		var rowBtn = document.id('invoice_product_row_btn');
		if (invoiceProductRows.length == 1) {
			var delbtn = invoiceProductRows[0].getElement('a.invoiceProductDeleteBtn');
			if (delbtn) {
				delbtn.setStyle('display','none');
			}
			var productSelect = invoiceProductRows[0].getElement('select[class~=invoiceProductSelect]');
			if (productSelect.get('value')=='') {
				var rowBtn = document.id('invoice_product_row_btn');				
				if (rowBtn ) {
					rowBtn.setStyle('display','none');
				}			
			}
		}		
	}
	, checkInvoiceProductRowDelete:function(parentRow, productSelect, isNew) {
		var invoiceProductsTable = document.id('invoiceProductsTable');
		var invoiceProductRows = invoiceProductsTable.getElements('tr[class~=invoiceProductRow]');		
		if (invoiceProductRows.length > 1) {		
			if (productSelect.get('value') == '' && !isNew && !parentRow.retrieve('isEditable',true)) {
				this.deleteInvoiceProductRow(parentRow);
//				parentRow.removeEvents();
//				parentRow.destroy();
//				this.checkInvoiceProductRowsAddDelete();
			}
		} 
	}
	, hideProductRowInputs:function(parentRow) {
		var productSelect = parentRow.getElement('select[class~=invoiceProductSelect]');
		productSelect.setStyle('display', 'inline-block').retrieve('displaySpan').setStyle('display','none');
		var productSelectAdd = parentRow.getElement('a.invoiceProductAdd');
		if (productSelectAdd) { productSelectAdd.setStyle('display','inline-block'); }
		//productSelect.retrieve('displaySpan').set('html',productSelect.options[productSelect.selectedIndex].text).setStyle('display', 'inline-block');		
		var productQuantity = parentRow.getElement('input[class~=invoiceProductQuantity]');				
		productQuantity.setStyle('display','none');
		productQuantity.retrieve('displaySpan').setStyle('display', 'none');
		var productPrice = parentRow.getElement('input[class~=invoiceProductPrice]');
		productPrice.setStyle('display','none').retrieve('displaySpan').setStyle('display','none');
		productPrice.retrieve('displayCurrency').setStyle('display','none');
		var productBtw = parentRow.getElement('select[class~=invoiceProductBtw]');
		productBtw.setStyle('display','none').retrieve('displaySpan').setStyle('display','none');	
		var productDescription = parentRow.getElement('textarea[class~=invoiceProductDescription]');
		productDescription.setStyle('display','none').retrieve('displaySpan').set('html','').setStyle('display','none');								
		var productTotal = parentRow.getElement('input[class~=invoiceProductTotal]');	
		productTotal.setStyle('display','none').retrieve('displayCurrency').setStyle('display','none');
//dbug.log('hideProductRowInputs');	
		var rowBtn = document.id('invoice_product_row_btn');				
		if (rowBtn) {
			rowBtn.setStyle('display','none');
		}	
	}
	, showProductRowInputs:function(parentRow) {
		var productSelect = parentRow.getElement('select[class~=invoiceProductSelect]');		
		productSelect.setStyle('display','inline-block');
		productSelect.retrieve('displaySpan').set('html','').setStyle('display', 'none');				
		var productQuantity = parentRow.getElement('input[class~=invoiceProductQuantity]');				
		productQuantity.setStyle('display','inline-block');
		productQuantity.retrieve('displaySpan').setStyle('display', 'none');
		var productPrice = parentRow.getElement('input[class~=invoiceProductPrice]');
		productPrice.setStyle('display','inline-block').retrieve('displaySpan').setStyle('display','none');
		productPrice.retrieve('displayCurrency').setStyle('display','inline-block');
		var productBtw = parentRow.getElement('select[class~=invoiceProductBtw]');
		productBtw.setStyle('display','inline-block').retrieve('displaySpan').setStyle('display','none');	
		var productDescription = parentRow.getElement('textarea[class~=invoiceProductDescription]');
		productDescription.setStyle('display','inline-block').retrieve('displaySpan').set('html','').setStyle('display','none');								
		var productTotal = parentRow.getElement('input[class~=invoiceProductTotal]');	
		productTotal.setStyle('display','inline-block').retrieve('displayCurrency').setStyle('display','inline-block');
		// productQuantity.focus();
	}	
	, calcInvoiceProductRowsHeight:function() {
		var invoiceProductsTableHeader = document.id('invoiceProductsTableHeader');
		var invoiceProductsTable = document.id('invoiceProductsTable');
		var invoiceProductRows = invoiceProductsTable.getElements('tr[class~=invoiceProductRow]');
		var rowsHeight = 0;
		var invoiceForm = document.id('invoiceForm');
		var page = invoiceForm.getElement('.contentCenterInvoice');
		var pageWidth = page.getSize().x;
		// 1:1.4142
		var pageHeight = (pageWidth * 1.4142).toInt();
		var inner = page.getElement('.contentCenterInvoiceInner');
		var margins = inner.getStyle('margin-top').toInt() + inner.getStyle('margin-bottom').toInt();
		var productsMax = (0.45 * (pageHeight-margins)).toInt(); 
//dbug.log('pageWidth = '+pageWidth+' pageHeight = '+pageHeight+' productsMax = '+productsMax);		
		if (invoiceProductsTableHeader) {
			var headerHeight = invoiceProductsTableHeader.getStyle('margin-top').toInt() + invoiceProductsTableHeader.getStyle('margin-bottom').toInt();
			rowsHeight += headerHeight;
		}
		if (invoiceProductRows.length > 0) {
			invoiceProductRows.each(function(row, i) {
				var is_next = row.getElement('input[type=hidden][class=product_is_next_page]');
				var rowHeight = row.getSize().y;
				var nowHeight = rowsHeight + rowHeight;
				if (nowHeight > productsMax) {
					is_next.set('value', 1);
					rowsHeight = headerHeight; // resetting
					rowsHeight += rowHeight;					
				} else {
					is_next.set('value', 0);
					rowsHeight += rowHeight;
				}
//dbug.log('row '+i+' height='+rowHeight+ ' total height = '+rowsHeight+ ' is_next = '+is_next.get('value'));				
			},this);
			
		}		
	}
	, calcInvoiceTotals:function() {
//dbug.log('calcInvoiceTotals');				
		var invoiceForm = document.id('invoiceForm');
		var invoiceTypeMultiplier = 1;
		var invoice_type = invoiceForm.retrieve('invoice_type');
		if (invoice_type == 'credit') { invoiceTypeMultiplier = -1; }
		var invoiceProductsTable = document.id('invoiceProductsTable');
		var invoiceProductRows = invoiceProductsTable.getElements('tr[class~=invoiceProductRow]');
		var invoice_total_price_ex = document.id('invoice_total_price_ex');
		var invoice_total_btw = document.id('invoice_total_btw');
		var invoice_total_price_in = document.id('invoice_total_price_in');
		var total_price_ex = 0;
		var total_btw = 0;
		var total_price_in = 0;
		if (invoiceProductRows.length > 0) {			
			invoiceProductRows.each(function(parentRow){
				var productBtw = parentRow.getElement('select[class~=invoiceProductBtw]');							
				var productTotalHidden = parentRow.getElement('input[class~=invoiceProductTotalHidden]');							
				var prTotal = productTotalHidden.get('value').toFloat();
				var btw = productBtw.get('value').toFloat() * prTotal;
				total_price_ex += prTotal;	
				total_btw += btw;
			},this);
			total_price_in = total_price_ex + total_btw;
		}				
		invoiceForm.store('total_price_in', total_price_in.round(2));
		invoice_total_price_ex.set('html', total_price_ex.round(2).numberFormat(2,',','.'));
		invoice_total_btw.set('html', total_btw.round(2).numberFormat(2,',','.'));		
		invoice_total_price_in.set('html', total_price_in.round(2).numberFormat(2,',','.'));		
	}
	, calcInvoiceProductRow:function(parentRow) {
		var productDescription = parentRow.getElement('textarea[class~=invoiceProductDescription]');
		var productBtw = parentRow.getElement('select[class~=invoiceProductBtw]');											
		var productPrice = parentRow.getElement('input[class~=invoiceProductPrice]');
		var productPriceHidden = parentRow.getElement('input[class~=invoiceProductPriceHidden]');		
		var productQuantity = parentRow.getElement('input[class~=invoiceProductQuantity]');		
		var productQuantityHidden = parentRow.getElement('input[class~=invoiceProductQuantityHidden]');				
		var productTotal = parentRow.getElement('input[class~=invoiceProductTotal]');
		var productTotalHidden = parentRow.getElement('input[class~=invoiceProductTotalHidden]');
		var count = productQuantityHidden.get('value').toFloat();
		var price = productPriceHidden.get('value').toFloat();
		if (isNaN(count)) { count = 0; }
		if (isNaN(price)) { price = 0; }
		var total = count * price;
		if (isNaN(total)) { total = 0; }
//		productPrice.set('value', price);
//		productQuantity.set('value', count);
		productTotalHidden.set('value', total.round(2));		
		productTotal.set('value', total.round(2).numberFormat(2,',','.'));
		this.calcInvoiceTotals();						
	}	
	, changeInvoiceProductQuantity:function(input, blur) {
//dbug.log('changeInvoiceProductQuantity');		
		var parentRow = input.getParent('tr.invoiceProductRow');
		var productQuantityHidden = parentRow.getElement('input[class~=invoiceProductQuantityHidden]');							
		var value = input.get('value');
		var valreplaced = value.replace(/\,/g,'.');
		input.retrieve('displaySpan').set('html', value);
		if (valreplaced != value.toInt()) { 		
			productQuantityHidden.set('value',valreplaced.toFloat().round(2));
		} else {
			productQuantityHidden.set('value',value);			
		}
		if (blur) {
			if (valreplaced != value.toInt()) {
				input.set('value', valreplaced.toFloat().round(2).numberFormat(2,',',''));
				input.retrieve('displaySpan').set('html', valreplaced.toFloat().round(2).numberFormat(2,',',''));				
			}
			//input.set('value', input.get('value').toFloat());
			//input.retrieve('displaySpan').set('html', valreplaced.toFloat().numberFormat(2,',','.'));
		}	
		this.calcInvoiceProductRow(parentRow);
	}
	, changeInvoiceProductPrice:function(input, blur) {
//dbug.log('changeInvoiceProductPrice');		
		var parentRow = input.getParent('tr.invoiceProductRow');
		var productPriceHidden = parentRow.getElement('input[class~=invoiceProductPriceHidden]');
		var value = input.get('value');
		var valreplaced = value.replace(/\,/g,'.');	
		input.retrieve('displaySpan').set('html', value);	
		productPriceHidden.set('value', valreplaced.toFloat().round(2));		
		if (blur) {				
			//input.set('value', input.get('value').toFloat());
			input.set('value', valreplaced.toFloat().round(2).numberFormat(2,',',''));
			input.retrieve('displaySpan').set('html', valreplaced.toFloat().round(2).numberFormat(2,',',''));				
		}		
		this.calcInvoiceProductRow(parentRow);		
	}
	, changeInvoiceProductBtw:function(sel) {
		var parentRow = sel.getParent('tr.invoiceProductRow');
		sel.retrieve('displaySpan').set('html', sel.options[sel.selectedIndex].text);
//dbug.log('btw sel change:'+	sel.options[sel.selectedIndex].text);			
		this.calcInvoiceTotals();		
	}
	, changeInvoiceProductSelect:function(sel) {
		var parentRow = sel.getParent('tr.invoiceProductRow');
		var invoiceForm = sel.getParent('form.invoiceForm');
		var newProductId = sel.get('value');
		var productSelectHidden = parentRow.getElement('input[class~=invoiceProductSelectHidden]');		
		var productQuantity = parentRow.getElement('input[class~=invoiceProductQuantity]');
		var productQuantityHidden = parentRow.getElement('input[class~=invoiceProductQuantityHidden]');		
		var productDescription = parentRow.getElement('textarea[class~=invoiceProductDescription]');
		var productBtw = parentRow.getElement('select[class~=invoiceProductBtw]');	
		var productPrice = parentRow.getElement('input[class~=invoiceProductPrice]');		
		var productPriceHidden = parentRow.getElement('input[class~=invoiceProductPriceHidden]');			
		var productTotal = parentRow.getElement('input[class~=invoiceProductTotal]');		
		if (newProductId != "") {
			this.showProductRowInputs(parentRow);
			parentRow.store('isEditable', true);
			var displaySpan = sel.retrieve('displaySpan');
			if (displaySpan) {
				displaySpan.set('html', sel.options[sel.selectedIndex].text);
			}
			var rowBtn = document.id('invoice_product_row_btn');				
			if (rowBtn) {
				rowBtn.setStyle('display','inline-block');
			}			
//dbug.log('changeInvoiceProductSelect, new id='+newProductId);	
			var newProductHash = mm.products.get(newProductId);
			productSelectHidden.set('value', newProductHash.get('title'));
			var btwHash = mm.btw.get(newProductHash.btw_tariff);		
			productBtw.set('value', btwHash.get('tariff')).retrieve('displaySpan').set('html', productBtw.options[productBtw.selectedIndex].text);					
			productDescription.set('value', newProductHash.get('description')).retrieve('displaySpan').set('html',productDescription.get('value').replace(/\n/,'<br>'));
// dbug.log('desc before update'+productDescription.retrieve('textareaGrow'));			
			productDescription.retrieve('textareaGrow').update();
// dbug.log('desc after update');			
			var invoice_type = invoiceForm.retrieve('invoice_type');
			var invoice_type_multiplier = 1;
			if (invoice_type=='credit') { invoice_type_multiplier = -1; }
			var displayPrice = (newProductHash.get('price').toFloat() * invoice_type_multiplier).numberFormat(2,',','');
			productPrice.set('value', displayPrice).retrieve('displaySpan').set('html', displayPrice);
			productPriceHidden.set('value', (newProductHash.get('price') * invoice_type_multiplier));
			this.calcInvoiceProductRow(parentRow);
			var invoiceProductsTable = sel.getParent('table');
			if (invoiceProductsTable.hasClass('validation-failed')) {
				invoiceProductsTable.removeClass('validation-failed');
			}
		} else {
			var displaySpan = sel.retrieve('displaySpan');
			if (displaySpan) {
				displaySpan.set('html', '');
			}		
			productSelectHidden.set('value', '');
			productQuantity.set('value', '1');
			productQuantityHidden.set('value','1');
			productDescription.set('value', '');
			productBtw.set('value','');	
			productPrice.set('value', '');
			productPriceHidden.set('value', '');
			productTotal.set('value', '');
			sel.setStyle('display','none');
			this.hideProductRowInputs(parentRow);			
			this.calcInvoiceProductRow(parentRow);
			var rowBtn = document.id('invoice_product_row_btn');				
			if (rowBtn) {
				rowBtn.setStyle('display','none');
			}			
			//this.deactivateInvoiceProductRow(parentRow);			
		}
	}
	, getAjaxTables:function(ajaxTableContainers) {
		ajaxTableContainers.each(function(tableDiv) {
			if (tableDiv.hasClass('expandRowContent')) { return; }
			this.getAjaxTable(tableDiv);
		},this);			
	}
	, getAjaxTable:function(tableDiv) {
		var rel = tableDiv.get('rel');
		if (rel!='') {
			if (rel.charAt(0)=='/') { rel = rel.substr(1,rel.length); }							
				var ajaxurl = '/_x/'+rel;
				tableDiv.erase('rel');
				tableDiv.store('defaultAjaxUrl', ajaxurl);
				if (window.location.hash != '') {
					var hashAr = window.location.hash.split('_');
					if ($type(hashAr) == 'array' && $defined(hashAr[0]) && $defined(hashAr[1]) ) {
						var tab = hashAr[0];
// dbug.log('getAjaxTables tab = '+tab+' 1 = '+ hashAr[1]);						
					}
				}	

			new Request.JSON({
				url:ajaxurl
				, method:'post'
				, onRequest: function() {
				//	if (overlay) { overlay.setStyles({'display':'block','opacity':0}).fade(1); }
				}
				, onFailure: function() {
				//	if (overlay) { overlay.setStyles({'display':'none'});	}							
				}
				, onSuccess: function(rJson, rText) {
					//mm.ajax.ajaxReady.delay(100, mm.ajax, tdiv);
//dbug.log(rJson);						
					if (rJson.html) {
						tableDiv.set('html', rJson.html);
						//var cnt = tdiv.getElement('div.ajaxTableContainer').get('html'); //we only need the contents of this div
						//tdiv.empty().set('html', cnt);
					}
					if ($defined(rJson.page.total_items)) {
//dbug.log('table: '+rJson.page.base_url+' total_items: '+rJson.page.total_items+' table_id: '+rJson.table_id + ' el = '+document.id('ajaxTableBadge_'+rJson.table_id));	
						if ($defined(rJson.table_id)) {
							var badge = document.id('ajaxTableBadge_'+rJson.table_id);
							if (badge) {
								badge.set('html', rJson.page.total_items);
							}
						}
					}

				//	if (overlay) { overlay.setStyle('display','block').fade(0); }								
					mm.ajax.ajaxReady.delay(10, mm.ajax, tableDiv);
				}
			}).send();				
		} 
		
	}
	, setupAjaxTables:function(ajaxTables) {
		ajaxTables.each(function(table) {
			var tdiv = table.getParent('div.ajaxTableContainer');
			var divCoords = tdiv.getCoordinates(tdiv.getParent());			
			var overlay = tdiv.getNext('div.ajaxTableOverlay') || new Element('div', {'class':'ajaxTableOverlay'}).setStyles({'display':'block','opacity':0,'top':divCoords.top,'left':divCoords.left,'width':divCoords.width,'height':divCoords.height}).inject(tdiv,'after');			
			overlay.set('tween', {duration:500,transition:'circ:in:out'});
			var tFooter = tdiv.getElement('div.tableFooter');
			var pag = tdiv.getElement('p.pagination');
			if (tFooter && pag) {
				var links  = pag.getElements('a');
			} else { 
				var links = [];
			}				
			links.extend(table.getElements('th a')); // extend with all anchors in headers
			if (links.length > 0) {
				links.each(function(anchor){
					var ajaxurl = '/_x'+anchor.get('href');			
					anchor.erase('href');
					anchor.set('href','#');
					anchor.addEvent('click', function(e) {
						e.stop();
						new Request.JSON({
							url:ajaxurl
							, link:'ignore'
							, method:'post'
							, onRequest: function() {
								table.getElements('tbody tr').setStyle('opacity',0.4);
								if (overlay) { 
									var divCoords = tdiv.getCoordinates(tdiv.getParent());									
									overlay.setStyles({'display':'block','opacity':0.1, 'top':divCoords.top,'left':divCoords.left,'width':divCoords.width,'height':divCoords.height}); //.fade(1); 
								}
							}
							, onFailure: function() {
								table.getElements('tbody tr').setStyle('opacity',1);								
								if (overlay) { overlay.setStyles({'display':'none'});	}							
							}
							, onSuccess: function(rJson, rText) {
								//mm.ajax.ajaxReady.delay(100, mm.ajax, tdiv);
								if (rJson.html) {
									tdiv.empty().set('html', rJson.html);
									//var cnt = tdiv.getElement('div.ajaxTableContainer').get('html'); //we only need the contents of this div
									//tdiv.empty().set('html', cnt);
								}
											
								mm.ajax.ajaxReady.delay(10, mm.ajax, tdiv);
								if (overlay) { overlay.setStyles({'display':'block','opacity':0}); }								
							}
						}).send();
					});
				},this);
				overlay.setStyles({'opacity':0});				
			}
			// TABLE REGULAR LINKS
			var regularLinks = table.getElements('a.regularLink');
			if (regularLinks.length > 0) {
				regularLinks.each(function(link) {
					link.addEvents({
						'mousedown': function(e) { 
							e.stop(); 
//dbug.log('regularLink mousedown');						
							window.location.href = link.get('href'); 
						}
						, 'click' : function(e) { e.stop(); }
					});
				});
			}
			
			if (mm.runtime.request == 'vat') {
				// VAT TABLE FINALIZE LINKS:
				var finalizeLinks = table.getElements('a.finalizeLink');
				if (finalizeLinks.length > 0) {
					finalizeLinks.each(function(link) {
						var href = link.get('href');
						if (href.charAt(0)=='/') { href = href.substr(1,href.length); }							
						var ajaxurl = '/_x/'+href;
						link.addEvents({
							'mousedown': function(e) {
								e.stop();
								mm.overlayAll.showConfirmDialog(ajaxurl, mm.lang.confirm_dialog.finalize_btw);
								/*
								new Request.JSON({
									url: ajaxurl
									, method: 'post'
									, onRequest: function() {
										mm.overlayAll.show();
										mm.overlayAll.showNotice('loading', mm.lang.notice_info.saving);							
									}
									, onFailure: function() {
									//	if (overlay) { overlay.setStyles({'display':'none'});	}		
										mm.overlayAll.hide(true);
									}
									, onSuccess: function(rJson, rText) {
			dbug.log(rJson);			
										if (rJson.saved) {
											window.location.href = '/vat';
										} else {
											mm.overlayAll.hide(true);								
											mm.noticeError.show({title:'fout bij afronden btw'});
										}
									}
								}).send();
								*/
							}
							,'click' : function(e) { e.stop(); }
						});

					});
				}
			
			}
			// CLICKROWS
			var clickRows = table.getElements('tr.clickRow');
			if (clickRows.length > 0) {
				clickRows.each(function(clickRow) {
					var rel = clickRow.get('rel');
					if (rel!='') {
						clickRow.erase('rel');
						clickRow.addEvents({
							'click': function(e) {
								e.stop();
// dbug.log('clickrow click');								
								window.location.href = rel;
							}
							, 'mouseenter': function(e) { 
								clickRow.addClass('clickRowHover');
							}
							, 'mouseleave': function(e) { 
								clickRow.removeClass('clickRowHover');
							}							
						});
					}
				},this);
			}
			// CLICKROWSDIALOG			
			var clickRowsDialog = table.getElements('tr.clickRowDialog');
			if (clickRowsDialog.length > 0) {
				clickRowsDialog.each(function(clickRowDialog) {
					var rel = clickRowDialog.get('rel');
					if (rel!='') {
						clickRowDialog.erase('rel');
						clickRowDialog.addEvents({
							'click': function(e) {
								e.stop();
								mm.overlayAll.showDialog(rel);								
							}
							, 'mouseenter': function(e) { 
								clickRowDialog.addClass('clickRowHover');
							}
							, 'mouseleave': function(e) { 
								clickRowDialog.removeClass('clickRowHover');
							}							
						});
					}
				},this);
			}			
			// CLICKROWS
			var expandRows = table.getElements('tr.expandRow');
			if (expandRows.length > 0) {
				expandRows.each(function(expandRow) {
					var rel = expandRow.get('rel');
					var showRow = expandRow.getNext('tr.expandRowContainer');
					var showDiv = showRow.getElement('div.expandRowContent');
					if (showRow && showDiv) { showDiv.setStyle('display','none'); showRow.setStyles({'height':'0px', 'overflow':'hidden'}); }
					if (rel!='') {
						expandRow.erase('rel');
						expandRow.addEvents({
							'click': function(e) {
								e.stop();
								if (showRow && showDiv) {					
									if (showDiv.getStyle('display') == 'block') {
										showDiv.setStyle('display','none');
										showRow.setStyles({'height':'0px', 'overflow':'hidden'});
										expandRow.removeClass('expandRowOpen');										
									} else {
										expandRows.each(function(erow) {
											var srow = erow.getNext('tr.expandRowContainer');
											var sdiv = srow.getElement('div.expandRowContent');
											if (srow && sdiv) { sdiv.setStyle('display','none'); srow.setStyles({'height':'0px', 'overflow':'hidden'}); }											
											erow.removeClass('expandRowOpen');
										});
										showDiv.setStyle('display','block');									
										showRow.setStyles({'height':'auto', 'overflow':'visible'});
										expandRow.addClass('expandRowOpen');	
										if (showDiv.hasClass('ajaxTableContainer')) {
											var tableLoaded = showDiv.retrieve('ajaxTableLoaded', false);
											if (!tableLoaded) {
												this.getAjaxTable(showDiv);
												showDiv.store('ajaxTableLoaded', true);
											}
										}
									}
								}
							}.bind(this)
							, 'mouseenter': function(e) { 
								expandRow.addClass('clickRowHover');
							}
							, 'mouseleave': function(e) { 
								expandRow.removeClass('clickRowHover');
							}							
						});
					}
				},this);
			}			
			// SELECTABLE ROWS:
			var selectRows = table.getElements('tr.selectRow');
			if (selectRows.length > 0) {
				selectRows.each(function(selectRow) {
					var selectCheck = selectRow.getElement('input[type=checkbox][class~=selectRowCheck]');
					if (selectCheck) {
						selectCheck.addEvent('click', function(e) {
							e.stopPropagation();
							var checked = selectCheck.get('checked');
// dbug.log('checked = '+checked);
							if (checked) {
								selectRow.addClass('selectedRow');
							} else {
								selectRow.removeClass('selectedRow');								
							}
						});
					}
				},this);				
			}			

			// could use fancyform
			var selectAllCheck = table.getElement('thead th input[type=checkbox][class~=selectAllCheck]');
			if (selectAllCheck) {
				selectAllCheck.addEvent('click', function(e) {
					e.stopPropagation();
					var checked = selectAllCheck.get('checked');
					var table = selectAllCheck.getParent('table');
					if (table) {
						var selectRows = table.getElements('tr.selectRow');	
						if (selectRows.length > 0) {
							selectRows.each(function(selectRow) {
								var selectCheck = selectRow.getElement('input[type=checkbox][class~=selectRowCheck]');
								if (selectCheck && !selectCheck.get('disabled')) {									
									if (checked) {
										selectRow.addClass('selectedRow');		
										selectCheck.set('checked', true);							
									} else {
										selectRow.removeClass('selectedRow');									
										selectCheck.set('checked', false);										
									}
								}
							});											
						}
					}
				});
			}
			
			// selectedRows action buttons:
			if (tFooter) {
				var actionbuttons = tFooter.getElements('a.actionbutton');
				if (actionbuttons.length > 0) {
					actionbuttons.each(function(btn) {
						var link = btn.get('href');
						btn.set('href', '#');						
						if (btn.hasClass('footerDialogLink')) {
							btn.addEvent('click', function(e) {
								e.stop();
								mm.overlayAll.showDialog(link);
							}.bind(this));
						} else {
							btn.addEvent('click', function(e) {
								e.stop();
								this.ajaxTableSelectedRowsAction(table, btn, link);
							}.bind(this));
						}
					},this);
				}				
			}			
			
			if (mm.runtime.highlightId) {
				var highlightRow = table.getElement('tr[alt='+mm.runtime.highlightId+']');
				if (highlightRow) {
					highlightRow.getElements('td').set('tween', {duration: 4000}).highlight('transparent',this.options.highlightIdColor);
				}
				mm.runtime.highlightId = false;
			}
			
		},this);		
	}
	, ajaxTableSelectedRowsAction:function(table, btn, link) {
		var selectRows = table.getElements('tr.selectRow');	
		var selectedIds = [];
		var tableType = table.get('rel');
		var not_possible = 0;
		var totalSelected = selectRows.length;
		if (selectRows.length > 0) {
			selectRows.each(function(row) {
				var selectCheck = row.getElement('input[type=checkbox][class~=selectRowCheck]');				
				if (selectCheck && !selectCheck.get('disabled')) {				
// dbug.log(link);					
					if (row.hasClass('selectedRow') && selectCheck.get('checked')) {	
//dbug.log('ook hiero, yo = '+selectCheck.hasClass('not_'+link) +' class = '+selectCheck.get('class'));										
						if (selectCheck.hasClass('not_'+link)) {
//dbug.log('NOT_'+link+' found');							
							row.removeClass('selectedRow');
							selectCheck.set('checked', false);
							not_possible++;
						} else {
							selectedIds.push(row.get('alt').toInt());							
						}
					}				
				}
			},this);			
		} 		
//dbug.log('ajaxTableSelectedRowsAction table='+tableType+' selection = ');
//dbug.log(JSON.encode(selectedIds));		
		if (selectedIds.length > 0) {
// dbug.log('no empty selection');
			var ajaxurl = '/_x/'+link+'/'+tableType;
			var rel = btn.get('rel');
// dbug.log(ajaxurl);
//return false;
			if (rel == 'confirm') {
				var extratext = '';
				if (not_possible > 0) {
					extratext += "<br />";
					extratext += '('+not_possible+' van de '+totalSelected+' kunnen niet verwijderd worden)';					
				}
				mm.overlayAll.showConfirmDialog(ajaxurl, mm.lang.confirm_dialog[link]+' '+extratext , {'selectedIds':selectedIds});
			} else if (rel=='postform'){
				/*
				var tmpForm = new Element('form', {'method':'post', 'action':'/'+link});
				var tableInput = new Element('input', {'type':'hidden','name':'table','value':tableType}).inject(tmpForm);
				selectedIds.each(function(selId) {
					var input = new Element('input', {'type':'hidden','name':'selectedIds[]','value':selId}).inject(tmpForm);
				});
				tmpForm.inject(btn, 'after');
				tmpForm.submit();
				*/
				var tmpForm = document.id(link+'_form');
				if (tmpForm) {
					var tableInput = tmpForm.getElement('input[type=hidden][name=table]');
					if (tableInput) { 
						tableInput.set('value', tableType);
					}
					var selectedInput = tmpForm.getElement('input[type=hidden][name=selectedIds]');
					if (selectedInput) {
						selectedInput.set('value', JSON.encode(selectedIds));
					}
					tmpForm.submit();
				}
			}
		} else {
			mm.overlayAll.showDialog('no_selection');
		}
	}
	, getAjaxStatsContainers:function(ajaxStatsContainers) {
		ajaxStatsContainers.each(function(statsContainer){
			var rel = statsContainer.get('rel');
			if (rel!='') {
				if (rel.charAt(0)=='/') { rel = rel.substr(1,rel.length); }							
				var ajaxurl = '/_x/'+rel;
				statsContainer.erase('rel');
			
				new Request.JSON({
					url:ajaxurl
					, method:'post'
					, onRequest: function() {
					//	if (overlay) { overlay.setStyles({'display':'block','opacity':0}).fade(1); }
					}
					, onFailure: function() {
					//	if (overlay) { overlay.setStyles({'display':'none'});	}							
					}
					, onSuccess: function(rJson, rText) {
						//mm.ajax.ajaxReady.delay(100, mm.ajax, tdiv);
//dbug.log(rJson);						
						if (rJson.html) {
							statsContainer.set('html', rJson.html);
							//var cnt = tdiv.getElement('div.ajaxTableContainer').get('html'); //we only need the contents of this div
							//tdiv.empty().set('html', cnt);
						}

					//	if (overlay) { overlay.setStyle('display','block').fade(0); }								
						mm.ajax.ajaxReady.delay(10, mm.ajax, statsContainer);
					}
				}).send();
			
			}		
		},this);

	}
	, setupStatsPeriodLinks:function(statsPeriodLinks) {
		statsPeriodLinks.each(function(link) {
			var statsContainer = link.getParent('div.ajaxStatsContainer');
			var rel = link.get('href');
			if (rel!='') {
				if (rel.charAt(0)=='/') { rel = rel.substr(1,rel.length); }							
				var ajaxurl = '/_x/'+rel;
				link.set('href','#');			
				link.addEvent('click', function(e) {
					e.stop();
					new Request.JSON({
						url:ajaxurl
						, method:'post'
						, onRequest: function() {
						//	if (overlay) { overlay.setStyles({'display':'block','opacity':0}).fade(1); }
						}
						, onFailure: function() {
						//	if (overlay) { overlay.setStyles({'display':'none'});	}							
						}
						, onSuccess: function(rJson, rText) {
							//mm.ajax.ajaxReady.delay(100, mm.ajax, tdiv);
	//dbug.log(rJson);						
							if (rJson.html) {
								statsContainer.set('html', rJson.html);
								//var cnt = tdiv.getElement('div.ajaxTableContainer').get('html'); //we only need the contents of this div
								//tdiv.empty().set('html', cnt);
							}

						//	if (overlay) { overlay.setStyle('display','block').fade(0); }								
							mm.ajax.ajaxReady.delay(10, mm.ajax, statsContainer);
						}
					}).send();				
				});
			}
		
		},this);

	}
	, setupGraphSelect:function(graphSelect) {
		var statsContainer = graphSelect.getParent('div.ajaxStatsContainer');		
		graphSelect.addEvent('change', function(e) {
			var rel = graphSelect.get('value');
			if (rel!='') {
				if (rel.charAt(0)=='/') { rel = rel.substr(1,rel.length); }							
				var ajaxurl = '/_x/'+rel;			
				new Request.JSON({
					url:ajaxurl
					, method:'post'
					, onRequest: function() {
					//	if (overlay) { overlay.setStyles({'display':'block','opacity':0}).fade(1); }
					}
					, onFailure: function() {
					//	if (overlay) { overlay.setStyles({'display':'none'});	}							
					}
					, onSuccess: function(rJson, rText) {
						//mm.ajax.ajaxReady.delay(100, mm.ajax, tdiv);
//dbug.log(rJson);						
						if (rJson.html) {
							statsContainer.set('html', rJson.html);
							//var cnt = tdiv.getElement('div.ajaxTableContainer').get('html'); //we only need the contents of this div
							//tdiv.empty().set('html', cnt);
						}

					//	if (overlay) { overlay.setStyle('display','block').fade(0); }								
						mm.ajax.ajaxReady.delay(10, mm.ajax, statsContainer);
					}
				}).send();			
			}
		});
	}
	, setupBargraphContainers:function(bargraphContainers) {
		bargraphContainers.each(function(chartDiv) {
			var rel = chartDiv.get('rel');
			if (rel!='') {
			if (rel.charAt(0)=='/') { rel = rel.substr(1,rel.length); }							
			var ajaxurl = '/_x/'+rel;
			chartDiv.erase('rel');			
			
			new Request.JSON({
				url:ajaxurl
				, method:'post'
				, onRequest: function() {
				//	if (overlay) { overlay.setStyles({'display':'block','opacity':0}).fade(1); }
				}
				, onFailure: function() {
				//	if (overlay) { overlay.setStyles({'display':'none'});	}							
				}
				, onSuccess: function(rJson, rText) {
//dbug.log(rJson);						
					if (rJson) {
						// new graph
						mm.barChart = new mm.Graph({
							containerId:chartDiv.get('id')
							, size:{width:700, height:200} 
							, gutter: {left:50,right:0,top:20,bottom:50}
							, background: 'transparent'
							, data: rJson.data
							, dataLabels: rJson.titles
							, axesLabels: rJson.labels
						});		
						chartDiv.setStyle('background-image','none');										
					}

				}
			}).send();			
		}	
		},this);
	}
	, setupPiechartContainers:function(piechartContainers) {
		mm.pieCharts = [];
		piechartContainers.each(function(chartDiv, index) {
			var rel = chartDiv.get('rel');
			if (rel!='') {
			if (rel.charAt(0)=='/') { rel = rel.substr(1,rel.length); }							
			var ajaxurl = '/_x/'+rel;
			chartDiv.erase('rel');
			
			new Request.JSON({
				url:ajaxurl
				, method:'post'
				, onRequest: function() {
				//	if (overlay) { overlay.setStyles({'display':'block','opacity':0}).fade(1); }
				}
				, onFailure: function() {
				//	if (overlay) { overlay.setStyles({'display':'none'});	}							
				}
				, onSuccess: function(rJson, rText) {
//dbug.log(rJson);						
					if (rJson) {
						var pieDataColors = [['#4c4c4c', '#000000'],['#0be52f','#019412']];	//array normal & hover state of pie, gradient begin and end colors	
						// new piechart
						if (rJson.type == 'sales') {
							pieDataColors = [['#cfcfcf', '#b5b5b5'],['#0be52f','#019412']];	//array normal & hover state of pie, gradient begin and end colors	
						} else if (rJson.type == 'purchases') {
							pieDataColors = [['#9a9a9a', '#7b7b7b'],['#ff1a00','#cd0000']];	//array normal & hover state of pie, gradient begin and end colors	
						} 
						
						mm.pieCharts[index] = new mm.Pie({
							containerId:chartDiv.get('id')
							, size: {width:200, height:200}
							, gutter: {left:10, right:10, top:10, bottom:10}
							, background: 'transparent'
							, data: rJson.data
							, dataLabels: rJson.labels
							, dataColors: pieDataColors
							, noDataLabel: rJson.nodata
						});	
						chartDiv.setStyle('background-image','none');											
					}

				}
			}).send();			
			
			}			
			
		},this);		
	}	
	, setupStyledRadios:function(mmradios) {
		var allc = $$('.mmRadio');
		mmradios.each(function(container) {
			var checks = container.getElements('input[type=checkbox]');
			if (checks.length > 0) {
				checks.each(function(check) {
					check.addEvent('click', function(e) { e.stopPropagation(); });
				});
			}
			var radio = container.getElement('input[type=radio]');
			var name = radio.get('name');
			var relatedContainers = [];
			allc.each(function(c) {
				var cr = c.getElement('input[type=radio][name='+name+']');
				if (cr) {
					relatedContainers.push(c);
				}
			});
			if (radio) {
				if (radio.get('checked')) {
					container.addClass('checked');
				}
				radio.addEvent('click', function(e) {
					e.stopPropagation();
					relatedContainers.each(function(c) { c.removeClass('checked'); });					
					if (radio.get('checked')) {
						container.addClass('checked');
					} else {
						container.removeClass('checked');
					}
				});
				container.setStyle('cursor','pointer').addEvent('click', function(e) {
					e.stop();					
					if (!radio.get('checked')) {
						relatedContainers.each(function(c) { c.removeClass('checked'); });						
						container.addClass('checked');
						radio.set('checked', true);
					} else {
						//radio.set('checked', false);						
						//container.removeClass('checked');
					}
				});				
			}
		},this);
	}
	, setupDialogLinks:function(dialogLinks) {
		dialogLinks.each(function(link) {			
			var linkref = link.get('href');
//dbug.log('setupDialogLinks linkref = '+linkref);			
			link.set('href','#');
			link.addEvent('click', function(e) {
				e.stop();
				mm.overlayAll.showDialog(linkref);
			});
		},this);
	}
	, setupDialogConfirmLinks:function(dialogConfirmLinks) {
		dialogConfirmLinks.each(function(link) {
			var linkref = '/_x'+link.get('href');
			var confirmText = link.get('title');
			link.set('href', '#');
			link.erase('title');
			link.addEvent('click', function(e) {
				e.stop();
				mm.overlayAll.showConfirmDialog(linkref, confirmText);
			}.bind(this));
		},this);
	}
	, setupAjaxPageSaveDialogLinks:function(ajaxPageSaveDialogLinks) {
		ajaxPageSaveDialogLinks.each(function(link) {
			
			var linkref = link.get('href');
			link.set('href','#');
			var form = document.body.getElement('form[class~=ajaxPageForm]');

			if (!form) { return false; }
			form.addEvent('submit', function(e) {
				e.stop();
			});			
			var pageFormValidator = new FormValidator(form, {
				useTitles:false
				, serial:false
				, onFormValidate:function() { 
					//dbug.log('formvalidate finished'); 
					//mm.noticeInfo.show({title:'notice test formvalidate'});
				}
			});
			form.store('formValidator', pageFormValidator);
			if (link.hasClass('disabled') && !link.hasClass('suspended')) {
				link.addEvent('click', function(e) {
					e.stop();
					mm.overlayAll.showDialog('/minsettings');
				}.bind(this));
			} else if (link.hasClass('suspended')) {
				link.addEvent('click', function(e) {
					e.stop();
					mm.overlayAll.showDialog('/suspended');
				}.bind(this));				
			} else {
				link.addEvent('click', function(e) {
					e.stop();	
					var hasProducts = false;
					if (form.hasClass('invoiceForm')) {
						var is_locked = form.getElement('#is_locked');
						if (is_locked) {
							if (is_locked.get('value') == 1) {
								hasProducts = true;	
							}
						} 
						if (!hasProducts) {					
							hasProducts = this.saveCheckInvoiceHasProducts();
						}
					}
					if (!pageFormValidator.validate() || !hasProducts) {
						mm.noticeError.show({title:'onvoldoende gegevens', noFade:true});
						return false;	
					}
				
					mm.overlayAll.showDialog(linkref);				
				
				}.bind(this));
			}
								
		},this);
	}
	, saveCheckInvoiceHasProducts:function() {
		var hasProducts = false;
		var invoiceProductsTable = document.id('invoiceProductsTable');
		var invoiceProductRows = invoiceProductsTable.getElements('tr[class~=invoiceProductRow]');
		if (invoiceProductRows.length > 0) {
			if (invoiceProductRows.length == 1) {
				var productSelect = invoiceProductRows[0].getElement('select[class~=invoiceProductSelect]');
				if (productSelect.get('value')!='') {
					hasProducts = true;
				}
			} else {
				hasProducts = true;
			}
		}	
		if (!hasProducts) {
			invoiceProductsTable.addClass('validation-failed');
		}			
		return hasProducts;
	}
	, checkAjaxPageFormChanged:function(theform) {
		var qs = theform.toQueryString();
		var formdata = JSON.encode(qs.parseQueryString());
		var olddata = theform.retrieve('oldData', false);
		var saveBtn = theform.retrieve('saveBtn', false);
		if (olddata) {
			if (olddata != formdata) {
//dbug.log(olddata);		
//dbug.log(formdata);						
//dbug.log('olddata != formdata');				
				if (!theform.retrieve('mmChanged',false)) {
					var ajaxPageSaveReminder = document.id('ajaxPageSaveReminder');
					if (ajaxPageSaveReminder) {

						ajaxPageSaveReminder.set('tween',{duration:500}).setStyles({'display':'block','opacity':0}).fade(1);
						var reminderSize = ajaxPageSaveReminder.getSize();
						new Fx.Move(ajaxPageSaveReminder, {
						  relativeTo: saveBtn,
						  position: 'upperLeft',
						  offset: {x: -(reminderSize.x + 10), y: 0},
						  transition: 'bounce:out',
							duration: 1500
						}).start();						
					}
					theform.store('mmChanged',true);
					if (saveBtn) {
						saveBtn.removeClass('inactive').setStyle('opacity',1);
					}
				}
			} else {
//dbug.log('olddata == formdata');				
				theform.store('mmChanged',false);
				if (saveBtn) {
					saveBtn.addClass('inactive').setStyle('opacity',0.2);
				}				
				var ajaxPageSaveReminder = document.id('ajaxPageSaveReminder');
				if (ajaxPageSaveReminder) {
					ajaxPageSaveReminder.setStyles({'top':'10px','left':'0px','display':'none'});
				}				
			}
		} else {
//dbug.log('no olddata');			
			theform.store('mmChanged',true).store('oldData', formdata);
		}
		
	}	
	, setupAjaxPageSaveLinks:function(ajaxPageSaveLinks) {
		ajaxPageSaveLinks.each(function(link) {
			var linkref = link.get('href');
			link.set('href','#');
			var form = document.body.getElement('form[class~=ajaxPageForm]');
			if (!form) { return false; }
			form.addEvent('submit', function(e) {
				e.stop();
			});
			// if savebtn has class inactive => setup mmChanged functionality
			if (link.hasClass('inactive')) {
				link.setStyle('opacity', 0.2);
				var qs = form.toQueryString();
				var formdata = qs.parseQueryString();				
				form.store('mmChangeForm',true).store('mmChanged', false).store('saveBtn',link).store('oldData',JSON.encode(formdata)).addEvents({
					'change':function(e) {
//dbug.log('form change');			
						this.checkAjaxPageFormChanged(form);
					}.bind(this)
					, 'keyup':function(e) {
//dbug.log('form keyup');						
						this.checkAjaxPageFormChanged(form);
					}.bind(this)
				});				
				var outLinks = document.id('maintop').getElements('a');
				if (outLinks.length > 0) {
					outLinks.each(function(outLink) {
						var href = outLink.get('href');
						if (href != '' && href != '#') {
							outLink.store('oldHref', href).set('href','#');
							outLink.addEvent('click', function(e) {
								e.stop();
								if (form.retrieve('mmChanged',false)) {
//dbug.log('wants to go to :'+outLink.retrieve('oldHref'));				
									mm.overlayAll.showConfirmDialog(outLink.retrieve('oldHref'),mm.lang.confirm_dialog.not_saved_leave, {}, true);
								} else {
									window.location.href = outLink.retrieve('oldHref');
								}				
							}.bind(this));
						}
					},this); 
				}
			}
			
			var pageFormValidator = new FormValidator(form, {
				useTitles:false
				, serial: false
				, evaluateFieldsOnBlur:true
				, evaluateFieldsOnChange:true
				, ignoreHidden: true
				, stopOnFailure:false
				, onFormValidate:function(validated, form) { 
					//dbug.log('formvalidate finished'); 
					//mm.noticeInfo.show({title:'notice test formvalidate'});
					this.hideFailedValidationOnTabs(form);					
				}.bind(this)
				, onElementValidate:function(elValidated, el) {
//dbug.log('el validated:'+el.get('name'));	
					if (elValidated && el.retrieve('notValidated', true)) {
						el.store('notValidated', false);
						//pageFormValidator.validate();
						var form = el.getParent('form');
						var tabpanel = el.getParent('.mmTabPanel');
						var subtabpanel = el.getParent('.mmSubTabPanel');
						if (subtabpanel) {
							var inputsFailed = subtabpanel.getElements('input[class~=validation-failed]');							
						} else if (tabpanel) {
							var inputsFailed = tabpanel.getElements('input[class~=validation-failed]');
						} else {
							var inputsFailed = form.getElements('input[class~=validation-failed]');
						}

// dbug.log('inputsFailed');						
// dbug.log(inputsFailed);
						inputsFailed.erase(el);

						if (inputsFailed.length == 0) {
							if (subtabpanel) {							
								this.hideFailedValidationOnTabs(form, el, subtabpanel);								
							} else if (tabpanel) {
								this.hideFailedValidationOnTabs(form, el);
							} else {
								this.hideFailedValidationOnTabs(form);												
							}
						} 
					}
				}.bind(this)
				, onElementFail:function(el) {
//dbug.log('validation failed for el:'+el.get('name')+' form='+form);					
					this.showFailedValidationOnTabs(el, form);
					el.store('notValidated', true);
				}.bind(this)
			});		
			
			form.store('formValidator', pageFormValidator);
			
			if (link.hasClass('disabled') && !link.hasClass('suspended')) {
				link.addEvent('click', function(e) {
					e.stop();
					mm.overlayAll.showDialog('/minsettings');
				}.bind(this));
			} else if (link.hasClass('suspended')) {
				link.addEvent('click', function(e) {
					e.stop();
					mm.overlayAll.showDialog('/suspended');
				}.bind(this));				
			} else {							
											
				link.addEvent('click', function(e) {
					e.stop();
					if (link.hasClass('inactive')) { return false; }
				
					var hasProducts = false;
					if (form.hasClass('invoiceForm')) {
						var is_locked = form.getElement('#is_locked');
						if (is_locked) {
							if (is_locked.get('value') == 1) {
								hasProducts = true;	
							}
						} 
						if (!hasProducts) {					
							hasProducts = this.saveCheckInvoiceHasProducts();
						}
						if (!pageFormValidator.validate() || !hasProducts) {
							mm.noticeError.show({title:'onvoldoende gegevens', noFade:true});
							return false;	
						}	
					
					} else {
						var can_continue = true;
						var form_validated = pageFormValidator.validate();
						if (form.get('id')=='settingsForm') {
							var bank_account_nr = form.getElement('#bank_account_nr');
							if (bank_account_nr && bank_account_nr.hasClass('validation-failed')) {
								mm.noticeError.show({title:'incorrect bankrekening nummer', noFade:true});								
								can_continue = false;
							}
						}									
						
						if (form.hasClass('purchaseForm')){									
							var hasClient = false;
							var clientSelect = document.id('selectClient');
							if (!$chk(clientSelect.get('value'))) {
								mm.noticeError.show({title:'geen contact geselecteerd', noFade:true});
								can_continue = false;								
							}
						}						
						
						
						if (!form_validated || !can_continue) {
							mm.noticeError.show({title:'onvoldoende gegevens', noFade:true});
							var mmTabsContainer = form.getElement('.mmTabsContainer');
							if (mmTabsContainer) {
								var mmTabButtons = mmTabsContainer.getElements('.mmTabButtons li');
								var mmTabPanels = mmTabsContainer.getElements('.mmTabPanel');

								var failed = form.getElements('.validation-failed');
								var failedPanels = [];
								var failedSubPanels = [];
								failed.each(function(elFailed) {
									var panel = elFailed.getParent('.mmTabPanel');
									var subpanel = elFailed.getParent('.mmSubTabPanel');
									if (subpanel) {
										failedSubPanels.push(subpanel);	
									}
									failedPanels.push(panel);
								});
								mmTabPanels.each(function(panel,i) {
									if (failedPanels.contains(panel)) {
										mmTabButtons[i].addClass('validation-failed-some');
										var badge = mmTabButtons[i].getElement('div.mmTabButtonWarningBadge');
										if (badge) {
											badge.setStyle('display','block');
										}
										//mmTabButtons[i].getElement('a').setStyle('color', '#ff0000');
									}
									var mmSubTabsContainer = panel.getElement('.mmSubTabsContainer');
									if (mmSubTabsContainer) {
										var mmSubTabButtons = mmSubTabsContainer.getElements('.mmSubTabButtons li');
										var mmSubTabPanels = mmSubTabsContainer.getElements('.mmSubTabPanel');								
										mmSubTabPanels.each(function(subpanel,j) {
											if (failedSubPanels.contains(subpanel)) {
												mmSubTabButtons[j].addClass('validation-failed-some');
												//mmSubTabButtons[j].getElement('a').setStyle('color', '#ff0000');	
											}
										});
									}
								});
							}
							return false;	
						}
					} 			

					var qs = form.toQueryString();
					var action = form.get('action');
					if (action.charAt(0)=='/') { action = action.substr(1,action.length); }		
					var ajaxurl = '/_x/savepageform/'+action;
					var formdata = qs.parseQueryString();
					if (form.hasClass('invoiceForm')) {
						var is_concept = form.getElement('#is_concept');						
						var is_estimate = form.getElement('#is_estimate');						
						if (is_concept.get('value').toInt() == 1) {
							formdata.action = 'save_concept';
						} else if (is_estimate.get('value').toInt() == 1) {
							formdata.action = 'save_estimate';
						}
					}
//dbug.log('save page form, formdata = ');
//dbug.log(JSON.encode(formdata));				

					new Request.JSON({
						url:ajaxurl
						, data: formdata
						, method:'post'
						, onSuccess: function(rJson, rText) {
							this.savePageFormRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText, formdata]);
						}.bind(this)
						, onRequest: function() {
							this.savePageFormRequestStart();
						}.bind(this)
						, onFailuer: function() {
							this.savePageFormRequestFailure();
						}.bind(this)
					}).send();
			
				}.bind(this));
				

			}

		},this);
	}
	, setupSettingsUploadLogoLink:function(link) {
		var linkId = link.get('id');
		var progressBar = false;
		var loader = false;
		var deleteBtn = false;
		if ($defined(linkId) && linkId != '') {
			progressBar = document.id(linkId+'_progress');
			loader = document.id(linkId+'_loader');
			deleteBtn = document.id(linkId+'_delete');
		}
		var rel = link.get('rel');
		var alt = link.get('alt');
		if ($defined(rel) && rel!='') {
			var uploadtype = rel;
			var hiddenUploadFile = false;
			if ($defined(alt) && alt!='') {
				hiddenUploadFile = document.id(alt);
			}
//dbug.log('hiddenUploadFile:'+hiddenUploadFile.get('value'));													
			if (deleteBtn) {
				deleteBtn.addEvent('click', function(e){
					e.stop();
//dbug.log('hiddenUploadFile:'+hiddenUploadFile.get('value'));										
					hiddenUploadFile.set('value','-');
					$$('img.invoiceImgLogo').set('src', '').setStyle('display','none');					
					deleteBtn.setStyle('display','none');	
					mm.ajax.checkAjaxPageFormChanged(link.getParent('form'));									
//dbug.log('hiddenUploadFile:'+hiddenUploadFile.get('value'));					
				});
			}			
			
							var flashurl = '/uploadbrandinglogo';
							var extraData = {
								'uploadtype':uploadtype
								, 'username':mm.runtime.auth.username
							};
// dbug.log('setupSettingsUploadLogoLink :'+flashurl);				
							var swf = new Swiff.Uploader({
								path: '/_img/plugins/fancyupload/Swiff.Uploader.swf',
								//url: 'https://wmadmin:k4n44lw3g@vic.moneymedic.eu/uploadsingle',
								url: flashurl,
								data: extraData,
								verbose: false,
								queued: false,
								multiple: false,
								target: link,
								instantStart: true,
								typeFilter: {
									'Afbeeldingen (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'
								},
								fileSizeMax: 2 * 1024 * 1024,								
								onBeforeStart: function() {
			// dbug.log('onBeforeStart');			
									if (deleteBtn) { deleteBtn.setStyle('display','none'); }
									if (loader) { loader.setStyle('display', 'block'); }
								},								
								onSelectSuccess: function(files) {
									if (Browser.Platform.linux) window.alert('Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nSince you are prepared now, the upload will start right away ...');
			// dbug.log('Starting Upload', 'Uploading <em>' + files[0].name + '</em> (' + Swiff.Uploader.formatUnit(files[0].size, 'b') + ')');
									this.setEnabled(false);
								},
								onSelectFail: function(files) {
			// dbug.log('<em>' + files[0].name + '</em> was not added!', 'Please select an image smaller than 2 Mb. (Error: #' + files[0].validationError + ')');
alert('Selecteer een afbeelding kleiner dan 2 Mb. (Error: #' + files[0].validationError + ')');
								},
								appendCookieData: true,
								onQueue: function() {
									if (!swf.uploading) return;
									var size = Swiff.Uploader.formatUnit(swf.size, 'b');
									if (progressBar) {
										progressBar.set('html', '<span class="small">' + swf.percentLoaded + '% of ' + size + '</span>');
									}
									//link.set('html', );						
								},
								onFileComplete: function(file) {

//dbug.log('filecomplete: response = ');
//dbug.log(JSON.decode(file.response.text));						
									if (file.response.error) {
alert('Failed Upload, Uploading ' + this.fileList[0].name + ' failed, please try again. (Error: #' + this.fileList[0].response.code + ' ' + this.fileList[0].response.error + ')');
									} else {
										//var md5 = JSON.decode(file.response.text, true).hash; // secure decode

										//log.alert('Successful Upload', 'an MD5 hash was created from <em>' + this.fileList[0].name + '</em>: <code>' + md5 + '</code>.<br />gravatar.com generated a fancy and unique monsterid for it, since we did not save the image.');

										//var img = $('demo-portrait');
										//img.setStyle('background-image', img.getStyle('background-image').replace(/\w{32}/, md5));
										//img.highlight();
// dbug.log('upload succes');							
										rJson = JSON.decode(file.response.text);
									}
									var finalfilename = false;
									if ($defined(rJson.uploadtype) && $defined(rJson.filename)) {
										finalfilename = rJson.uploadtype+'/'+rJson.filename;
									}
									if ($defined(rJson.uploadtype) && $defined(rJson.thumb_name)) {
										finalthumbname = rJson.uploadtype+'/'+rJson.thumb_name;
									}
									if (hiddenUploadFile && finalfilename) {
										hiddenUploadFile.set('value',finalfilename );
									}
/*
									if (progressBar && finalfilename) {
										var finalfilelink = '<a href="/_f/'+mm.runtime.auth.username+'/'+finalfilename+'">'+rJson.filename+'</a>';
										progressBar.set('html', finalfilelink);
									}	*/

									if (progressBar) {
										progressBar.set('html', '');										
									}		
									if (finalfilename) {
										if (finalthumbname) {
											var finalimgsrc = '/_bimg/'+mm.runtime.auth.username+'/'+finalthumbname;
										} else {
											var finalimgsrc = '/_bimg/'+mm.runtime.auth.username+'/'+finalfilename;
										}
	
										if ($defined(rJson.imgsize)) {
											if ($defined(rJson.thumb_imgsize)) {
												var imgw = rJson.thumb_imgsize[0];
												var imgh = rJson.thumb_imgsize[1];												
											} else {
												var imgw = rJson.imgsize[0];
												var imgh = rJson.imgsize[1];
											}
											var imgratio = (imgw / imgh).toFloat();	
											var boundingratio = mm.runtime.brandingLogoRatio.toFloat();
//dbug.log('imgratio = '+imgratio);											
//dbug.log('boundingratio = '+boundingratio);

											if (imgratio > boundingratio) {
//dbug.log(imgratio+' is greater than '+boundingratio);												
												$$('img.invoiceImgLogo').setStyles({'width':'100%', 'height':null, 'display':'inline-block'});
											} else {
//dbug.log(imgratio+' is smaller than '+boundingratio);												
												$$('img.invoiceImgLogo').setStyles({'width':null, 'height':'100%', 'display':'inline-block'});												
											}									
										}
										$$('img.invoiceImgLogo').set('src', finalimgsrc);										
										if (deleteBtn) {
											deleteBtn.setStyle('display','inline-block');
										}
									mm.ajax.checkAjaxPageFormChanged(link.getParent('form'));
									}
									file.remove();
									this.setEnabled(true);
								},
								onComplete: function() {
									//link.set('html', 'klik again');
									if (loader) { loader.setStyle('display','none'); }
									if (deleteBtn) { deleteBtn.setStyle('display','inline-block'); }									
								}
							});

							// Button state
							link.addEvents({
								click: function() {
									return false;
								},
								mouseenter: function() {
									//this.addClass('hover');
									swf.reposition();
								},
								mouseleave: function() {
									//this.removeClass('hover');
									this.blur();
								},
								mousedown: function() {
									this.focus();
								}
							});			
			
		}		
	}
	, setupFancyUploadSingleLinks:function(fancyUploadSingleLinks) {
		fancyUploadSingleLinks.each(function(link) {
			var linkId = link.get('id');
			var progressBar = false;
			var loader = false;
			var deleteBtn = false;
			var fileDisplay = false;
			if ($defined(linkId) && linkId != '') {
				progressBar = document.id(linkId+'_progress');
				loader = document.id(linkId+'_loader');				
				fileDisplay = document.id(linkId+'_filename');
				deleteBtn = document.id(linkId+'_delete');				
			}
			var rel = link.get('rel');
			var ajaxUpdate = link.hasClass('ajaxUpdate');
			var alt = link.get('alt');
			if ($defined(rel) && rel!='') {
				var uploadtype = rel;
				var hiddenUploadFile = false;
				if ($defined(alt) && alt!='') {
					hiddenUploadFile = document.id(alt);
				}
				
				if (deleteBtn) {
					deleteBtn.addEvent('click', function(e){
						e.stop();
						hiddenUploadFile.set('value','');
						if (fileDisplay) {
							fileDisplay.empty();	
						}
						deleteBtn.setStyle('display','none');											
					});
				}
				
				//https://'+mm.runtime.auth.username+'.moneymedic.eu
				//?__fmedic__='+mm.runtime.session_id
				var flashurl = '/uploadsingle';
				var extraData = {
					'uploadtype':uploadtype
					, 'username':mm.runtime.auth.username
				};
//dbug.log('setupFancyUploadSingleLinks :'+flashurl);				
				var swf = new Swiff.Uploader({
					path: '/_img/plugins/fancyupload/Swiff.Uploader.swf',
					//url: 'https://wmadmin:k4n44lw3g@vic.moneymedic.eu/uploadsingle',
					url: flashurl,
					data: extraData,
					verbose: false,
					queued: false,
					multiple: false,
					target: link,
					instantStart: true,
					typeFilter: {
						'Bestanden (*.jpg, *.jpeg, *.gif, *.png, *.pdf, *.doc, *.txt, *.docx, *.xls, *.xlsx)': '*.jpg; *.jpeg; *.gif; *.png; *.pdf; *.doc; *.txt; *.docx, *.xls, *.xlsx'
					},
					fileSizeMax: 2 * 1024 * 1024,
					onSelectSuccess: function(files) {
						if (Browser.Platform.linux) window.alert('Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nSince you are prepared now, the upload will start right away ...');
//dbug.log('Starting Upload', 'Uploading <em>' + files[0].name + '</em> (' + Swiff.Uploader.formatUnit(files[0].size, 'b') + ')');
						this.setEnabled(false);
					},
					onBeforeStart: function() {
//dbug.log('onBeforeStart');								
						if (deleteBtn) { deleteBtn.setStyle('display','none'); }						
						if (loader) { loader.setStyle('display', 'block'); }
					},					
					onSelectFail: function(files) {
alert('' + files[0].name + ' is te groot. Selecteer een afbeelding kleiner dan 2 Mb. (Error: #' + files[0].validationError + ')');
					},
					appendCookieData: true,
					onQueue: function() {
						if (!swf.uploading) return;
						var size = Swiff.Uploader.formatUnit(swf.size, 'b');
						if (progressBar) {
							progressBar.set('html', '<span class="small">' + swf.percentLoaded + '% of ' + size + '</span>');
						}
						//link.set('html', );						
					},
					onFileComplete: function(file) {
						
//dbug.log('filecomplete: response = ');
//dbug.log(JSON.decode(file.response.text));						
						if (file.response.error) {
alert('Uploading ' + this.fileList[0].name + ' failed, please try again. (Error: #' + this.fileList[0].response.code + ' ' + this.fileList[0].response.error + ')');
						} else {
							//var md5 = JSON.decode(file.response.text, true).hash; // secure decode

							//log.alert('Successful Upload', 'an MD5 hash was created from <em>' + this.fileList[0].name + '</em>: <code>' + md5 + '</code>.<br />gravatar.com generated a fancy and unique monsterid for it, since we did not save the image.');

							//var img = $('demo-portrait');
							//img.setStyle('background-image', img.getStyle('background-image').replace(/\w{32}/, md5));
							//img.highlight();
//dbug.log('upload succes');							
							rJson = JSON.decode(file.response.text);
						}
						var finalfilename = false;
						if ($defined(rJson.uploadtype) && $defined(rJson.filename)) {
							finalfilename = rJson.uploadtype+'/'+rJson.filename;
						}
						if (hiddenUploadFile && finalfilename) {
							hiddenUploadFile.set('value',finalfilename );
						}
						if (fileDisplay && finalfilename) {
							var finalfilelink = '<a href="/_f/'+mm.runtime.auth.username+'/'+finalfilename+'">'+rJson.filename.substr(11)+'</a>';
							fileDisplay.set('html', finalfilelink);
							if (deleteBtn) { deleteBtn.setStyle('display','inline-block'); }							
						}			
						if (progressBar) {
							progressBar.set('html', '');
						}			
						file.remove();
						this.setEnabled(true);
						if (ajaxUpdate) {
alert('nu ajaxupdate');							
						}
					},
					onComplete: function() {
						//link.set('html', 'klik again');
						if (loader) { loader.setStyle('display', 'none');  }						
												
					}
				});

				// Button state
				link.addEvents({
					click: function() {
						return false;
					},
					mouseenter: function() {
						this.addClass('hover');
						swf.reposition();
					},
					mouseleave: function() {
						this.removeClass('hover');
						this.blur();
					},
					mousedown: function() {
						this.focus();
					}
				});
				
				
			}
		});
	}
	,setupInfoToggleLinks:function(infoToggleLinks) {
		infoToggleLinks.each(function(link) {
			var container = link.getParent('.infoContainer');
			if (container) {
				var infoBody = container.getElement('.infoBody');
				if (infoBody) {
					link.store('infoBody', infoBody);
				}
			}
			link.addEvent('click', function(e) {
				e.stop();
				var infoBody = link.retrieve('infoBody');
				if (infoBody) {
					if (infoBody.getStyle('display') == 'none') {
						infoBody.setStyle('display','block');
					} else {
						infoBody.setStyle('display','none');						
					}
				}
			});
		},this);
	}
	, hideFailedValidationOnTabs:function(form, fromEl, subtab) {
		if (!$defined(fromEl)) { fromEl = false; }
		if (!$defined(subtab)) { subtab = false; }		
// dbug.log('hideFailedValidationOnTabs fromEl ='+fromEl );		
		var curPanel = false; var curSubPanel = false;
		var mmTabsContainer = form.getElement('.mmTabsContainer');
		if (mmTabsContainer) {
			var mmTabButtons = mmTabsContainer.getElements('.mmTabButtons li');
			var mmTabPanels = mmTabsContainer.getElements('.mmTabPanel');
			if (fromEl) {
				curPanel = fromEl.getParent('.mmTabPanel');
				curSubPanel = fromEl.getParent('.mmSubTabPanel');

			}
			mmTabButtons.each(function(btn,index) {
				var badge = btn.getElement('div.mmTabButtonWarningBadge');				
				if (fromEl ) {			
					if (mmTabPanels[index]==curPanel) {
						if (subtab) {
							// hier nog de subtabbuttons				
							var mmSubTabsContainer = mmTabPanels[index].getElement('.mmSubTabsContainer');
							if (mmSubTabsContainer) {
								var mmSubTabButtons = mmSubTabsContainer.getElements('.mmSubTabButtons li');
								var mmSubTabPanels = mmSubTabsContainer.getElements('.mmSubTabPanel');								
								mmSubTabPanels.each(function(subpanel,j) {
									if (mmSubTabPanels[j] == subtab) {
										mmSubTabButtons[j].removeClass('validation-failed-some');								
									}
								});
								
								var remainingFailed = mmSubTabsContainer.getElements('.mmSubTabButtons li[class~=validation-failed-some]');
								if (remainingFailed.length == 0 ) {
									// only now remove main tab badge
									if (index != 1) {
										if (badge) { badge.setStyle('display','none'); }
									} else {
										var d = mmTabPanels[index].getElement('invoice_nr_count_hidden');  //-------
										if (d) {
											if (d.get('value') != 0 ) {
												if (badge) { badge.setStyle('display','none'); }							
											}
										}
									}									
								}
							}
							
														
						} else {
							if (index != 1) {
								if (badge) { badge.setStyle('display','none'); }
							} else {
								var d = mmTabPanels[index].getElement('invoice_nr_count_hidden');  //-------
								if (d) {
									if (d.get('value') != 0 ) {
										if (badge) { badge.setStyle('display','none'); }							
									}
								}
							}	
							// hier nog de subtabbuttons				
							var mmSubTabsContainer = mmTabPanels[index].getElement('.mmSubTabsContainer');
							if (mmSubTabsContainer) {
								var mmSubTabButtons = mmSubTabsContainer.getElements('.mmSubTabButtons li');
								var mmSubTabPanels = mmSubTabsContainer.getElements('.mmSubTabPanel');								
								mmSubTabPanels.each(function(subpanel,j) {
									mmSubTabButtons[j].removeClass('validation-failed-some');								
								});
							}											
						}
					}
				} else {
					if (index != 1) {
						if (badge) { badge.setStyle('display','none'); }
					} else {
						var d = mmTabPanels[index].getElement('invoice_nr_count_hidden');  //-------
						if (d) {
							if (d.get('value') != 0 ) {
								if (badge) { badge.setStyle('display','none'); }							
							}
						}
					}
				
					// hier nog de subtabbuttons				
					var mmSubTabsContainer = mmTabPanels[index].getElement('.mmSubTabsContainer');
					if (mmSubTabsContainer) {
						var mmSubTabButtons = mmSubTabsContainer.getElements('.mmSubTabButtons li');
						var mmSubTabPanels = mmSubTabsContainer.getElements('.mmSubTabPanel');								
						mmSubTabPanels.each(function(subpanel,j) {
							mmSubTabButtons[j].removeClass('validation-failed-some');								
						});
					}				
				}
			});
			
		}		
	}
	, showFailedValidationOnTabs:function(el, form) {
		var mmTabsContainer = form.getElement('.mmTabsContainer');
		if (mmTabsContainer) {
			var mmTabButtons = mmTabsContainer.getElements('.mmTabButtons li');
			var mmTabPanels = mmTabsContainer.getElements('.mmTabPanel');
					
			var failedPanels = [];
			var failedSubPanels = [];

			var panel = el.getParent('.mmTabPanel');
			var subpanel = el.getParent('.mmSubTabPanel');
			if (subpanel) {
				failedSubPanels.push(subpanel);	
			}
			failedPanels.push(panel);

			mmTabPanels.each(function(panel,i) {
				if (failedPanels.contains(panel)) {
					//mmTabButtons[i].getElement('a').setStyle('color', '#ff0000');
					mmTabButtons[i].addClass('validation-failed-some');
					var badge = mmTabButtons[i].getElement('div.mmTabButtonWarningBadge');
					if (badge) {
						badge.setStyle('display','block');
					}					
				}
				var mmSubTabsContainer = panel.getElement('.mmSubTabsContainer');
				if (mmSubTabsContainer) {
					var mmSubTabButtons = mmSubTabsContainer.getElements('.mmSubTabButtons li');
					var mmSubTabPanels = mmSubTabsContainer.getElements('.mmSubTabPanel');								
					mmSubTabPanels.each(function(subpanel,j) {
						if (failedSubPanels.contains(subpanel)) {
							//mmSubTabButtons[j].getElement('a').setStyle('color', '#ff0000');
							mmSubTabButtons[j].addClass('validation-failed-some');								
						}
					});
				}
			});		
		}
	}
	, setupInvoiceEditAreas:function(invoiceEditAreas) {
		invoiceEditAreas.each(function(area){
			area.addEvents({
				'mouseenter':function(e) {
					area.addClass('isEditable');
				}
				, 'mouseleave':function(e) {
					if (!area.retrieve('isEditable',false)) {
						area.removeClass('isEditable');
					}
				}
			});
		},this);
	}
	, setupEditSpans:function(editSpans) {
		editSpans.each(function(editSpan) {
			var rel = editSpan.get('rel');
			var invoiceEditArea = editSpan.getParent('.invoiceEditArea');
			if (rel) {
				var hiddenInput = document.id(rel);
				if (hiddenInput) {
					editSpan.store('hiddenInput', hiddenInput);		
					hiddenInput.store('oldValue', hiddenInput.get('value'));			
				}
				var editSpanBtn = document.id(rel+'_editbtn');
				if (editSpanBtn) {
					editSpan.store('editSpanBtn', editSpanBtn);
				}
				var required = editSpan.hasClass('required');				
				if (hiddenInput && editSpanBtn) {
					var theForm = hiddenInput.getParent('form');
					if (theForm && theForm.hasClass('ajaxBlurForm')) {
						theForm.addEvent('submit', function(e) { return false; }).store('ajaxBlurForm', true);
					}
					var theBlurContainer = hiddenInput.getParent('div.ajaxBlurContainer');
					if (theBlurContainer) { theBlurContainer.store('ajaxBlurContainer', true); }
					var dummyText = editSpan.getElement('span.dummyText');						
					if (dummyText) { 
						dummyText = dummyText.dispose();
						editSpan.store('dummyText', dummyText); 						
						var cnt = editSpan.get('html');
						if (!$chk(cnt)) {
							dummyText.inject(editSpan);
						}						
					}

					// BTN ONCLICK
					editSpanBtn.addEvent('click', function(e) {						
						e.stop();
						if (invoiceEditArea) { invoiceEditArea.store('isEditable', true); }
						var dummyText = editSpan.getElement('span.dummyText');							
						var oldtitle = editSpan.get('text');				
						if (dummyText) { oldtitle = ''; }						
						editSpan.set('text','');
						var input = new Element('input', {'class':'editSpanInput wp100'}).set('value',oldtitle).inject(editSpan);
						editSpanBtn.setStyle('display', 'none');				
						editSpan.store('isEditable', true);						
						input.addEvent('blur', function(e) {
							var newtitle = this.get('value').trim();
							if (newtitle == '' && required) {
								input.addClass('validation-failed');
							} else {
								if (invoiceEditArea) { invoiceEditArea.store('isEditable', false).removeClass('isEditable'); }														
								this.destroy();
								if (newtitle == '') {
									var dummyText = editSpan.retrieve('dummyText', false);																	
									if (dummyText) { dummyText.inject(editSpan); }								
								} else {									
									editSpan.set('text', newtitle);
								}								
								hiddenInput.set('value', newtitle);
								var theform = hiddenInput.getParent('form');
								if (theform.retrieve('mmChangeForm',false) && hiddenInput.retrieve('oldValue',false) !== newtitle) {										
									mm.ajax.checkAjaxPageFormChanged(theform);
								}
								var theBlurContainer = hiddenInput.getParent('div.ajaxBlurContainer');
								if (theBlurContainer && theBlurContainer.get('rel')!='') { 
//dbug.log('ajax blur container');											
									var formdataqs = theBlurContainer.toQueryString();
									var formdata = formdataqs.parseQueryString();
									var action = theBlurContainer.get('rel');
									if (action.charAt(0)=='/') { action = action.substr(1,action.length); }							
									var ajaxurl = '/_x/'+action;										
									new Request.JSON({
										url:ajaxurl
										, method:'post'
										, data: formdata
										, onRequest: function() {

										}
										, onFailure: function() {

										}
										, onSuccess: function(rJson, rText) {
//dbug.log(rJson);
										}
									}).send();
								}																							
								if (theform.retrieve('ajaxBlurForm', false)) {
//dbug.log('AJAXBLURFORM');											
									var formdataqs = theform.toQueryString();
									var formdata = formdataqs.parseQueryString();
									var action = theform.get('action');
									if (action.charAt(0)=='/') { action = action.substr(1,action.length); }							
									var ajaxurl = '/_x/'+action;										
									new Request.JSON({
										url:ajaxurl
										, method:'post'
										, data: formdata
										, onRequest: function() {

										}
										, onFailure: function() {

										}
										, onSuccess: function(rJson, rText) {
//dbug.log(rJson);
										}
									}).send();
								}
																								
								editSpanBtn.setStyle('display', 'inline-block');
								editSpan.store('isEditable', false);
							}
						}.bind(input));
						input.addEvent('keypress', function(e) {
							if (e.key=='enter') {
								e.stop();
								input.blur();
							}
						}.bind(input));
						input.focus();												
					});
					
					// SPAN ONCLICK
					editSpan.addEvent('click', function(e) {
						
						e.stop();
						if (invoiceEditArea) { invoiceEditArea.store('isEditable', true); }						
						if (editSpan.retrieve('isEditable', false)) { return false; }		
						var dummyText = editSpan.getElement('span.dummyText');																
						var oldtitle = editSpan.get('text');				
						if (dummyText) { oldtitle = ''; }
						editSpan.set('text','');
						var input = new Element('input', {'class':'editSpanInput wp100'}).set('value',oldtitle).inject(editSpan);
						editSpanBtn.setStyle('display', 'none');				
						editSpan.store('isEditable', true);						
						input.addEvent('blur', function(e) {
							if (invoiceEditArea) { invoiceEditArea.store('isEditable', false).removeClass('isEditable'); }							
							var newtitle = this.get('value').trim();
													
							if (newtitle == '' && required) {
								input.addClass('validation-failed');								
							} else {							
								this.destroy();
								if (newtitle == '') {
									var dummyText = editSpan.retrieve('dummyText', false);																	
									if (dummyText) { dummyText.inject(editSpan); }								
								} else {									
									editSpan.set('text', newtitle);
								}
								hiddenInput.set('value', newtitle);
								var theform = hiddenInput.getParent('form');
								if (theform.retrieve('mmChangeForm',false) && hiddenInput.retrieve('oldValue',false) !== newtitle) {										
									mm.ajax.checkAjaxPageFormChanged(theform);
								}
								var theBlurContainer = hiddenInput.getParent('div.ajaxBlurContainer');
								if (theBlurContainer && theBlurContainer.get('rel')!='') { 
//dbug.log('ajax blur container');											
									var formdataqs = theBlurContainer.toQueryString();
									var formdata = formdataqs.parseQueryString();
									var action = theBlurContainer.get('rel');
									if (action.charAt(0)=='/') { action = action.substr(1,action.length); }							
									var ajaxurl = '/_x/'+action;										
									new Request.JSON({
										url:ajaxurl
										, method:'post'
										, data: formdata
										, onRequest: function() {

										}
										, onFailure: function() {

										}
										, onSuccess: function(rJson, rText) {
//dbug.log(rJson);
										}
									}).send();
								}																	
								if (theform.retrieve('ajaxBlurForm', false)) {
									var formdataqs = theform.toQueryString();
									var formdata = formdataqs.parseQueryString();
									var action = theform.get('action');
									if (action.charAt(0)=='/') { action = action.substr(1,action.length); }							
									var ajaxurl = '/_x/'+action;										
									new Request.JSON({
										url:ajaxurl
										, method:'post'
										, data: formdata
										, onRequest: function() {

										}
										, onFailure: function() {

										}
										, onSuccess: function(rJson, rText) {
//dbug.log(rJson);
										}
									}).send();
								}															
								editSpanBtn.setStyle('display', 'inline-block');
								editSpan.store('isEditable', false);
							}
						}.bind(input));
						input.addEvent('keypress', function(e) {
							if (e.key=='enter') {
								e.stop();
								input.blur();
							}
						}.bind(input));						
						input.focus();												
					});					
				}
			}
		},this);
	}
	, setupEditSpanTexts:function(editSpanTexts) {
		editSpanTexts.each(function(editSpanText) {
			var rel = editSpanText.get('rel');
			var alt = editSpanText.get('alt');
			var maxHeight = false;
			if ($chk(alt)) { 
				if (alt.test(':')) {
					var split = alt.split(':');
					switch(split[0]) {
						case 'maxHeight':
							maxHeight = split[1].toInt(); 						
						break;
					}
				}
			}
			var invoiceEditArea = editSpanText.getParent('.invoiceEditArea');			
			if (rel) {
				var hiddenInput = document.id(rel);
				if (hiddenInput) {
					editSpanText.store('hiddenInput', hiddenInput);					
					hiddenInput.store('oldValue', hiddenInput.get('value'));
				}
				var editSpanTextBtn = document.id(rel+'_editbtn');
				if (editSpanTextBtn) {
					editSpanText.store('editSpanBtn', editSpanTextBtn);
				}
				var required = editSpanText.hasClass('required');
				if (hiddenInput && editSpanTextBtn) {	
						var theForm = hiddenInput.getParent('form');
						if (theForm && theForm.hasClass('ajaxBlurForm')) {
							theForm.addEvent('submit', function(e) { return false; }).store('ajaxBlurForm', true);
						}
						var theBlurContainer = hiddenInput.getParent('div.ajaxBlurContainer');
						if (theBlurContainer) { theBlurContainer.store('ajaxBlurContainer', true); }						
						var dummyText = editSpanText.getElement('span.dummyText');						
						if (dummyText) { 
							dummyText = dummyText.dispose();
							editSpanText.store('dummyText', dummyText); 						
							var cnt = editSpanText.get('html');
							if (!$chk(cnt)) {
								dummyText.inject(editSpanText);
							}							
						}					
						
						if (maxHeight) {
							editSpanText.setStyles({'height':maxHeight+2, 'overflow':'hidden'});
						}
						
						// BUTTON ONCLICK											
						editSpanTextBtn.addEvent('click', function(e) {
							e.stop();									
							if (invoiceEditArea) { invoiceEditArea.store('isEditable', true); }														
							var dummyText = editSpanText.getElement('span.dummyText');						
							var oldcnt = editSpanText.get('html');	
							if (dummyText) { oldcnt = ''; }
							editSpanText.set('html','');
							editSpanText.store('isEditable', true);
							var textarea = new Element('textarea', {'class':'editSpanTextarea wp100'}).set('value',oldcnt.replace(/\<br\>/ig,"\r")).inject(editSpanText);
							editSpanTextBtn.setStyle('display', 'none');
							
							if (maxHeight) {							
								textarea.setStyles({'height':maxHeight, 'overflow':'hidden'});
							}
							
							textarea.addEvent('blur', function(e) {
								var newcnt = this.get('value');
								if (newcnt.trim() == '' && required) {
									textarea.addClass('validation-failed');
								} else {
									if (invoiceEditArea) { invoiceEditArea.store('isEditable', false).removeClass('isEditable'); }																	
									this.destroy();
									var displaycnt = newcnt.replace(/\n/g,'<br>');
									if (displaycnt.trim() == '') {
										var dummyText = editSpanText.retrieve('dummyText', false);									
										if (dummyText) { dummyText.inject(editSpanText).setStyle('display','inline-block'); }										
									} else {									
										editSpanText.set('html', displaycnt);
									}
									hiddenInput.set('value', newcnt);
									var theform = hiddenInput.getParent('form');
									if (theform.retrieve('mmChangeForm',false) && hiddenInput.retrieve('oldValue',false) !== newcnt) {										
										mm.ajax.checkAjaxPageFormChanged(theform);
									}	
									var theBlurContainer = hiddenInput.getParent('div.ajaxBlurContainer');
									if (theBlurContainer && theBlurContainer.get('rel')!='') { 
//	dbug.log('ajax blur container');											
										var formdataqs = theBlurContainer.toQueryString();
										var formdata = formdataqs.parseQueryString();
										var action = theBlurContainer.get('rel');
										if (action.charAt(0)=='/') { action = action.substr(1,action.length); }							
										var ajaxurl = '/_x/'+action;										
										new Request.JSON({
											url:ajaxurl
											, method:'post'
											, data: formdata
											, onRequest: function() {

											}
											, onFailure: function() {

											}
											, onSuccess: function(rJson, rText) {
//	dbug.log(rJson);
											}
										}).send();
									}									
									if (theform.retrieve('ajaxBlurForm', false)) {
										var formdataqs = theform.toQueryString();
										var formdata = formdataqs.parseQueryString();
										var action = theform.get('action');
										if (action.charAt(0)=='/') { action = action.substr(1,action.length); }							
										var ajaxurl = '/_x/'+action;										
										new Request.JSON({
											url:ajaxurl
											, method:'post'
											, data: formdata
											, onRequest: function() {

											}
											, onFailure: function() {

											}
											, onSuccess: function(rJson, rText) {
//dbug.log(rJson);
											}
										}).send();
									}								
									editSpanTextBtn.setStyle('display', 'inline-block');
									editSpanText.store('isEditable', false);																				
								}
							}.bind(textarea));
							if (!maxHeight) {							
								new mm.TextareaGrow(textarea, {minSize:30});
							}
							textarea.focus();					
						});
								
						// SPAN ONCLICK
						editSpanText.addEvent('click', function(e) {
							e.stop();
							
							if (editSpanText.retrieve('isEditable', false)) { return false; }																	
							var dummyText = editSpanText.getElement('span.dummyText');												
							if (invoiceEditArea) { invoiceEditArea.store('isEditable', true); }														
							var oldcnt = editSpanText.get('html');				
							editSpanText.set('html','');
							if (dummyText) { oldcnt = ''; }							
							var textarea = new Element('textarea', {'class':'editSpanTextarea wp100'}).set('value',oldcnt.replace(/\<br\>/ig,"\r")).inject(editSpanText);
							editSpanTextBtn.setStyle('display', 'none');				
							editSpanText.store('isEditable', true);
							
							if (maxHeight) {
								textarea.setStyles({'height':maxHeight, 'overflow':'hidden'});
							}
							
							
							textarea.addEvent('blur', function(e) {
								var newcnt = this.get('value');
								if (newcnt.trim() == '' && required) {
									textarea.addClass('validation-failed');
								} else {								
									if (invoiceEditArea) { invoiceEditArea.store('isEditable', false).removeClass('isEditable'); }								
									this.destroy();
									var displaycnt = newcnt.replace(/\n/g,'<br>');
									if (displaycnt.trim() == '') {
										var dummyText = editSpanText.retrieve('dummyText', false);									
										if (dummyText) { dummyText.inject(editSpanText).setStyle('display','inline-block'); }
									} else {									
										editSpanText.set('html', displaycnt);
									}
									hiddenInput.set('value', newcnt);
									var theform = hiddenInput.getParent('form');
									if (theform.retrieve('mmChangeForm',false) && hiddenInput.retrieve('oldValue',false) !== newcnt) {										
										mm.ajax.checkAjaxPageFormChanged(theform);
									}
									var theBlurContainer = hiddenInput.getParent('div.ajaxBlurContainer');
									if (theBlurContainer && theBlurContainer.get('rel')!='') { 
//	dbug.log('ajax blur container');											
										var formdataqs = theBlurContainer.toQueryString();
										var formdata = formdataqs.parseQueryString();
										var action = theBlurContainer.get('rel');
										if (action.charAt(0)=='/') { action = action.substr(1,action.length); }							
										var ajaxurl = '/_x/'+action;										
										new Request.JSON({
											url:ajaxurl
											, method:'post'
											, data: formdata
											, onRequest: function() {

											}
											, onFailure: function() {

											}
											, onSuccess: function(rJson, rText) {
//	dbug.log(rJson);
											}
										}).send();
									}									
									if (theform.retrieve('ajaxBlurForm', false)) {
										var formdataqs = theform.toQueryString();
										var formdata = formdataqs.parseQueryString();
										var action = theform.get('action');
										if (action.charAt(0)=='/') { action = action.substr(1,action.length); }							
										var ajaxurl = '/_x/'+action;										
										new Request.JSON({
											url:ajaxurl
											, method:'post'
											, data: formdata
											, onRequest: function() {

											}
											, onFailure: function() {

											}
											, onSuccess: function(rJson, rText) {
//dbug.log(rJson);
											}
										}).send();
									}									
									editSpanTextBtn.setStyle('display', 'inline-block');
									editSpanText.store('isEditable', false);																												
								}
							}.bind(textarea));
							if (!maxHeight) {														
								new mm.TextareaGrow(textarea, {minSize:30});
							}
							textarea.focus();					
						});								
			}
		}
		},this);
	}
	, setupEditSpanSelects:function(editSpanSelects) {
		editSpanSelects.each(function(editSpanSelect) {
			var rel = editSpanSelect.get('rel');
			if (rel) {
				
			}			
		},this);
	}
	, initDatePickers:function(datePickerInputs, container) {
		
		datePickerInputs.each(function(input) {
//dbug.log('initDefaultDatePickers el='+input);			
			var next = input.getNext('input[type=text][class~=timepicker]');
			var timePickerElement = false; 
			if ($defined(next)) { timePickerElement = next; }; 
			var startTimestamp = false;
			var initialStringVallue = false;
			var minimumDate = false;
			var maximumDate = false;			
			var altT = input.get('alt');		
			if (altT!='') { 
				var extra = JSON.decode(altT);
				if (extra && extra.timestamp) { startTimestamp = extra.timestamp; }
				if (extra && extra.initialString) { initialStringVallue = extra.initialString; }	
				if (extra && extra.minDate) { 
					minimumDate = { date:extra.minDate, format:'U' }; 
//dbug.log('MINDATE = '+extra.minDate);									
				}
				if (extra && extra.maxDate) { maximumDate = { date:extra.maxDate, format:'U'};  }

			}
			var toggleEl = null;
			var calendarImg = input.getNext('img[class~=datepickerimg]');
//dbug.log('calendarImg = '+calendarImg);			
			if (calendarImg) {
				toggleEl = calendarImg;
			}
			var calendar = new DatePicker(input, {
				pickerClass: 'datepicker_dashboard',
			            inputOutputFormat: 'U'
			            , format: 'd-m-Y'
						, days: ['Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag']
						, months: ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'October', 'November', 'December']
			            , allowEmpty: false
						, toggleElement: toggleEl
						, debug: false
						, timePicker: false
						, startView: 'month'
						, startDate: startTimestamp
						, timePickerEl: timePickerElement
						, initialString: initialStringVallue	// input initial value other than a date formatted string
						, minDate: minimumDate
						, maxDate: maximumDate
						, onSelect: function() {
//							alert(input.get('value'));
//dbug.log('datepicker select');						
							this.datePickerSelect(input);	
						}.bind(this)
			        });			
		},this);		
	}		
	, datePickerSelect:function(input) {
//dbug.log('date picker selected something: '+input.get('value'));		
	}
	, savePageFormRequestStart:function() {
		mm.overlayAll.show();
		mm.overlayAll.showNotice('loading', mm.lang.notice_info.saving);
		//mm.noticeInfo.show({title:mm.lang.notice_info.saving});
	}
	, savePageFormRequestFailure:function() {
		mm.overlayAll.hide(true);
	}
	, savePageFormRequestSucces:function(rJson, rText, formdata) {
//dbug.log('savePageFormRequestSucces, rJson.saved = '+rJson.saved);		
		if (rJson.saved) {
//dbug.log(rJson);			
			//mm.noticeInfo.show({title:'opgeslagen'});	
			if (mm.runtime.request == 'purchase') {
				window.location.href = '/purchases';
			} else if (mm.runtime.request == 'settings') {
				/*
				mm.overlayAll.hide(true);			
				//mm.noticeInfo.show({title:mm.lang.notice_info.saved});
				var settingsForm = document.id('settingsForm');		
				if (settingsForm.retrieve('mmChangeForm',false)) {
					settingsForm.store('mmChanged', false);
					var saveBtn = settingsForm.retrieve('saveBtn');
					if (saveBtn) {
						saveBtn.addClass('inactive').setStyle('opacity',0.2);						
					}
					var ajaxPageSaveReminder = document.id('ajaxPageSaveReminder');
					if (ajaxPageSaveReminder) {
						ajaxPageSaveReminder.setStyles({'top':'10px','left':'0px','display':'none'});
					}
				}
				*/
				
				(function() { 
					//window.location.href = window.location.href 
					var hash = '';
					if (window.location.hash != '') {				
						hash = window.location.hash;
					}
					//window.location.reload();
					//window.location.href = window.location.href;
					document.location.reload(true);
				}).delay(10,mm);				
				
			} else if (mm.runtime.request == 'invoice') {
				if (rJson.saved) {
					if (rJson.invoice_id) {
						// if (formdata.action == 'save_concept') {
						// 	(function() { window.location.href = '/invoices'; }).delay(200,this);					
						// } else {
						// 	(function() { window.location.href = '/invoice/'+rJson.invoice_id; }).delay(20,this);					
						// }
						(function() { window.location.href = '/invoice/'+rJson.invoice_id; }).delay(20,this);											
					}
				}				
			} else {		
				(function() { 
					//window.location.href = window.location.href 
					var hash = '';
					if (window.location.hash != '') {				
						hash = window.location.hash;
					}
					//window.location.reload();
					//window.location.href = window.location.href;
					document.location.reload(true);
				}).delay(10,mm);			
			}
		} else {
			mm.overlayAll.hide(true);			
			mm.noticeError.show({title:'fout bij opslaan'});
		}
	}
	, setupToggleDivLinks:function(toggleDivLinks) {
		toggleDivLinks.each(function(link) {
			var pDiv = link.getParent('div[class~=toggleDiv]');
			if (pDiv) {
				var sDiv = pDiv.getNext('div[class~=toggleDiv]');
				if (!sDiv) {
					sDiv = pDiv.getPrevious('div[class~=toggleDiv]');
				}
				if (sDiv) {

					link.addEvent('click', function(e) {
						//$(pDiv).setStyle('display','none');
						//$(sDiv).setStyle('display','block');
						e.stop();
						var oldh = pDiv.getSize().y;
//						pDiv.fade('out');
						pDiv.hide();
						//pDiv.set('morph', {duration:'normal', transition:'sine:in:out',link:'chain' }).setStyles({'display':'block'}).morph({display:'block','height':[oldh,0]}).morph({'height':null,'display':'none'});						
						sDiv.setStyle('display','block');
						var newh = sDiv.getSize().y;
						//sDiv.set('morph', {duration:'normal', transition:'expo:out',link:'chain' }).setStyles({'display':'block','overflow':'hidden'}).morph({display:'block','height':[0,newh]}).morph({'height':null,'overflow':'visible'});
						pDiv.hide();
						sDiv.setStyle('opacity',0.5);
						sDiv.fade('in');
					});
				}
			}
		});
	}	
	, setupToggleDivChildrenLinks:function(toggleDivChildrenLinks) {
		toggleDivChildrenLinks.each(function(link) {
			var children = link.getNext('div');
			if (children) {
				link.addEvent('click', function(e) {
					e.stop();
					if (children.getStyle('display')=='block') {
						children.setStyle('display','none');						
					} else {
						children.setStyle('display','block');
					}
					link.blur();
				});
			}
		},this);
	}
	, setupTabContainers:function(container) {
		var panels = container.getElements('div.mmTabPanel');
		var buttons = container.getElements('ul.mmTabButtons li a');			
		var tabs = new mm.Tabs(panels, buttons, {
			useFade: true, useHover: false, fadeProps:{duration:400, transition:'circ:in:out'}				
		});
// dbug.log(window.location.hash);		
		if (window.location.hash != '') {
			var hashAr = window.location.hash.split('_');
			buttons.each(function(btn,i) {				
				if (btn.get('href') == hashAr[0]) {
					tabs.show(i);
				}
			});
		} else {
			if (mm.runtime.request=='invoice') {
				tabs.show(buttons.length-1);
			}
		}
		//tabs.show(1);
	}
	, setupSubTabContainers:function(subtabContainers) {
		subtabContainers.each(function(container) {
			var panels = container.getElements('div.mmSubTabPanel');
			var buttons = container.getElements('ul.mmSubTabButtons li a');			
			new mm.Tabs(panels, buttons, {
				useFade: true, useHover: false, fadeProps:{duration:400, transition:'circ:in:out'}				
			});		
		},this);
	}
}); mm.OverlayAllClass = new Class ({
	
	Implements: [Options, Events],
	options : {
		element : false
		, defaultId: 'mmOverlayAll'
		, overlayTween: { 'duration':500, 'transition':'quad:in:out' }		
		, noticeTween : { 'duration':250, 'transition':'circ:out' }
		, dialogTween : { 'duration':400, 'transition':'quad:out' }
		, dialogContentTween : { 'duration':400, 'transition':'quad:out' }		
		, overlayOpacity: 0.70		
		, noticeTexts : new Hash({
			'loading_dashboard' : 'Loading dashboard interface ...'
			, 'loading_widgets' : 'Loading widgets ...' 
			, 'creating_toolbars' : 'Creating toolbars ...'
			, 'loading_confirmunload' : 'Waiting for confirmation to leave the page ...'
		})
		, ajaxDelay: 500
		, dialogDims : {'small':{'width':440, 'height':220}, 'large':{'width':600, 'height':400}}
		, staticDialogContents : new Hash({
			'none' : { type:'none', message: ''}
			, 'loginpoll_failure' : { 
				type:'error'
				, modal : true
				, message :'...' 
				, body : '<div class="warningContainer">'
								+'<div class="warningIcon"><img src="/_img/icons/warning.png" border="0" /></div>'
								+'<div class="warningTitle">{message}</div>'
							+'</div>'
				, footer : '<div class="mmOverlayAllDialogFooterToolbar">'
								+ '<a href="#" id="btn_loginpoll_failure_close" class="dialogactionbutton "><span class="aBtnIcon" style="background-image:url(/_img/icons/action_21x21close.png);"></span> sluiten</a>'
								+ '<a href="#" id="btn_loginpoll_failure_reconnect" class="dialogactionbutton "><span class="aBtnIcon" style="background-image:url(/_img/icons/action_21x21ok.png);"></span> verbinden</a>'
							+ '</div>'

			}
			, 'loginpoll_expired' : { 
				type: 'error'
				, modal : true				
				, message :'...' 
				, body : '<div class="warningContainer">'
								+'<div class="warningIcon"><img src="/_img/icons/warning.png" border="0" /></div>'
								+'<div class="warningTitle">{message}</div>'
							+'</div>'
				, footer : '<div class="mmOverlayAllDialogFooterToolbar">'
								+ '<a href="#" id="btn_loginpoll_expired_close" class="dialogactionbutton "><span class="aBtnIcon" style="background-image:url(/_img/icons/action_21x21close.png);"></span> sluiten</a>'
							+ '</div>'				

			}
			, 'logout_confirm' : {
				type: 'info'
				, modal : false				
				, message : '...'
				, body : '<div class="warningContainer">'
								+'<div class="warningIcon"><img src="/_img/icons/warning.png" border="0" /></div>'
								+'<div class="warningTitle">{message}</div>'
							+'</div>'	
				, footer : '<div class="mmOverlayAllDialogFooterToolbar">'
								+ '<a href="#" id="btn_logout_confirm_cancel" class="dialogactionbutton "><span class="aBtnIcon" style="background-image:url(/_img/icons/action_21x21close.png);"></span> annuleren</a>'
								+ '<a href="#" id="btn_logout_confirm_ok" class="dialogactionbutton "><span class="aBtnIcon" style="background-image:url(/_img/icons/action_21x21ok.png);"></span> uitloggen</a>'
							+ '</div>'
			}
		})
		
	},
	initialize:function(options) {
		this.setOptions(options);
		this.element = false;
		this.isOpen = false;
		this.isDialogOpen = false;
		this.isConfirmDialogOpen = false;
		this.curDialog = false;
		this.bound = this.bound||{};
		this.dialogContents = this.options.dialogContents;		
		this.dialogs = new Hash({});
		this.dialogType = false;
		this.dialogLink = false;
		this.dialogAction = false;	
		this.dialogExtraOptions = false;	
		this.confirmDialogAction = false;
		this.dialogIsSaving = false;
		this.staticDialogContents = this.options.staticDialogContents;
		this.curStaticDialogContents = false;
		this.setupElements();
		this.setupEvents();
		
		// no automatic showing on each page:
		//this.showNotice('loading', 'hier nog tekstje vanuit de app language file');
		//this.updateNotice.delay(1000, this, [wm.lang.notice.loading_widgets]);				
		//this.hide.delay(2000, this);
	},
	setupElements: function() {
		if (this.options.element) {
			if (document.id(this.options.element)) {
				this.element = document.id(this.options.element);
			} 
		}
		if (!this.element) { this.makeElement(); }		
		//var elZ = this.element.getStyle('z-index').toInt();
		var elZ = 9000;		
		this.noticeContainer = new Element('div', {'id':'mmOverlayAllNoticeContainer'}).setStyle('z-index',(elZ+1));
		this.notice = new Element('div', {'id':'mmOverlayAllNotice'}).inject(this.noticeContainer);
		this.noticeIconLoading = new Element('div', {'id':'mmOverlayAllNoticeIconLoading'}).set('html','&nbsp;').inject(this.notice);
        this.noticeLoader = new APNG(this.noticeIconLoading, { useNative: false, frames: 7, autoStart:false, endless: true, property: 'background-position', axis: 'x', interval: 100, preload: true, startFrame: 0} );		
		this.noticeText = new Element('div', {'id':'mmOverlayAllNoticeText'}).inject(this.notice);		
		this.noticeContainer.inject(this.element, 'after');		
		this.noticeContainer.setStyles({'display':'block','opacity':0}).pin();
		this.noticeContainer.setStyle('display','none');
		this.noticeIcons = [this.noticeIconLoading];
		
		this.dialogContainer = new Element('div', {'id':'mmOverlayAllDialogContainer'}).setStyle('z-index',(elZ+2));
		this.dialogOverlay = new Element('div', {'id':'mmOverlayAllDialogOverlay'}).inject(this.dialogContainer);
		this.dialogOverlayNotice = new Element('div', {'id':'mmOverlayAllDialogOverlayNotice'}).inject(this.dialogOverlay);
		this.dialogOverlayText = new Element('div', {'id':'mmOverlayAllDialogOverlayText'}).inject(this.dialogOverlayNotice);		
		this.dialogOverlayLoader = new Element('div', {'id':'mmOverlayAllDialogOverlayLoader'}).inject(this.dialogOverlayNotice);		
		this.dialog = new Element('div', {'id':'mmOverlayAllDialog'}).inject(this.dialogContainer);
		this.dialogCloseBtn = new Element('a', {'id':'mmOverlayAllDialogClose'}).set('html','x').inject(this.dialog);
		this.dialogContainer.setStyles({'display':'block','left':'-10000px'});

		this.dialogHeader = new Element('div', {'id':'mmOverlayAllDialogHeader'}).inject(this.dialog);
		this.dialogBody = new Element('div', {'id':'mmOverlayAllDialogBody'}).inject(this.dialog);		
		this.dialogFooter = new Element('div', {'id':'mmOverlayAllDialogFooter'}).inject(this.dialog);

		this.dialogBody.set('tween', {duration:this.options.dialogContentTween.duration, transition:this.options.dialogContentTween.transition});

		this.dialogContainer.inject(this.element, 'after');
		
		this.confirmDialogContainer = new Element('div', {'id':'mmOverlayAllConfirmDialogContainer'}).setStyle('z-index',(elZ+2));		
		this.confirmDialog = new Element('div', {'id':'mmOverlayAllConfirmDialog'}).inject(this.confirmDialogContainer);		
		this.confirmDialogHeader = new Element('div', {'id':'mmOverlayAllConfirmDialogHeader'}).set('html',mm.lang.confirm_dialog.title).inject(this.confirmDialog);
		this.confirmDialogBody = new Element('div', {'id':'mmOverlayAllConfirmDialogBody'}).inject(this.confirmDialog);				
		this.confirmDialogFooter = new Element('div', {'id':'mmOverlayAllConfirmDialogFooter'}).inject(this.confirmDialog);		
		this.confirmText = new Element('div', {'id':'mmOverlayAllConfirmDialogText'}).inject(this.confirmDialogBody);
		this.confirmBtns = new Element('div', {'class':'mmOverlayAllDialogFooterToolbar'}).inject(this.confirmDialogFooter);
		
//<span class="aBtnIcon" style="background-image: url(/_img/icons/action_21x21ok.png);"></span>
		this.confirmBtnOk = new Element('a', {'class':'dialogactionbutton ', 'href':'#'}).set('html', ' Ja').inject(this.confirmBtns);
//<span class="aBtnIcon" style="background-image: url(/_img/icons/action_21x21close.png);"></span>
		this.confirmBtnCancel = new Element('a', {'class':'dialogactionbutton ', 'href':'#'}).set('html', ' Nee').inject(this.confirmBtns);		
			
		this.staticDialogContents.get('logout_confirm').message = mm.lang.dialog_message.logout_confirm;
		this.staticDialogContents.get('loginpoll_failure').message = mm.lang.dialog_message.loginpoll_failure;		
		this.staticDialogContents.get('loginpoll_expired').message = mm.lang.dialog_message.loginpoll_expired;			
			
		this.confirmDialogContainer.inject(this.element, 'after');	
		this.confirmBtnOk.set('html', '<span class="aBtnIcon" style="background-image: url(/_img/icons/action_21x21ok.png);"></span> Ja');
		this.confirmBtnCancel.set('html', '<span class="aBtnIcon" style="background-image: url(/_img/icons/action_21x21close.png);"></span> Nee');
		this.element.setStyles({'opacity':this.options.overlayOpacity, 'top':'0px','left':'0px','right':'0px','bottom':'0px'}).pin();
	},
	makeElement: function() {
//alert('make'+this.options.defaultId);		
		this.element = new Element('div', {'id':this.options.defaultId}).setStyle('z-index',9000);
		this.element.inject(document.body, 'top');
	},
	setupEvents: function() {
		// tweening stuff
		this.element.set('tween', {duration: this.options.overlayTween.duration, transition:this.options.overlayTween.transition, link:'chain', onComplete:function() { this.tweenOverlayComplete(); }.bind(this) });				
		this.noticeContainer.set('tween', {duration: this.options.noticeTween.duration, transition:this.options.noticeTween.transition, link:'chain', onComplete:function() { this.tweenNoticeComplete(); }.bind(this) });				
		this.dialogContainer.set('tween', {duration: this.options.dialogTween.duration, transition:this.options.dialogTween.transition, link:'chain', onComplete:function() { this.tweenDialogComplete(); }.bind(this) });
		this.confirmDialogContainer.set('tween', {duration: this.options.dialogTween.duration, transition:this.options.dialogTween.transition, link:'chain', onComplete:function() { this.tweenConfirmDialogComplete(); }.bind(this) });				
		this.dialogCloseBtn.addEvent('click', function(e) {
			this.hideDialog(true);
		}.bind(this));		
		this.confirmBtnCancel.addEvent('click', function(e) {
			e.stop();
			this.hideConfirmDialog(true);
		}.bind(this));
		this.bound.repositionDialog = this.repositionDialog.bind(this);		
		this.bound.repositionConfirmDialog = this.repositionConfirmDialog.bind(this);
		this.element.addEvent('click', function(e) { 			
			e.stopPropagation(); 
		});
		this.dialogContainer.addEvent('click', function(e) { 			
			e.stopPropagation(); 
		});		
		window.addEvent('resize', this.bound.repositionDialog);		
		window.addEvent('resize', this.bound.repositionConfirmDialog);				
	},
	repositionDialog: function() {
		if (!this.isDialogOpen) { return false; }
		this.dialogContainer.setStyles({'display':'block'});		
		var overlaySize = this.element.getSize();
		var dSize = this.dialogContainer.getSize();
// dbug.log('repositionDialog :' + JSON.encode(overlaySize)+ ' : '+JSON.encode(dSize));				
		this.dialogContainer.pin().setStyles({'top':((overlaySize.y/2)-(dSize.y/2))+'px','left':((overlaySize.x/2)-(dSize.x/2))+'px'});		
	},
	repositionConfirmDialog: function() {
		if (!this.isConfirmDialogOpen) { return false; }
		this.confirmDialogContainer.setStyles({'display':'block'});		
		var overlaySize = this.element.getSize();
		var dSize = this.confirmDialogContainer.getSize();
//dbug.log('repositionDialog :' + JSON.encode(overlaySize)+ ' : '+JSON.encode(dSize));				
		this.confirmDialogContainer.pin().setStyles({'top':((overlaySize.y/2)-(dSize.y/2))+'px','left':((overlaySize.x/2)-(dSize.x/2))+'px'});		
	},	
	showNotice: function(mtype, notice) {
		if (!$defined(notice)) { notice = ''; }
		this.noticeContainer.setStyles({'display':'none', 'opacity':0});
		this.noticeIcons.each(function(icon) {
			icon.setStyle('display','none');
		},this);		
		switch(mtype) {
			case 'none' : 
			break;
			case 'loading' :
				this.noticeIconLoading.setStyle('display','inline-block');
				this.noticeLoader.cancel();				
				this.noticeLoader.start();
			break; 
		}
		this.noticeText.set('html', notice);	
		this.noticeContainer.setStyles({'display':'block','opacity':0}).unpin();
		this.noticeContainer.pin().setStyles({top:'45%','z-index':90010}).fade(1);			
	},
	updateNotice: function(notice) {
		this.noticeText.set('html', notice);
	},
	hideNotice:function() {
		this.noticeLoader.cancel();		
		this.noticeContainer.setStyles({'display':'none'});
		this.noticeText.set('html', '');
	},
	tweenOverlayComplete:function() {
		var opac = this.element.getStyle('opacity');
		if (opac == 0) {
			this.element.setStyle('display','none');
			//this.isOpen = false;
		} else {
			//this.isOpen = true;
		}
	},
	tweenDialogComplete: function() {
		var opac = this.dialogContainer.getStyle('opacity');
		if (opac == 0) {			
			this.dialogContainer.setStyle('display','none');
			
		} else {
			//this.isDialogOpen = true;
		}
	},
	tweenConfirmDialogComplete: function() {
		var opac = this.confirmDialogContainer.getStyle('opacity');
		if (opac == 0) {			
			this.confirmDialogContainer.setStyle('display','none');
			
		} else {
			//this.isDialogOpen = true;
		}
	},
	tweenNoticeComplete:function() {
		var opac = this.noticeContainer.getStyle('opacity');
		if (opac == 0) {			
			this.noticeText.set('html', '');			
			this.noticeContainer.setStyle('display','none');
			this.noticeLoader.cancel();
		}		
	},
	show: function(immediately) {
		if (!this.isOpen) {
			this.isOpen = true;
			if (!$defined(immediately)) { immediately = false; }
			if (immediately) {
				this.element.setStyles({'display':'block', 'visibility':'visible', 'opacity':this.options.overlayOpacity});
			} else {
				this.element.setStyles({'display':'block','opacity':0}).fade(this.options.overlayOpacity);
				this.noticeContainer.set('tween', {duration: this.options.noticeTween.duration, transition:this.options.noticeTween.transition, link:'chain', onComplete:function() { this.tweenNoticeComplete(); }.bind(this)}).fade(1);			
			}

		}
	},
	hide: function() {
		if (this.isOpen) {
			this.isOpen = false;
			this.noticeContainer.set('tween', {duration: 500, transition:this.options.noticeTween.transition, link:'chain', onComplete:function() { this.tweenNoticeComplete(); }.bind(this) }).fade(0);
			this.element.fade(0);
		}
	},
	displayDialog:function(dialoglink) {
// dbug.log('displayDialog:'+dialoglink);		
	
	},
	setDialogContents: function(mtype) {
// dbug.log('displayDialog:'+mtype);		
	},
	showConfirmDialog:function(confirmLink, confirmText, confirmData, regularLink) {
		this.isConfirmDialogOpen = true;
		if (!this.isOpen) { this.show(); }	
		if (!$defined(confirmText)) { confirmText = ''; }	
		if (!$defined(confirmData)) { confirmData = {}; }
		if (!$defined(regularLink)) { regularLink = false; }
		this.confirmText.set('html', confirmText);
		this.confirmBtnOk.removeEvents('click');
		if (regularLink) {
			this.confirmBtnOk.addEvent('click', function(e) {
				e.stop();
				window.location.href = confirmLink;
			}.bind(this));
		} else {
			this.confirmBtnOk.addEvent('click', function(e) {
				e.stop();
// dbug.log(confirmLink);			
// dbug.log(confirmData);
				var confirmRequest = new Request.JSON({
					method:'post'
					, url: confirmLink
					, data: confirmData
					, onRequest: function() {
						//mm.noticeInfo.show({title:mm.lang.notice_info.saving});
						//this.dialogRequestStart();
						this.showDialogOverlay();
						this.showNotice('loading',mm.lang.dialog_notice.saving );
						this.hideConfirmDialog(false);												
					}.bind(this)
					, onSuccess: function(rJson, rText) {
						if (rJson.success) {
							/*if (rJson.affectedRows) {
								mm.noticeInfo.show({title:affectedRows});
							}*/
							(function() { 
								var hash = '';
								if (window.location.hash != '') { hash = window.location.hash; }
								document.location.reload(true);
							 }).delay(500,mm);				
						
						} else {
							mm.noticeError.show({title:mm.lang.notice_error.save_error});						
							this.hideConfirmDialog(true);
						}
					}.bind(this)
					, onFailure: function() {
						mm.noticeError.show({title:mm.lang.notice_error.save_error});
						this.hideConfirmDialog(true);						
					}.bind(this)
				}).send();
			}.bind(this));	
		}	
		this.confirmDialogContainer.setStyles({'display':'block','opacity':0});				
		this.repositionConfirmDialog();	
		this.confirmDialogContainer.setStyles({'display':'block','opacity':0, 'z-index':90010}).fade(1);			
	},
	showPublicDialog:function(dialogLink) {
		this.clearDialog();
		this.isDialogOpen = true;		
		var dialogDims = this.options.dialogDims.large;		
		if (dialogLink == 'subscribe' || dialogLink == '/subscribe') { dialogDims = this.options.dialogDims.small; }
		this.dialogContainer.setStyles({'width':dialogDims.width,'height':200});		
		var headerHeight = this.dialogHeader.getStyle('height').toInt();
		var footerHeight = this.dialogFooter.getStyle('height').toInt();			
		var bodyHeight = dialogDims.height - headerHeight - footerHeight - this.dialogBody.getStyle('margin-top').toInt() - this.dialogBody.getStyle('margin-bottom').toInt();
		this.dialogBody.setStyle('height', bodyHeight);
		this.dialogOverlayNotice.setStyle('margin-top', ((bodyHeight / 2) +16).toInt());		
		
		if (!this.isOpen) { this.show(); }		
		this.dialogContainer.setStyles({'display':'block','opacity':0});		
		this.dialogExtraOptions = false;
		this.publicDialogRequest(dialogLink);					
		this.dialogContainer.setStyles({'display':'block','opacity':0, 'z-index':90010}); //.fade(1);		
	},
	showStaticDialog: function(dialogType, dialogMessage, checkUnloading) {
		if ($defined(checkUnloading) && checkUnloading) {
			if (mm.main.unloading) {
				return false;
			}
		}
			
		// loginpoll   loginpoll_expired / loginpoll_failure
		this.clearDialog();
		this.isDialogOpen = true;
		var dialogDims = this.options.dialogDims.small;		
		this.dialogContainer.setStyles({'width':dialogDims.width,'height':dialogDims.height});	
		var headerHeight = this.dialogHeader.getStyle('height').toInt();
		var footerHeight = this.dialogFooter.getStyle('height').toInt();			
		var bodyHeight = dialogDims.height - headerHeight - footerHeight - this.dialogBody.getStyle('margin-top').toInt() - this.dialogBody.getStyle('margin-bottom').toInt();
		this.dialogBody.setStyle('height', bodyHeight);
		this.dialogOverlayNotice.setStyle('margin-top', ((bodyHeight / 2) +16).toInt());		
		
		if (!this.isOpen) { this.show(); }		
		this.dialogContainer.setStyles({'display':'block','opacity':0,'z-index':90010});		
		this.dialogExtraOptions = false;
		//this.publicDialogRequest(dialogLink);	
		this.curStaticDialogContents = this.staticDialogContents.get(dialogMessage);
		this.dialogHeader.set('html', mm.lang.dialog_title[dialogMessage]);
		this.dialogFooter.set('html', this.curStaticDialogContents.footer );
		var body = this.curStaticDialogContents.body.substitute({message:this.curStaticDialogContents.message});
		this.dialogBody.empty().set('html', body).setStyle('opacity',1);
//		this.setupTermsDialogFooterButtons();
		this.setupStaticDialogFooterButtons(dialogMessage);
		this.repositionDialog();		
		this.dialogContainer.fade(1);
		this.hideDialogOverlay();
		this.hideNotice();
		if (this.curStaticDialogContents.modal == true) {
			this.dialogCloseBtn.setStyle('display','none');
		} else {
			this.dialogCloseBtn.setStyle('display','block');			
		}		
	},
	showDialog: function(dialoglink, extraOptions) {
		this.clearDialog();
		this.isDialogOpen = true;
		if (dialoglink.charAt(0)=='/') { dialoglink = dialoglink.substr(1,dialoglink.length); }		
		this.dialogLink = dialoglink;
		
		var dialogDims = this.options.dialogDims.small;		
		var splitted = this.dialogLink.split('/');
		if (splitted[0]=='client' || splitted[0]=='help' || splitted[0]=='contract' || splitted[0]=='contract_read') {
			dialogDims = this.options.dialogDims.large;
		} 		
//		this.dialogContainer.setStyles({'width':dialogDims.width,'height':dialogDims.height});
		this.dialogContainer.setStyles({'width':dialogDims.width,'height':200, 'cursor':'default'});		
		var headerHeight = this.dialogHeader.getStyle('height').toInt();
		var footerHeight = this.dialogFooter.getStyle('height').toInt();			
		var bodyHeight = dialogDims.height - headerHeight - footerHeight - this.dialogBody.getStyle('margin-top').toInt() - this.dialogBody.getStyle('margin-bottom').toInt();
		this.dialogBody.setStyle('height', bodyHeight);
		this.dialogOverlayNotice.setStyle('margin-top', ((bodyHeight / 2) +16).toInt());		
		
		if (!this.isOpen) { this.show(); }		
		this.dialogContainer.setStyles({'display':'block','opacity':0, 'z-index':90010});		
//		this.repositionDialog();	
		this.dialogRequest(dialoglink);					
		if ($defined(extraOptions)) {
			this.dialogExtraOptions = extraOptions;
		} else {
			this.dialogExtraOptions = false;
		}
//		if (!$defined(mtype)) { mtype = 'none'; } 
//		this.setDialogContents(mtype);		
		
		//this.dialogContainer.setStyles({'display':'block','opacity':0}).fade(1);
		this.dialogContainer.setStyles({'display':'block','opacity':0}); //.fade(1);
	},
	hideDialog: function(hideOverlay) {
		this.isDialogOpen = false;
		this.dialogContainer.fade(0);
		if ($chk(hideOverlay)) {
			this.hide();
		}
	}
	, hideConfirmDialog:function(hideOverlay) {
		this.isConfirmDialogOpen = false;
		this.confirmDialogContainer.fade(0);
		if ($chk(hideOverlay)) {
			this.hide();
		}		
	}
	, clearDialog:function() {
		this.dialogHeader.set('html', '');
		this.dialogBody.set('html', '');
		this.dialogFooter.set('html', '');		
	}
	, publicDialogRequest:function(dialoglink) {
		if (dialoglink.charAt(0)=='/') { dialoglink = dialoglink.substr(1,dialoglink.length); }	
		var ajaxurl = '/_x/publicdialog/'+dialoglink;		
		new Request.JSON({
			url: ajaxurl
			, method:'post'
			, onSuccess: function(rJson, rText) {
				this.publicDialogRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText]);
			}.bind(this)
			, onRequest: function() {
				this.dialogRequestStart();
			}.bind(this)
			, onFailure: function() {
				this.dialogRequestFailure();
			}.bind(this)					
		}).send();

	}
	, publicDialogRequestSucces: function(rJson, rText) {
		if (rJson.body) {
			this.dialogBody.empty().set('html', rJson.body).setStyle('opacity',1);
			var headerHeight = this.dialogHeader.getStyle('height').toInt();
			var footerHeight = this.dialogFooter.getStyle('height').toInt();			
			this.dialogBody.setStyle('height', 'auto');
			var bodyCntHeight = this.dialogBody.getSize().y + 8;
			this.dialogContainer.setStyle('height', bodyCntHeight + headerHeight + footerHeight + this.dialogBody.getStyle('margin-top').toInt() + this.dialogBody.getStyle('margin-bottom').toInt());			
			this.dialogOverlayNotice.setStyle('margin-top', ((bodyCntHeight / 2) +16).toInt());			
			this.dialogBody.setStyles({'height':bodyCntHeight, 'overflow':'auto'});			
			//mm.ajax.ajaxReady.delay(100, mm.ajax, this.dialogBody);
			this.dialogForm = this.dialogBody.getElement('form.dialogForm');
			if (this.dialogForm) {
				this.setupPublicDialogForm();
			}
		}
		if ($defined(rJson.header)) {			
			this.dialogHeader.set('html', rJson.header);
		}
		if ($defined(rJson.footer)) {
			this.dialogFooter.set('html', rJson.footer);
			this.setupTermsDialogFooterButtons();
		}
		this.repositionDialog();		
		this.dialogContainer.fade(1);
		this.hideDialogOverlay();
		this.hideNotice();
	}
	, setupPublicDialogForm:function() {
		this.dialogForm = this.dialogBody.getElement('form.dialogForm');
		if (this.dialogForm) {
			this.dialogForm.addEvent('submit', function(e) {
				e.stop();
			}.bind(this));	
			this.dialogFormValidator = new FormValidator(this.dialogForm, {
				useTitles:true, evaluateFieldsOnChange:true, evaluateFieldsOnBlur:true, serial:false
				/*
					onFormValidate: $empty(isValid, form, event),
					onElementValidate: $empty(isValid, field, className, warn),
					onElementPass: $empty(field),
					onElementFail: $empty(field, validatorsFailed) */
				, onElementValidate: function(isValid, field, className, warn) {
					if (!isValid) {
						if (field.get('disabled')) {
// dbug.log('disabled element failed validation');
// 							field.removeClass('validation-failed');
						}
					}
				}				
			});
		}		
	}
	, dialogRequest:function(dialoglink) {
		if (dialoglink.charAt(0)=='/') { dialoglink = dialoglink.substr(1,dialoglink.length); }
		var ajaxurl = '/_x/dialog/'+dialoglink;
		new Request.JSON({
			url:ajaxurl
			, method:'post'
			, onSuccess: function(rJson, rText) {
				this.dialogRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText]);
			}.bind(this)
			, onRequest: function() {
				this.dialogRequestStart();
			}.bind(this)
			, onFailure: function() {
				this.dialogRequestFailure();
			}.bind(this)					
		}).send();
	}
	, dialogRequestSucces:function(rJson, rText) {
		if ($defined(rJson.type)) { this.dialogType = rJson.type; } else  {this.dialogType = false; }
		if ($defined(rJson.action)) { this.dialogAction = rJson.action; } else { this.dialogAction = false; }	
		if (rJson.body) {
// dbug.log('this.dialogType = '+this.dialogType);			
// dbug.log('this.dialogAction = '+this.dialogAction);
			//this.dialogBody.empty().set('html', rJson.body).setStyle('opacity',0).fade(1);
			this.dialogBody.empty().set('html', rJson.body).setStyle('opacity',1);
			var headerHeight = this.dialogHeader.getStyle('height').toInt();
			var footerHeight = this.dialogFooter.getStyle('height').toInt();			
//			var bodyHeight = dialogDims.height - headerHeight - footerHeight - this.dialogBody.getStyle('margin-top').toInt() - this.dialogBody.getStyle('margin-bottom').toInt();
			this.dialogBody.setStyle('height', 'auto');
			// this.dialogBody.setStyles({'height':'0px', 'overflow':'auto'});			
			// var coords = this.dialogBody.getScrollSize();
//			var bodyCntHeight = coords.y + 4;			
			var bodyCntHeight = this.dialogBody.getSize().y + 8;
			this.dialogContainer.setStyle('height', bodyCntHeight + headerHeight + footerHeight + this.dialogBody.getStyle('margin-top').toInt() + this.dialogBody.getStyle('margin-bottom').toInt());			
			this.dialogOverlayNotice.setStyle('margin-top', ((bodyCntHeight / 2) +16).toInt());			
			this.dialogBody.setStyles({'height':bodyCntHeight, 'overflow':'auto'});			
//			this.dialogBody.fade(1);
			this.setupDialogForm();						
			mm.ajax.ajaxReady.delay(100, mm.ajax, this.dialogBody);
		}
		if ($defined(rJson.header)) {			
			this.dialogHeader.set('html', rJson.header);
		}
		if ($defined(rJson.footer)) {
			this.dialogFooter.set('html', rJson.footer);
			this.setupDialogFooterButtons();
			var tooltips = this.dialogFooter.getElements('.mmTooltip');
			if (tooltips.length > 0) {
				new mm.Tips(tooltips, {className:'mmTip', text: function(el){ return false; }, showDelay:mm.ajax.options.tooltipDelays.show, hideDelay:mm.ajax.options.tooltipDelays.hide});				
			}			
		}
		this.repositionDialog();		
		this.dialogContainer.fade(1);
		this.hideDialogOverlay();
		this.hideNotice();
	}
	, setupStaticDialogFooterButtons:function(dialogMessage) {
// dbug.log('setupStaticDialogFooterButtons');		
		if (dialogMessage == 'loginpoll_failure') {
			var btn_loginpoll_failure_close = this.dialogFooter.getElement('#btn_loginpoll_failure_close');
			var btn_loginpoll_failure_reconnect = this.dialogFooter.getElement('#btn_loginpoll_failure_reconnect');			
			if (btn_loginpoll_failure_reconnect) {
				btn_loginpoll_failure_reconnect.addEvent('click',function(e) {
					e.stop();
					this.hideDialog(true);
					mm.loginPoll.startPoller.delay(([this.options.overlayTween.duration,this.options.dialogTween.duration].max() + 50).toInt(),mm.loginPoll);					
				}.bind(this));				
			}
			if (btn_loginpoll_failure_close) {
				btn_loginpoll_failure_close.addEvent('click',function(e) {
					e.stop();
					this.hideDialog(false);
					window.location.href = '/logout';
				}.bind(this));
			}
		}
		if (dialogMessage == 'loginpoll_expired') {
			var btn_loginpoll_expired_close = this.dialogFooter.getElement('#btn_loginpoll_expired_close');
			if (btn_loginpoll_expired_close) {
				btn_loginpoll_expired_close.addEvent('click', function(e) {
					e.stop();
					this.hideDialog(false);
					window.location.href = '/login';					
				}.bind(this));
			}
		}		
		if (dialogMessage == 'logout_confirm') {
			
		}		
	}
	, setupTermsDialogFooterButtons:function() {
		var terms_close = this.dialogFooter.getElement('#terms_close');
		if (terms_close) {
			terms_close.addEvent('click', function(e) {
				e.stop();
				this.hideDialog(true);
			}.bind(this));
		}
		var subscribe_submit = this.dialogFooter.getElement('#subscribe_submit');
		if (subscribe_submit) {
			subscribe_submit.addEvent('click', function(e) {
				e.stop();				
				if (this.dialogFormValidator.validate()) {
					var action = this.dialogForm.get('action');					
					var qs = this.dialogForm.toQueryString();				
					var formdata = qs.parseQueryString();
// dbug.log(JSON.encode(formdata));	
// dbug.log('action = '+action);
// dbug.log('qs = '+qs);
					var req = new Request.JSON({
						url:'/_x/subscribelist'
						, method:'post'						
						, link: 'cancel'
						, data:formdata
						, noCache: true
						, onSuccess: function(rJson, rText) {
//dbug.log(rJson);			
							var subscribe_info = this.dialogBody.getElement('#subscribe_info');
							var code = 999;
							if (rJson.Code) { code = rJson.Code.toInt(); }
							if (code != 999) {
								
								/*
								1: Invalid email address
								The email value passed in was invalid.

								100: Invalid API Key
								The API key pass was not valid or has expired.

								101: Invalid ListID
								The ListID value passed in was not valid.

								204: In Suppression List
								Address exists in suppression list. Subscriber is not added.

								205: Is Deleted
								Email Address exists in deleted list. Subscriber is not added.

								206: Is Unsubscribed
								Email Address exists in unsubscribed list. Subscriber is not added.

								207: Is Bounced
								Email Address exists in bounced list. Subscriber is not added.

								208: Is Unconfirmed
								Email Address exists in unconfirmed list. Subscriber is not added.
								*/								
								
								if (code == 0 || code == 208) {
									subscribe_submit.setStyle('display','none');
									var subscribe_success = this.dialogBody.getElement('#subscribe_success');
									var subscribe_notice = this.dialogBody.getElement('#subscribe_notice_'+code);
									if (subscribe_success) { subscribe_success.setStyle('display','block'); }									
									if (subscribe_notice) { subscribe_notice.setStyle('display','block'); }
									if (subscribe_info) { subscribe_info.setStyle('display','none'); }
									this.dialogForm.setStyle('display','none');																		
								} else {																									
									if (subscribe_info) { subscribe_info.setStyle('display','none'); }								
									var subscribe_failure = this.dialogBody.getElement('#subscribe_failure');
									if (subscribe_failure) { subscribe_failure.setStyle('display','block'); }
									var subscribe_notice = this.dialogBody.getElement('#subscribe_notice_'+code);
									if (subscribe_notice) { subscribe_notice.setStyle('display','block'); }									
									this.dialogForm.setStyle('display','none');										
								}
							}
						}.bind(this)
						, onRequest: function() {
							//this.emailAvailableRequestStart();
						}.bind(this)
						, onFailure: function() {
							//this.emailAvailableRequestFailure();
							mm.noticeError.show({title:'fout bij versturen'});							
						}.bind(this)
					}).send();

				} else {
					mm.noticeError.show({title:'geen e-mail adres ingevoerd'});
				}
			}.bind(this));
		}
	}
	, dialogRequestStart: function() {
		this.showDialogOverlay();
		//this.showOverlayNotice();
		this.showNotice('loading',mm.lang.dialog_notice.loading );
	}
	, dialogRequestFailure: function() {
		this.hideDialogOverlay();
		this.hideOverlayNotice();
	}
	, showOverlayNotice:function(notice) {
		if (!$defined(notice)) { notice = mm.lang.dialog_notice.loading; }		
		this.setOverlayNoticeText(notice);		
		this.dialogOverlayNotice.setStyle('display', 'block');
	}
	, hideOverlayNotice:function() {
		this.dialogOverlayNotice.setStyle('display', 'none');
	}	
	, setOverlayNoticeText:function(notice) {
		this.dialogOverlayText.set('html', notice);		
	}
	, showDialogOverlay:function(notice) {
//		if (!$defined(notice)) { notice = mm.lang.dialog_notice.loading; }
		this.dialogCloseBtn.setStyle('display','none');
		this.dialogFooter.setStyle('display','none');		
//		this.setDialogOverlayNoticeText(notice);
		this.dialogOverlay.setStyle('display','block');		
	}
	, setDialogOverlayNoticeText:function(notice) {
		this.dialogOverlayText.set('html', notice);
	}
	, hideDialogOverlay:function() {
		this.dialogCloseBtn.setStyle('display','block');		
		this.dialogFooter.setStyle('display','block');
		this.dialogOverlay.setStyle('display','none');		
	}
	
	, setupDialogForm:function() {
		this.dialogForm = this.dialogBody.getElement('form.dialogForm');
		if (this.dialogForm) {
			this.dialogForm.addEvent('submit', function(e) {
				e.stop();
			}.bind(this));	
			this.dialogFormValidator = new FormValidator(this.dialogForm, {
				useTitles:true, evaluateFieldsOnChange:true, evaluateFieldsOnBlur:true, serial:false
				/*
					onFormValidate: $empty(isValid, form, event),
					onElementValidate: $empty(isValid, field, className, warn),
					onElementPass: $empty(field),
					onElementFail: $empty(field, validatorsFailed) */
				, onElementValidate: function(isValid, field, className, warn) {
					if (!isValid) {
						if (field.get('disabled')) {
// dbug.log('disabled element failed validation');
// 							field.removeClass('validation-failed');
						}
					}
				}				
			});		
			
			if (this.dialogType == 'invoice_save_send') {
				var steps_choices = this.dialogForm.getElements('.step_choices');
				var steps_choice_1 = this.dialogForm.getElements('.step_choice_1');			
				var steps_choice_2 = this.dialogForm.getElements('.step_choice_2');						
				var steps_choice_3 = this.dialogForm.getElements('.step_choice_3');					
				var steps_choice_4 = this.dialogForm.getElements('.step_choice_4');									
				steps_choices.each(function(step_choices) {
					step_choices.setStyle('display','block');
				});
				steps_choice_4.each(function(step_choice_4) {
					step_choice_4.setStyle('display','none');
				});				
				steps_choice_1.each(function(step_choice_1) {
					step_choice_1.setStyle('display','none');
				});			
				steps_choice_2.each(function(step_choice_2) {
					step_choice_2.setStyle('display','none');
				});		
				steps_choice_3.each(function(step_choice_3) {
					step_choice_3.setStyle('display','none');
				});				
				var dialog_recipient_email_1 = this.dialogForm.getElement('#dialog_recipient_email_1');				
				var dialog_recipient_email_2 = this.dialogForm.getElement('#dialog_recipient_email_2');				
				var dialog_recipient_email_3 = this.dialogForm.getElement('#dialog_recipient_email_3');								
				var dialog_send_message_1 = this.dialogForm.getElement('#dialog_send_message_1');					
				var dialog_send_message_2 = this.dialogForm.getElement('#dialog_send_message_2');					
				var dialog_send_message_3 = this.dialogForm.getElement('#dialog_send_message_3');													
				var recipient_email = document.id('recipient_email');
				if (recipient_email && dialog_recipient_email_1 && dialog_recipient_email_2 && dialog_recipient_email_3) {
					dialog_recipient_email_1.set('value', recipient_email.get('value'));
					dialog_recipient_email_2.set('value', recipient_email.get('value'));					
					dialog_recipient_email_3.set('value', recipient_email.get('value'));										
				}
				
				var ch_invoice_save_send_choices = this.dialogForm.getElements('input[type=radio][class~=invoice_save_send_choice]');
				var div_invoice_save_send_choices = this.dialogForm.getElements('div.mmRadio');
				var periodic_options = this.dialogForm.getElement('#periodic_options');
				var concept_options = this.dialogForm.getElement('#concept_options');
				// var dialog_auto_periodic_invoice = this.dialogForm.getElement('#dialog_auto_periodic_invoice');	
				var dialog_auto_invoice = this.dialogForm.getElement('#dialog_auto_invoice');				
				
				ch_invoice_save_send_choices.each(function(ch) {
					ch.addEvent('click', function(e) {
						var choice = ch.get('value').toInt();
						if (ch.get('checked') && (choice == 3 )) {
							//if (choice!=1) { dialog_auto_periodic_invoice.set('checked', false); dialog_auto_invoice.set('checked', false); }							
							//periodic_options.inject(ch.getParent('div'), 'bottom');
							if (choice==3 ) {
								periodic_options.setStyle('display','block');
							} else {
								periodic_options.setStyle('display', 'none');
							}
							this.dialogInvoiceSaveConceptBtn.setStyle('display','none');							
							this.dialogInvoiceSaveSendNextBtn.setStyle('display','inline-block');
						} else {
							periodic_options.setStyle('display','none');							
						}
						if (ch.get('checked') && choice == 1) {
							this.dialogForm.getElement('#estimate_options').setStyle('display', 'block');							
							this.dialogInvoiceSaveConceptBtn.setStyle('display','none');							
							this.dialogInvoiceSaveSendNextBtn.setStyle('display','inline-block');														
						} else {
							this.dialogForm.getElement('#estimate_options').setStyle('display', 'none');														
						}
						if (ch.get('checked') && choice == 2) {
							this.dialogForm.getElement('#invoice_options').setStyle('display', 'block');		
							this.dialogInvoiceSaveConceptBtn.setStyle('display','none');																			
							this.dialogInvoiceSaveSendNextBtn.setStyle('display','inline-block');							
						} else {
							this.dialogForm.getElement('#invoice_options').setStyle('display', 'none');							
						}	
						if (ch.get('checked') && choice == 4) {
							this.dialogForm.getElement('#concept_options').setStyle('display', 'block');
							this.dialogInvoiceSaveSendNextBtn.setStyle('display','none');
							this.dialogInvoiceSaveConceptBtn.setStyle('display','inline-block');
						} else {
							if ($defined(concept_options)) {
								concept_options.setStyle('display', 'none');							
							}
						}																	
					}.bind(this));
				},this);
				div_invoice_save_send_choices.each(function(div) {
					div.addEvent('mouseup', function(e) {						
						ch = div.getElement('input[type=radio]');
						var chvalue = ch.get('value').toInt();
						//if (chvalue!=1) { dialog_auto_periodic_invoice.set('checked', false); dialog_auto_invoice.set('checked', false); }
						if (chvalue == 3) {
							//periodic_options.inject(ch.getParent('div'), 'bottom');
							if (chvalue == 3) { 
								periodic_options.setStyle('display','block'); 
							} else {
								periodic_options.setStyle('display','none'); 
							}
							this.dialogInvoiceSaveConceptBtn.setStyle('display','none');							
							this.dialogInvoiceSaveSendNextBtn.setStyle('display','inline-block');							
						} else {
							periodic_options.setStyle('display','none');							
						}
						if (chvalue == 1) {
							this.dialogForm.getElement('#estimate_options').setStyle('display', 'block');
							this.dialogInvoiceSaveConceptBtn.setStyle('display','none');							
							this.dialogInvoiceSaveSendNextBtn.setStyle('display','inline-block');							
						} else {
							this.dialogForm.getElement('#estimate_options').setStyle('display', 'none');							
						}
						if (chvalue == 2) {
							this.dialogForm.getElement('#invoice_options').setStyle('display', 'block');
							this.dialogInvoiceSaveConceptBtn.setStyle('display','none');							
							this.dialogInvoiceSaveSendNextBtn.setStyle('display','inline-block');														
						} else {
							this.dialogForm.getElement('#invoice_options').setStyle('display', 'none');							
						}			
						var concept_options = this.dialogForm.getElement('#concept_options');						
						if (chvalue == 4) {
							concept_options.setStyle('display', 'block');	
							this.dialogInvoiceSaveSendNextBtn.setStyle('display','none');
							this.dialogInvoiceSaveConceptBtn.setStyle('display','inline-block');													
						} else {
							if ($defined(concept_options)) {
								concept_options.setStyle('display','none');
							}
						}

					}.bind(this));
				},this);	
				
				// var dialog_auto_periodic_invoice = this.dialogForm.getElement('#dialog_auto_periodic_invoice');
				if (dialog_auto_invoice) {
					// dialog_auto_periodic_invoice.addEvent('click', function(e) {
					// 	if (dialog_auto_periodic_invoice.get('checked')) {
					// 		periodic_options.setStyle('display','block');	
					// 		dialog_auto_invoice.set('checked', false);						
					// 	} else {
					// 		periodic_options.setStyle('display','none');							
					// 	}
					// });
					dialog_auto_invoice.addEvent('click', function(e) {
						if (dialog_auto_invoice.get('checked')) {
							//dialog_auto_periodic_invoice.set('checked', false);
							periodic_options.setStyle('display','none');														
						} 
					});
				}
				
				
				var dialog_invoice_save_endless = this.dialogForm.getElement('#dialog_invoice_save_endless');
				var dialog_invoice_save_times = this.dialogForm.getElement('#dialog_invoice_save_times');
				var dialog_invoice_save_times_display = this.dialogForm.getElement('#dialog_invoice_save_times_display');				
				dialog_invoice_save_times_display.addEvents({
					'keyup': function(e) {
						var v = dialog_invoice_save_times_display.get('value');
						if (isNaN(v)) { v = 0; } 
						dialog_invoice_save_times.set('value', v);
					}
					,'blur' : function(e) {
						var v = dialog_invoice_save_times_display.get('value');
						if (isNaN(v)) { v = 0; } 
						dialog_invoice_save_times.set('value', v);						
					}
				});
				if (dialog_invoice_save_endless) {
					dialog_invoice_save_endless.addEvent('click', function(e) {
						if (dialog_invoice_save_endless.get('checked')) {
							dialog_invoice_save_times.set('value', -1);
							dialog_invoice_save_times_display.removeClass('focused').addClass('disabled').set('disabled', true);							
						} else {
							dialog_invoice_save_times.set('value', dialog_invoice_save_times_display.get('value').toInt());
							dialog_invoice_save_times_display.removeClass('focused').removeClass('disabled').set('disabled', false);
						}
					});
				}
				
				var dialog_date_start = this.dialogForm.getElement('#dialog_date_start');
				var dialog_repeat = this.dialogForm.getElement('#dialog_repeat');
				if (dialog_repeat && dialog_date_start ) {
					dialog_repeat.addEvent('change', function(e) {
						var datepicker = dialog_date_start.retrieve('datepicker_object');
						var period = dialog_repeat.get('value');
						//dialog_date_start.focus();
						var today = new Date();
						//var yesterday = today.clone().decrement(); 	
						var newDate = today.clone();					

						switch(period) {
							case 'weekly' :
								newDate.decrement('week').increment('day');
							break;
							case 'monthly' :
								newDate.decrement('month').increment('day');
							break;		
							case 'quarterly' :
								newDate.decrement('month',3).increment('day');
							break;		
							case 'halfyearly' :
								newDate.decrement('month',6).increment('day');							
							break;			
							case 'yearly' :
								newDate.decrement('year').increment('day');							
							break;																					
						}
// dbug.log('newDate = ');						
// dbug.log(newDate);	
// dbug.log('new timestamp = '+(newDate.getTime()/1000).toInt());		
						var newMinDate = { date:''+(newDate.getTime()/1000).toInt()+'', format:'U' }; 			
// dbug.log('last mindate = '+datepicker.options.minDate);									
						datepicker.options.minDate = datepicker.unformat(newMinDate.date, newMinDate.format);			
// dbug.log('new mindate = '+datepicker.options.minDate);									
// dbug.log('cur date = '+new Date(datepicker.unformat(dialog_date_start.get('value'), 'U')));

						var minTimestamp = (datepicker.options.minDate.getTime()/1000).toInt();
						var curTimestamp = dialog_date_start.get('value');
						var tooSmall = false;
						if (curTimestamp < minTimestamp) {
// dbug.log(datepicker.d);							
							tooSmall = true;
							curTimestamp = minTimestamp;
							dialog_date_start.set('value', curTimestamp);
							datepicker.d = new Date(datepicker.unformat(''+minTimestamp+'', 'U'));
// dbug.log(datepicker.d);														
							datepicker.visual.set('value', datepicker.format(datepicker.d, datepicker.options.format));							
						}
// dbug.log('min timestamp = '+minTimestamp +' cur timestamp = '+curTimestamp+ ' tooSmall = '+tooSmall);
					});
				}
				
				
				var dialog_send_now_1 = this.dialogForm.getElement('#dialog_send_now_1');
				var dialog_send_now_2 = this.dialogForm.getElement('#dialog_send_now_2');
				var dialog_send_now_3 = this.dialogForm.getElement('#dialog_send_now_3');								
				[dialog_send_now_1, dialog_send_now_2, dialog_send_now_3].each(function(ch) {
					var chid = ch.get('id');
					var idsplit = chid.split('_');
					var num = idsplit.getLast();
// dbug.log('clicked on checkbox num:'+num);					
					ch.addEvent('click', function(e) {
						var rmail = this.dialogForm.getElement('#dialog_recipient_email_'+num);
						var rmsg = this.dialogForm.getElement('#dialog_send_message_'+num);
						var labels = this.dialogForm.getElements('div.step_choice_'+num+' label');
						// var cc = this.dialogForm.getElement('#dialog_cc_me_'+num);
						if (ch.get('checked')) {
							rmail.removeClass('focused').removeClass('disabled').set('disabled', false);
							// cc.removeClass('disabled').set('disabled', false);
							rmsg.removeClass('focused').removeClass('disabled').set('disabled', false);							
							labels.removeClass('disabled');
							if (!$chk(rmail.get('value'))) {
								rmail.addClass('validation-failed');
							}							
						} else {
							rmail.removeClass('focused').addClass('disabled').set('disabled', true);
							rmsg.removeClass('focused').addClass('disabled').set('disabled', true);							
							labels.addClass('disabled');							
							// cc.addClass('disabled').set('disabled', true);
							if (!$chk(rmail.get('value'))) {
								rmail.removeClass('validation-failed');
							}							
						}
					}.bind(this));
				},this);

				/*
				var dialog_upload_attachment_link = this.dialogForm.getElement('#dialog_upload_attachment_link');
				if (dialog_upload_attachment_link) {
					this.setupEstimateAttachmentUploadLink(dialog_upload_attachment_link);
				}
				*/
				
				this.setupAttachmentUploadLink('estimate');
				this.setupAttachmentUploadLink('invoice');
			} // end save_send dialog
			
			
			if (this.dialogType == 'invoice_send') {
				var dialog_invoice_id = this.dialogForm.getElement('#dialog_invoice_id');
				var invoice_id = document.id('invoice_id');
				if (invoice_id && dialog_invoice_id) {
					dialog_invoice_id.set('value', invoice_id.get('value'));
				}
				var dialog_recipient_email = this.dialogForm.getElement('#dialog_recipient_email');
				var recipient_email = document.id('recipient_email');
				if (recipient_email && dialog_recipient_email) {
					dialog_recipient_email.set('value', recipient_email.get('value'));
				}
				this.setupAttachmentUploadLink('invoice');				
			}
			
			
			if (this.dialogType == 'invoicenum') {
				var invoice_nr_prefix = this.dialogForm.getElement('#dialog_invoice_nr_prefix');
				var invoice_nr_count = this.dialogForm.getElement('#dialog_invoice_nr_count');
				var invoice_nr_preview = this.dialogForm.getElement('#dialog_invoice_nr_preview');				
				if (invoice_nr_prefix && invoice_nr_count && invoice_nr_preview) {
					invoice_nr_prefix.addEvents({
						'keyup': this.settingsInvoiceNrPreview.bind(this, invoice_nr_prefix)
						, 'blur': this.settingsInvoiceNrPreview.bind(this, [invoice_nr_prefix,true])
					});
					invoice_nr_count.addEvents({
						'keyup': this.settingsInvoiceNrPreview.bind(this, invoice_nr_count)
						, 'blur': this.settingsInvoiceNrPreview.bind(this, [invoice_nr_count,true])
					});			
				}				
			}
			
		
			if (this.dialogType == 'client') {
				var client_country = this.dialogForm.getElement('#client_country');
				var client_details_nl = this.dialogForm.getElement('#client_details_nl');
				var client_details_int = this.dialogForm.getElement('#client_details_int');				
				if (client_country && client_details_nl && client_details_int) {
					client_country.addEvent('change', function(e) {
						var code = client_country.get('value');
						if (code == 'NL') {
							client_details_nl.setStyle('display','block');
							client_details_int.setStyle('display','none');														
						} else {
							client_details_nl.setStyle('display','none');
							client_details_int.setStyle('display','block');
						}
					});
				}
				var client_postal_num_nl = this.dialogForm.getElement('#client_postal_num_nl');				
				var client_postal_alpha_nl = this.dialogForm.getElement('#client_postal_alpha_nl');				
				if (client_postal_num_nl && client_postal_alpha_nl) {
					client_postal_num_nl.addEvent('keyup', function(e) {
						if (client_postal_num_nl.get('value').length == 4) {
							//if (this.dialogFormValidator.test('minLength',client_postal_num_nl) && this.dialogFormValidator.test('maxLength',client_postal_num_nl) && this.dialogFormValidator.test('validate-integer',client_postal_num_nl)) {
								client_postal_alpha_nl.focus();
							//}
						}
					}.bind(this));
					client_postal_alpha_nl.addEvent('keyup', function(e) {
						if (client_postal_alpha_nl.get('value').length == 2) {
							//if (this.dialogFormValidator.test('minLength',client_postal_num_nl) && this.dialogFormValidator.test('maxLength',client_postal_num_nl) && this.dialogFormValidator.test('validate-integer',client_postal_num_nl)) {
								var client_city_nl = this.dialogForm.getElement('#client_city_nl');
								if (client_city_nl) {
									client_city_nl.focus();
								}
							//}
						}
					}.bind(this));
				}
				var client_name_company = this.dialogForm.getElement('#client_name_company');
				var hidden_client_id = this.dialogForm.getElement('#client_id');
				var client_id = false;
				if (hidden_client_id && $chk(hidden_client_id.get('value'))) {
					client_id = hidden_client_id.get('value').toInt();
				}
				if (client_name_company) {
					client_name_company.addEvents({
						'blur':function(e) {
							var ctitle = client_name_company.get('value');	
							if ($chk(ctitle)) {
								this.checkClientAvailable(client_name_company, client_id);
							}
						}.bind(this)								
					});
				}
				
			}
			
			if (this.dialogType == 'payment') {
				var payment_amount = this.dialogForm.getElement('#payment_amount');
				var payment_amount_display = this.dialogForm.getElement('#payment_amount_display');
				var payment_left_display = this.dialogForm.getElement('#payment_left_display');
				var payment_not_paid = this.dialogForm.getElement('#payment_not_paid');
				var not_paid = 0;
				if (payment_not_paid) { 
					not_paid = payment_not_paid.get('value').toFloat();
				}
				if (payment_amount && payment_amount_display && payment_left_display) {
					payment_amount.addEvents({
						'keyup': function(e) {
							var amount_raw = payment_amount.get('value');
							var amount = amount_raw.replace(/\,/g, '.');
							amount = amount.toFloat();
							if (isNaN(amount)) { amount = 0; }
							var left = (not_paid - amount).toFloat();
							payment_amount_display.set('html', '&euro; &nbsp; '+amount.numberFormat(2,',',''));
							payment_left_display.set('html', '&euro; &nbsp; '+left.numberFormat(2, ',','')); 
							if (left == 0) {
								payment_left_display.removeClass('paymentDisplayNotFull').addClass('paymentDisplayFull');
							} else {
								payment_left_display.removeClass('paymentDisplayFull').addClass('paymentDisplayNotFull');
							}
						}
					});					
				}
				var payment_send_notification = this.dialogForm.getElement('#payment_send_notification');
				var payment_notify_email = this.dialogForm.getElement('#payment_notify_email');
				var payment_notify_message = this.dialogForm.getElement('#payment_notify_message');				
				var label_notify_email = this.dialogForm.getElement('#label_notify_email');
				var label_notify_message = this.dialogForm.getElement('#label_notify_message');				
				if (payment_send_notification && payment_notify_email && payment_notify_message) {
					payment_send_notification.addEvent('click', function(e) {
						var checked = payment_send_notification.get('checked');
						if (checked) {
							payment_notify_email.set('disabled', false).removeClass('disabled');
							payment_notify_message.set('disabled', false).removeClass('disabled');	
							label_notify_email.removeClass('disabled');
							label_notify_message.removeClass('disabled');							
						} else {
							payment_notify_email.set('disabled', true).addClass('disabled').removeClass('focused');	
							payment_notify_message.set('disabled', true).addClass('disabled').removeClass('focused');														
							label_notify_email.addClass('disabled');
							label_notify_message.addClass('disabled');							
						}
					});
				}	
			}
				
			if (this.dialogType == 'periodic') {
				var periodic_times_min = this.dialogForm.getElement('#periodic_times_min');				
				var periodic_times_display = this.dialogForm.getElement('#periodic_times_display');
				var periodic_times = this.dialogForm.getElement('#periodic_times');
				if (periodic_times_display && periodic_times_min) {
					periodic_times_display.addEvents({
						'keyup':function(e) {
							var value = periodic_times_display.get('value');
							var min = periodic_times_min.get('value');
							if (isNaN(value)) {
								periodic_times_display.set('value',0);
							}
							
						}
						, 'blur': function(e) {
							var value = periodic_times_display.get('value');
							if (isNaN(value)) {
								periodic_times_display.set('value',0);
							}							
							var min = periodic_times_min.get('value').toInt();
							if (value.toInt() < min) {
								periodic_times_display.set('value',min);
							}							
							periodic_times.set('value',periodic_times_display.get('value').toInt());
						}
					});
				}
			}	
			
			if (this.dialogType == 'product') {
				
				var product_account_nr_defaults = this.dialogForm.getElement('#product_account_nr_defaults');
				var accounting_nr = this.dialogForm.getElement('#accounting_nr');
				var accounting_nr_title = this.dialogForm.getElement('#accounting_nr_title');	
				
				if (product_account_nr_defaults && accounting_nr && accounting_nr_title) {
					product_account_nr_defaults.addEvent('change', function(e) {
						var value = product_account_nr_defaults.get('value');
						if (value != '') {
							var splitted = value.split('____');
							if ($defined(splitted[0]) && $defined(splitted[1])) {
								accounting_nr.set('value', splitted[0]);
								accounting_nr_title.set('value', splitted[1]);
							}
						} else {
							accounting_nr.set('value', '');
							accounting_nr_title.set('value', '');							
						}
					});					
				}
				
				var product_title = this.dialogForm.getElement('#product_title');
				var hidden_product_id = this.dialogForm.getElement('#product_id');
				var product_id = false;
				if (hidden_product_id && $chk(hidden_product_id.get('value'))) {
					product_id = hidden_product_id.get('value').toInt();
				}
				if (product_title) {
					product_title.addEvents({
						'blur':function(e) {
							var ptitle = product_title.get('value');
							if ($chk(ptitle)) {
								this.checkProductAvailable(product_title, product_id);
							}							
						}.bind(this) 
					});
				}
				
			}
			
			if (this.dialogType == 'purchasecategory') {
				var purchasecategory_account_nr_defaults = this.dialogForm.getElement('#purchasecategory_account_nr_defaults');
				var accounting_nr = this.dialogForm.getElement('#accounting_nr');
				var accounting_nr_title = this.dialogForm.getElement('#accounting_nr_title');
				if (purchasecategory_account_nr_defaults && accounting_nr && accounting_nr_title) {
					purchasecategory_account_nr_defaults.addEvent('change', function(e) {
						var value = purchasecategory_account_nr_defaults.get('value');
						if (value != '') {
							var splitted = value.split('____');
							if ($defined(splitted[0]) && $defined(splitted[1])) {
								accounting_nr.set('value', splitted[0]);
								accounting_nr_title.set('value', splitted[1]);
							}
						} else {
							accounting_nr.set('value', '');
							accounting_nr_title.set('value', '');							
						}
					});					
				}								
			}
				
			if (this.dialogType == 'usersecrets_edit') {
				this.setupUserSecretsDialog();
			}
			if (this.dialogType == 'reset_edit') {
				this.setupResetDialog();
			}
			if (this.dialogType == 'quit_edit') {
				this.setupQuitDialog();
			}	
			

		} // end if form
				
	}
	, setupQuitDialog:function() {
		var quit_extra = this.dialogForm.getElement('#quit_extra');
		var chQuit = this.dialogForm.getElement('#dialog_quit');
		var quit_comment = this.dialogForm.getElement('#quit_comment');
		chQuit.addEvent('click', function(e) {
			if (chQuit.get('checked')) {
				quit_extra.setStyle('display','block');
			} else {
				quit_extra.setStyle('display','none');
			}
		}.bind(this));
		new OverText(quit_comment, {});
		quit_extra.setStyle('display','none');
	}
	, setupResetDialog:function() {
		var purge_extra = this.dialogForm.getElement('#purge_extra');
		if (purge_extra) {
			purge_extra.setStyle('opacity', 0.1);			
		}
		var chPurge = this.dialogForm.getElement('#dialog_purge');

			if (chPurge && purge_extra) {
				chPurge.addEvent('click', function(e) {
					if (chPurge.get('checked')) {				
						purge_extra.setStyle('opacity', 1);
					} else {
						purge_extra.setStyle('opacity', 0.1);
					}
				}.bind(this));			
			}

		/*
		var dialog_purge_invoices = this.dialogForm.getElement('#dialog_purge_invoices');
		var dialog_purge_purchases = this.dialogForm.getElement('#dialog_purge_purchases');		
		var dialog_purge_products = this.dialogForm.getElement('#dialog_purge_products');		
		var dialog_purge_purchasecategories = this.dialogForm.getElement('#dialog_purge_purchasecategories');		
		var dialog_purge_clients = this.dialogForm.getElement('#dialog_purge_clients');		
		
		if (chPurge) {
			chPurge.addEvent('click', function(e) {
				if (chPurge.get('checked')) {				

//					purge_extra.setStyle('display','block');	

				} else {
					dialog_purge_invoices.set('checked', false);
					dialog_purge_purchases.set('checked', false);
					dialog_purge_products.set('disabled', true).set('checked', false);
					dialog_purge_purchasecategories.set('disabled', true).set('checked', false);
					dialog_purge_clients.set('disabled', true).set('checked', false);					
				}
			}.bind(this));			
		}

		
		dialog_purge_invoices.addEvent('click', function(e) {
			if (dialog_purge_invoices.get('checked') && dialog_purge_purchases.get('checked')) {
				dialog_purge_products.set('disabled', false);
				dialog_purge_purchasecategories.set('disabled', false);
				dialog_purge_clients.set('disabled', false);								
			} else {
				dialog_purge_products.set('disabled', true).set('checked', false);
				dialog_purge_purchasecategories.set('disabled', true).set('checked', false);
				dialog_purge_clients.set('disabled', true).set('checked', false);				
			}
		}.bind(this));
		
		dialog_purge_purchases.addEvent('click', function(e) {
			if (dialog_purge_invoices.get('checked') && dialog_purge_purchases.get('checked')) {
				dialog_purge_products.set('disabled', false);
				dialog_purge_purchasecategories.set('disabled', false);
				dialog_purge_clients.set('disabled', false);								
			} else {
				dialog_purge_products.set('disabled', true).set('checked', false);
				dialog_purge_purchasecategories.set('disabled', true).set('checked', false);
				dialog_purge_clients.set('disabled', true).set('checked', false);				
			}
		}.bind(this));	
		*/	
		
							
	}
	, setupUserSecretsDialog:function() {
		this.usersecretEmail = this.dialogForm.getElement('#dialog_email');
		this.usersecretEmail.store('org_email', this.usersecretEmail.get('value'));
		this.usersecretEmail.store('validators', [FormValidator.getValidator('validate-email'), FormValidator.getValidator('required')]);		
		// this.usersecretBankAccountNr = this.dialogForm.getElement('#dialog_bank_account_nr');
		// this.usersecretBankAccountNr.store('isValid',true);
		// this.usersecretBankAccountHolder = this.dialogForm.getElement('#dialog_bank_account_holder');	
		// this.usersecretBankAccountHolder.store('validators', [FormValidator.getValidator('minLength'), FormValidator.getValidator('required')]);				
		// this.usersecretBankAccountTypes = this.dialogForm.getElements('input[type=radio][class~=dialog_bank_account_type]');
		var newpassword_check = this.dialogForm.getElement('#dialog_create_newpassword');
		var dialog_newpassword_strength = this.dialogForm.getElement('#dialog_newpassword_strength');		
		var newpassword = this.dialogForm.getElement('#dialog_newpassword');				
		var pwStrength = new mm.PasswordstrengthClass({container:this.dialogForm.getElement('#dialog_password_strength'), inputElement:newpassword});
		var pwMask = new mm.PasswordmaskClass({inputElement:newpassword});					

		newpassword_check.addEvent('click', function(e) {
			var checked = newpassword_check.get('checked');
			if (checked) {
				dialog_newpassword_strength.setStyle('display','block');
			} else {
				dialog_newpassword_strength.setStyle('display','none');				
			}
		});

		this.emailAvailableRequest = new Request.JSON({
			url: '/_x/emailavailable'
			, method: 'post'
			, link: 'cancel'
			, noCache: true
			, onSuccess: function(rJson, rText) {
				//this.emailAvailableRequestSucces(rJson, rText);	//(rJson, rText);
					if (rJson.available) {
						//this.signupEmail.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px -24px'});
						this.usersecretEmail.store('emailAvailable', true).removeClass('validation-failed');									
					} else {
						// this.signupEmail.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'});			
						this.usersecretEmail.store('emailAvailable', false).addClass('validation-failed');
						//this.signupEmail.addClass('validation-failed');		
					}					
			}.bind(this)
			, onRequest: function() {
				//this.emailAvailableRequestStart();
			}.bind(this)
			, onFailure: function() {
				//this.emailAvailableRequestFailure();
			}.bind(this)
		});			
		$clear(this.emailAvailableTimer);
		this.emailAvailableTimer = this.checkEmailAvailable.delay(500,this, this.usersecretEmail);
				
		this.usersecretEmail.addEvents({
			keydown: function(e) {
				
			}.bind(this)
			, keyup: this.validateField.bind(this, this.usersecretEmail)			
			, blur: this.validateField.bind(this, this.usersecretEmail)

		});		
		this.usersecretEmail.addEvents({
			'keyup': this.checkEmailAvailable.bind(this, this.usersecretEmail)
			, 'blur': this.checkEmailAvailable.bind(this, this.usersecretEmail)			
		});
		this.usersecretEmail.store('isValid', true);
		// this.usersecretBankAccountTypes.each(function(btype) {
		// 	btype.addEvent('click', function(e) { 
		// 		this.checkBankAccountNr();
		// 	}.bind(this));
		// 	
		// },this);
		// 
		// this.usersecretBankAccountNr.addEvents({
		// 	 'keyup': this.checkBankAccountNr.bind(this)
		// 	, 'blur': this.checkBankAccountNr.bind(this)
		// });		
		// this.usersecretBankAccountHolder.addEvents({
		// 	'keyup': this.validateField.bind(this, this.usersecretBankAccountHolder)
		// 	, 'blur': this.validateField.bind(this, this.usersecretBankAccountHolder)
		// });
	}
	, checkEmailAvailable:function(emailfield) {		
		if (emailfield.retrieve('isValid', false)) { 
			if (emailfield.get('value') != emailfield.retrieve('org_email') ) {
				this.emailAvailableRequest.cancel();
				this.emailAvailableRequest.send('checkemail='+emailfield.get('value')+'&docheckemail='+1);			
			} else {
				this.emailAvailableRequest.cancel();
				emailfield.store('emailAvailable', true).removeClass('validation-failed');				
			}
		} 
	}
	, checkProductAvailable:function(field, product_id) {
		if (!$defined(product_id)) {
			product_id = false;
		}
		var ptitle = field.get('value');
		new Request.JSON({
			url: '/_x/productavailable'
			, data: {'account_id':mm.runtime.context.accountId,'title':ptitle,'product_id':product_id}
			, method: 'post'
			, async: false			
			, link: 'cancel'
			, noCache: true
			, onSuccess: function(rJson, rText) {
				if (rJson.available) {
					field.store('productAvailable', true).removeClass.delay(200, field, 'validation-failed');									
				} else {
					field.store('productAvailable', false).addClass.delay(200, field, 'validation-failed');
mm.noticeError.show({'title':'product titel bestaat al'});										
				}					
			}.bind(this)
			, onRequest: function() {

			}.bind(this)
			, onFailure: function() {
mm.noticeError.show({'title':'fout bij check product titel'});
			}.bind(this)
		}).send();
		
	}
	, checkClientAvailable:function(field, client_id) {
		if (!$defined(client_id)) {
			client_id = false;
		}
		var ctitle = field.get('value');
		new Request.JSON({			
			url: '/_x/clientavailable'
			, data: {'account_id':mm.runtime.context.accountId,'title':ctitle,'client_id':client_id}
			, method: 'post'
			, link: 'cancel'
			, async: false
			, noCache: true
			, onSuccess: function(rJson, rText) {
				if (rJson.available) {
					field.store('clientAvailable', true).removeClass.delay(200, field, 'validation-failed');									
				} else {
					field.store('clientAvailable', false).addClass.delay(200, field, 'validation-failed');
mm.noticeError.show({'title':'contact naam bestaat al'});										
				}					
			}.bind(this)
			, onRequest: function() {

			}.bind(this)
			, onFailure: function() {
mm.noticeError.show({'title':'fout bij check contact naam'});
			}.bind(this)
		}).send();
		
	}
	, validateField:function(el) {
//dbug.log('validateField el='+el.get('id'));		
		var validators = el.retrieve('validators');
		var valid = true;
		if (validators) {
			validators.each(function(validator) {								
				if (!validator.test(el)) { valid = false; }
// dbug.log('validator:'+validator.className+' = '+validator.test(el));
			} );
		}
		if (valid) {			
			// el.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px -24px'});
			// el.retrieve('errorIcon').retrieve('mmTip').hide();
			if (el == this.usersecretEmail) { this.usersecretEmail.store('isValid', true); }
			el.removeClass('validation-failed');			
		} else {
			// el.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'});
			if (el == this.usersecretEmail) { this.usersecretEmail.store('isValid', false); }			
			el.addClass('validation-failed');
		}
		return valid;
	}
	, checkBankAccountNr:function() {
		var value = 0;
		this.usersecretBankAccountTypes.each(function(btype, index) {
// dbug.log('radio	index='+index+' checked = '+btype.get('checked')+' value = '+btype.get('value'));		
			if (btype.get('checked')) {
				value = btype.get('value').toInt();
			}
		},this);
		var giro = false;
		if (value === 2) {
			// giro
			giro = true;
		} 
		var num = this.usersecretBankAccountNr.get('value');
		var valid = mm.main.validateAccountNumber(num, giro);
		if (valid) {
			this.usersecretBankAccountNr.store('isValid',true).removeClass('validation-failed');
//			this.usersecretBankAccountNr.retrieve('errorIcon').setStyles({'display':'block', 'background-position':'0px -24px'});
		} else {
			this.usersecretBankAccountNr.store('isValid',false).addClass('validation-failed');			
//			this.usersecretBankAccountNr.retrieve('errorIcon').setStyles({'display':'block', 'background-position':'0px 0px'});			
		}
// dbug.log('checkBankAccountNr giro='+giro+' num='+num+' valid='+valid);		
	}
	, setupAttachmentUploadLink:function(type) {
		if ($defined(type) && $chk(type)) {
			var dialog_upload_attachment_link = this.dialogForm.getElement('#dialog_upload_attachment_link_'+type);
			var progressBar = this.dialogForm.getElement('#dialog_upload_attachment_link_progress_'+type);
			var attachment_extra_display = this.dialogForm.getElement('#attachment_extra_display_'+type);			
			var dialog_send_attachment_extra = this.dialogForm.getElement('#dialog_send_attachment_extra_'+type);
			var dialog_attachment_extra = this.dialogForm.getElement('#dialog_attachment_extra_'+type);
dbug.log('DIALOG ATT EXTRE = '+dialog_attachment_extra);
			var loader = this.dialogForm.getElement('#dialog_upload_attachment_link_loader_'+type);			
			var flashurl = '/uploadestimateattachment';	
			var extraData = {
				'uploadtype':'tmp'
				, 'username':mm.runtime.auth.username
			};					
			
									var swf = new Swiff.Uploader({
										path: '/_img/plugins/fancyupload/Swiff.Uploader.swf',
										//url: 'https://wmadmin:k4n44lw3g@vic.moneymedic.eu/uploadsingle',
										url: flashurl,
										data: extraData,
										zIndex: 101000,
										verbose: true,
										queued: false,
										multiple: false,
										target: dialog_upload_attachment_link,
										instantStart: true,
										typeFilter: {
											'Bestanden (*.jpg, *.jpeg, *.gif, *.png, *.pdf, *.doc, *.txt, *.docx, *.xls, *.xlsx)': '*.jpg; *.jpeg; *.gif; *.png; *.pdf; *.doc; *.txt; *.docx, *.xls, *.xlsx'
										},
										fileSizeMax: 2 * 1024 * 1024,
										onBeforeStart: function() {
			// dbug.log('onBeforeStart');								
											loader.setStyle('display', 'block');
										},
										onBeforeStop: function() {
			// dbug.log('onBeforeStop');																
										},							
										onSelectSuccess: function(files) {
											if (Browser.Platform.linux) window.alert('Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nSince you are prepared now, the upload will start right away ...');
					// dbug.log('Starting Upload', 'Uploading <em>' + files[0].name + '</em> (' + Swiff.Uploader.formatUnit(files[0].size, 'b') + ')');
											this.setEnabled(false);
										},
										onSelectFail: function(files) {
			alert('' + files[0].name + ' is te groot. Selecteer een bestand kleiner dan 2 Mb. (Error: #' + files[0].validationError + ')');
										},
										appendCookieData: true,
										onQueue: function() {
											if (!swf.uploading) return;
											var size = Swiff.Uploader.formatUnit(swf.size, 'b');
											if (progressBar) {
												progressBar.set('html', '<span class="small">' + swf.percentLoaded + '% / ' + size + '</span>');
											}
											//link.set('html', );						
										},
										onFileComplete: function(file) {

					// dbug.log('filecomplete: response = ');
					// dbug.log(JSON.decode(file.response.text));						
											if (file.response.error) {
			alert('Uploading ' + this.fileList[0].name + ' failed, please try again. (Error: #' + this.fileList[0].response.code + ' ' + this.fileList[0].response.error + ')');
											} else {
												//var md5 = JSON.decode(file.response.text, true).hash; // secure decode

												//log.alert('Successful Upload', 'an MD5 hash was created from <em>' + this.fileList[0].name + '</em>: <code>' + md5 + '</code>.<br />gravatar.com generated a fancy and unique monsterid for it, since we did not save the image.');

												//var img = $('demo-portrait');
												//img.setStyle('background-image', img.getStyle('background-image').replace(/\w{32}/, md5));
												//img.highlight();
					// dbug.log('upload succes');							
												rJson = JSON.decode(file.response.text);
											}
											var finalfilename = false;
											if ($defined(rJson.uploadtype) && $defined(rJson.filename)) {
												finalfilename = rJson.uploadtype+'/'+rJson.filename;
											}
											if (dialog_attachment_extra && finalfilename) {
												dialog_attachment_extra.set('value',finalfilename );
											}
											if (progressBar && finalfilename) {
												//var finalfilelink = '<a href="/_f/'+mm.runtime.auth.username+'/'+finalfilename+'">'+rJson.filename+'</a>';
												//progressBar.set('html', finalfilelink);
												dialog_send_attachment_extra.set('checked', true).setStyle('display','inline-block');
												var displayName = rJson.filename.substr(rJson.filename.indexOf('_')+1);
												attachment_extra_display.set('html', displayName).setStyle('display','inline-block');
												progressBar.set('html', '');
											}						
											file.remove();
											this.setEnabled(true);
										},
										onComplete: function() {
											//link.set('html', 'klik again');
			// dbug.log('HIDDEN VALUE = '+dialog_attachment_extra.get('value'));								
											loader.setStyle('display', 'none');
										}
									});

									// Button state
									dialog_upload_attachment_link.addEvents({
										click: function() {
											return false;
										},
										mouseenter: function() {
											this.addClass('hover');
											swf.reposition();
										},
										mouseleave: function() {
											this.removeClass('hover');
											this.blur();
										},
										mousedown: function() {
											this.focus();
										}
									});
			
			
		}
	}
	, setupEstimateAttachmentUploadLink:function(dialog_upload_attachment_link) {
// dbug.log('setupEstimateAttachmentUploadLink:'+dialog_upload_attachment_link.get('id') );		
		var progressBar = this.dialogForm.getElement('#dialog_upload_attachment_link_progress');
		var attachment_extra_display = this.dialogForm.getElement('#attachment_extra_display');
		var dialog_send_attachment_extra = this.dialogForm.getElement('#dialog_send_attachment_extra');
		var dialog_attachment_extra = this.dialogForm.getElement('#dialog_attachment_extra');
		var loader = this.dialogForm.getElement('#dialog_upload_attachment_link_loader');
		var flashurl = '/uploadestimateattachment';
		var extraData = {
			'uploadtype':'tmp'
			, 'username':mm.runtime.auth.username
		};
		
						var swf = new Swiff.Uploader({
							path: '/_img/plugins/fancyupload/Swiff.Uploader.swf',
							//url: 'https://wmadmin:k4n44lw3g@vic.moneymedic.eu/uploadsingle',
							url: flashurl,
							data: extraData,
							zIndex: 101000,
							verbose: true,
							queued: false,
							multiple: false,
							target: dialog_upload_attachment_link,
							instantStart: true,
							typeFilter: {
								'Bestanden (*.jpg, *.jpeg, *.gif, *.png, *.pdf, *.doc, *.txt, *.docx, *.xls, *.xlsx)': '*.jpg; *.jpeg; *.gif; *.png; *.pdf; *.doc; *.txt; *.docx, *.xls, *.xlsx'
							},
							fileSizeMax: 2 * 1024 * 1024,
							onBeforeStart: function() {
// dbug.log('onBeforeStart');								
								loader.setStyle('display', 'block');
							},
							onBeforeStop: function() {
// dbug.log('onBeforeStop');																
							},							
							onSelectSuccess: function(files) {
								if (Browser.Platform.linux) window.alert('Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nSince you are prepared now, the upload will start right away ...');
		// dbug.log('Starting Upload', 'Uploading <em>' + files[0].name + '</em> (' + Swiff.Uploader.formatUnit(files[0].size, 'b') + ')');
								this.setEnabled(false);
							},
							onSelectFail: function(files) {
alert('' + files[0].name + ' is te groot. Selecteer een bestand kleiner dan 2 Mb. (Error: #' + files[0].validationError + ')');
							},
							appendCookieData: true,
							onQueue: function() {
								if (!swf.uploading) return;
								var size = Swiff.Uploader.formatUnit(swf.size, 'b');
								if (progressBar) {
									progressBar.set('html', '<span class="small">' + swf.percentLoaded + '% / ' + size + '</span>');
								}
								//link.set('html', );						
							},
							onFileComplete: function(file) {

		// dbug.log('filecomplete: response = ');
		// dbug.log(JSON.decode(file.response.text));						
								if (file.response.error) {
alert('Uploading ' + this.fileList[0].name + ' failed, please try again. (Error: #' + this.fileList[0].response.code + ' ' + this.fileList[0].response.error + ')');
								} else {
									//var md5 = JSON.decode(file.response.text, true).hash; // secure decode

									//log.alert('Successful Upload', 'an MD5 hash was created from <em>' + this.fileList[0].name + '</em>: <code>' + md5 + '</code>.<br />gravatar.com generated a fancy and unique monsterid for it, since we did not save the image.');

									//var img = $('demo-portrait');
									//img.setStyle('background-image', img.getStyle('background-image').replace(/\w{32}/, md5));
									//img.highlight();
		// dbug.log('upload succes');							
									rJson = JSON.decode(file.response.text);
								}
								var finalfilename = false;
								if ($defined(rJson.uploadtype) && $defined(rJson.filename)) {
									finalfilename = rJson.uploadtype+'/'+rJson.filename;
								}
								if (dialog_attachment_extra && finalfilename) {
									dialog_attachment_extra.set('value',finalfilename );
								}
								if (progressBar && finalfilename) {
									//var finalfilelink = '<a href="/_f/'+mm.runtime.auth.username+'/'+finalfilename+'">'+rJson.filename+'</a>';
									//progressBar.set('html', finalfilelink);
									dialog_send_attachment_extra.set('checked', true).setStyle('display','inline-block');
									var displayName = rJson.filename.substr(rJson.filename.indexOf('_')+1);
									attachment_extra_display.set('html', displayName).setStyle('display','inline-block');
									progressBar.set('html', '');
								}						
								file.remove();
								this.setEnabled(true);
							},
							onComplete: function() {
								//link.set('html', 'klik again');
// dbug.log('HIDDEN VALUE = '+dialog_attachment_extra.get('value'));								
								loader.setStyle('display', 'none');
							}
						});

						// Button state
						dialog_upload_attachment_link.addEvents({
							click: function() {
								return false;
							},
							mouseenter: function() {
								this.addClass('hover');
								swf.reposition();
							},
							mouseleave: function() {
								this.removeClass('hover');
								this.blur();
							},
							mousedown: function() {
								this.focus();
							}
						});
		
		
		

	}
	, settingsInvoiceNrPreview:function(inputEl,blur) {
		var invoice_nr_prefix = this.dialogForm.getElement('#dialog_invoice_nr_prefix');
		var invoice_nr_count = this.dialogForm.getElement('#dialog_invoice_nr_count');
		var invoice_nr_preview = this.dialogForm.getElement('#dialog_invoice_nr_preview');		
		var prefix = invoice_nr_prefix.get('value').substr(0,6);
		var count = invoice_nr_count.get('value').trim().toInt();
		if (isNaN(count) ) { count = 1;  }
		if (blur) {
			if (isNaN(count) || count < 1 ) {
				count = 1; invoice_nr_count.set('value',1);				
			}
			invoice_nr_prefix.set('value', prefix);
		}
		var count = sprintf("%05d",''+count);
		invoice_nr_preview.set('html', prefix+count);		
	}
	, setupDialogFooterButtons:function() {
		this.dialogIsSaving = false;	
		this.dialogSaveBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogSaveBtn]');
		this.dialogCancelBtn = this.dialogFooter.getElement('a.mmOverlayAllDialogCancelBtn');		
		if (this.dialogSaveBtn) {
			this.dialogSaveBtn.addEvent('click', function(e) {
				e.stop();
				if (!this.dialogIsSaving) {
					this.dialogIsSaving = true;				
					this.saveDailogForm();
				}
			}.bind(this));
		}
//dbug.log('cancelbutton = '+this.dialogCancelBtn +' saveBtn='+this.dialogSaveBtn);		
		if (this.dialogCancelBtn) {
			this.dialogCancelBtn.addEvent('click', function(e) {
				e.stop();
				this.cancelDialogForm();
			}.bind(this));
		}
		
		if (this.dialogType == 'help') {
			
			this.dialogNextBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogHelpNextBtn]');
			this.dialogPrevBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogHelpPrevBtn]');			
			var helpContainer = this.dialogBody.getElement('div.dialog_help_content_container');
			var cnts = this.dialogBody.getElements('div.dialog_help_content');			
			var help_page = this.dialogBody.getElement('#help_page');
			var cur_help_page = 0;
			if (help_page) { cur_help_page = help_page.get('value').toInt(); }
			helpContainer.store('curHelp', cur_help_page);	
			if (this.dialogNextBtn) {
				//var href = this.dialogNextBtn.get('href');
				//this.dialogNextBtn.set('href','#');
				//if (href.charAt(0)=='/') { href = href.substr(1,href.length); }			
				this.dialogNextBtn.addEvent('click', function(e) { 
					e.stop();
					//alert('showdialog met '+href);
					var curHelp = helpContainer.retrieve('curHelp', 0).toInt();
					var curHelpView = this.dialogBody.getElement('#help_'+curHelp);
					var nextHelp = this.dialogBody.getElement('#help_'+(curHelp+1));
					if (nextHelp) {
						curHelpView.setStyle('display','none');
						nextHelp.setStyle('display','block');				
						helpContainer.store('curHelp', curHelp+1);								
					} 
					var newNext = this.dialogBody.getElement('#help_'+(curHelp+2));
					if (!newNext) {
						this.dialogNextBtn.setStyle('display','none');
					}
					this.dialogPrevBtn.setStyle('display','inline-block');
				}.bind(this));
				
			}
			if (this.dialogPrevBtn) {
				//var href = this.dialogPrevBtn.get('href');
				//this.dialogPrevBtn.set('href','#');
				//if (href.charAt(0)=='/') { href = href.substr(1,href.length); }			
				this.dialogPrevBtn.addEvent('click', function(e) { 
					e.stop();					
					var curHelp = helpContainer.retrieve('curHelp', 0).toInt();
					var curHelpView = this.dialogBody.getElement('#help_'+curHelp);					
					var prevHelp = this.dialogBody.getElement('#help_'+(curHelp-1));
					if (prevHelp) {
						curHelpView.setStyle('display','none');
						prevHelp.setStyle('display','block');					
						helpContainer.store('curHelp', curHelp-1);	
					}
					var newPrev = this.dialogBody.getElement('#help_'+(curHelp-2));
					if (!newPrev) {
						this.dialogPrevBtn.setStyle('display','none');
					}
					this.dialogNextBtn.setStyle('display','inline-block');					
				}.bind(this));
			}		
			
			var helpLinks = this.dialogBody.getElements('a[class~=mainactionHelp], a[class~=mainactionHelpActive]');			
			var cnts = this.dialogBody.getElements('div.dialog_help_content');
			if (helpLinks.length > 0) {					
				helpLinks.each(function(hLink) {
					var href = hLink.get('href');
					if (href.charAt(0)=='/') { href = href.substr(1,href.length); }			
					hLink.set('href', '#');
					hLink.addEvent('click', function(e) {						
						e.stop();					
						var el = this.dialogBody.getElement('#'+href);
						if (el) {
							var numsplit = href.split('_');
							var num = numsplit[1].toInt();
							helpContainer.store('curHelp', num);
							var nextHelp = this.dialogBody.getElement('#help_'+(num+1));
							if (nextHelp) {
								this.dialogNextBtn.setStyle('display','inline-block');		
							} else {
									this.dialogNextBtn.setStyle('display','none');		
							}
							var prevHelp = this.dialogBody.getElement('#help_'+(num-1));
							if (prevHelp) {
								this.dialogPrevBtn.setStyle('display','inline-block');														
							} else {
									this.dialogPrevBtn.setStyle('display','none');														
							}								
							cnts.setStyle('display', 'none');								
							el.setStyle('display','block');
						}
					}.bind(this));
				},this);
			}				
		}
		
		if (this.dialogType == 'usersecrets' || this.dialogType == 'reset' || this.dialogType == 'quit') {
			this.dialogNextBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogNextBtn]');			
			this.dialogCloseNowBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogCloseBtn]');	
			this.dialogCloseNowBtn.addEvent('click', function(e) { e.stop(); this.hideDialog(true); }.bind(this) );	
			var try_again = this.dialogForm.getElement('#try_again');
			var derror = this.dialogForm.getElement('#usersecrets_error');
			var dform = this.dialogForm.getElement('#usersecrets_form');			
			if (try_again && derror && dform) {
				try_again.addEvent('click', function(e) {
					e.stop();
					derror.setStyle('display','none');
					dform.setStyle('display', 'block');
					this.dialogCloseNowBtn.setStyle('display','none');
					this.dialogNextBtn.setStyle('display','inline-block');					
					this.dialogForm.getElements('input').set('value','');
				}.bind(this));
			}
//			this.userSecrets_1 = this.dialogForm.getElement('#usersecrets_1');
//			this.userSecrets_2 = this.dialogForm.getElement('#usersecrets_2');	
			
			this.dialogNextBtn.addEvent('click', function(e) {
				e.stop();
				var qs = this.dialogForm.toQueryString();				
				var formdata = qs.parseQueryString();
				var action = this.dialogForm.get('action');
				if (action.charAt(0)=='/') { action = action.substr(1,action.length); }			
				var ajaxurl = '/_x/'+action;				

				formdata.secret_answer = Base64.encode(formdata.secret_answer);
				formdata.password = Base64.encode(formdata.password);	
// dbug.log('dialogFormData:'+JSON.encode(formdata));

// testing:
/*
if (this.dialogType == 'reset' || this.dialogType == 'quit') {
	this.showDialog(this.dialogType+'_code');
return false;
}
*/

				new Request.JSON({
					url:ajaxurl
					, data: formdata
					, method:'post'
					, onSuccess: function(rJson, rText) {
						//this.sendInvoiceFormRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText, formdata]);
// dbug.log(rJson);
						if (rJson.success) {
							this.showDialog(this.dialogType+'_code');
							//this.dialogNextBtn.setStyle('display','none');
						} else {
							var derror = this.dialogForm.getElement('#usersecrets_error');
							var dform = this.dialogForm.getElement('#usersecrets_form');
							derror.setStyle('display', 'block');
							dform.setStyle('display','none');
							//this.dialogNextBtn.removeEvents('click');
							//this.dialogNextBtn.set('html', 'sluiten').addEvent('click', function(e) { this.hideDialog(true); }.bind(this));
							this.dialogNextBtn.setStyle('display','none');
							this.dialogCloseNowBtn.setStyle('display','inline-block');
// dbug.log(this.dialogCancelBtn);							
						}
					}.bind(this)
					, onRequest: function() {
						//this.sendInvoiceFormRequestStart();
					}.bind(this)
					, onFailure: function() {
						//this.sendInvoiceFormRequestFailure();
						var derror = this.dialogForm.getElement('#usersecrets_error');
						var dform = this.dialogForm.getElement('#usersecrets_form');
						derror.setStyle('display', 'block');
						dform.setStyle('display','none');
						//this.dialogNextBtn.removeEvents('click');
						//this.dialogNextBtn.set('html', 'sluiten').addEvent('click', function(e) { this.hideDialog(true); }.bind(this));						
						this.dialogNextBtn.setStyle('display','none');
						this.dialogCloseNowBtn.setStyle('display','inline-block');						
					}.bind(this)
				}).send();
					
			}.bind(this));
		}
		
		if (this.dialogType == 'reset_edit' || this.dialogType == 'quit_edit') {
			this.dialogNextBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogNextBtn]');
			this.dialogCloseNowBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogCloseBtn]');	
			this.dialogCloseNowBtn.setStyle('display','none').addEvent('click', function(e) { e.stop(); this.hideDialog(true); }.bind(this) );
			var cnt_form = this.dialogForm.getElement('#cnt_form');			
			var cnt_error = this.dialogForm.getElement('#cnt_error');
			var cnt_success = this.dialogForm.getElement('#cnt_success');						
			this.dialogNextBtn.addEvent('click', function(e) {
				e.stop();
				var qs = this.dialogForm.toQueryString();				
				var formdata = qs.parseQueryString();
				var action = this.dialogForm.get('action');
				if (action.charAt(0)=='/') { action = action.substr(1,action.length); }			
				var ajaxurl = '/_x/'+action;
				
				new Request.JSON({
					url:ajaxurl
					, data: formdata
					, method:'post'
					, onSuccess: function(rJson, rText) {
						//this.sendInvoiceFormRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText, formdata]);
// dbug.log(rJson);
						var cnt_form = this.dialogForm.getElement('#cnt_form');			
						var cnt_error = this.dialogForm.getElement('#cnt_error');
						var cnt_success = this.dialogForm.getElement('#cnt_success');
						if (rJson.success) {
							cnt_success.setStyle('display','block');
							cnt_form.setStyle('display','none');														
							cnt_error.setStyle('display','none');							
							this.dialogNextBtn.setStyle('display','none');
							if (this.dialogType == 'quit_edit') {
								mm.loginPoll.stopPoller();								
								var quitHref = 'https://www.moneymedic.eu/quit/';
								if (rJson.quit_url) {
									quitHref += rJson.quit_url;
								} else {
									quitHref += '09644372e99020106946045c6fd2d70b';
								}
								this.dialogCloseNowBtn.removeEvents('click');
// dbug.log('quit_url = '+quitHref);										
								this.dialogCloseNowBtn.addEvent('click', function(e) { 
									e.stop(); 
									//this.hideDialog(true); 							
									if (rJson.quit_url) {
										window.location.href = quitHref;
									} else {
										window.location.href = quitHref;										
									}
								}.bind(this) );
								(function () { window.location.href = quitHref; }).delay(3000, mm);
							} else if (this.dialogType == 'reset_edit') {
								mm.loginPoll.stopPoller();
								this.dialogCloseNowBtn.removeEvents('click');								
								this.dialogCloseNowBtn.addEvent('click', function(e) { 
									e.stop();
									(function () { window.location.href = '/app'; }).delay(10);									
								}.bind(this));								
							}
							this.dialogCloseNowBtn.setStyle('display','inline-block');		
							this.dialogCloseBtn.setStyle('display','none');
						} else {
							cnt_success.setStyle('display','none');
							cnt_form.setStyle('display','none');																					
							cnt_error.setStyle('display','block');							
							this.dialogNextBtn.setStyle('display','none');
							this.dialogCloseNowBtn.setStyle('display','inline-block');							
						}

					}.bind(this)
					, onRequest: function() {
						//this.sendInvoiceFormRequestStart();
						this.dialogNextBtn.setStyle('display','none');
					}.bind(this)
					, onFailure: function() {
						var cnt_form = this.dialogForm.getElement('#cnt_form');			
						var cnt_error = this.dialogForm.getElement('#cnt_error');
						var cnt_success = this.dialogForm.getElement('#cnt_success');						
						cnt_form.setStyle('display','none');																				
						cnt_success.setStyle('display','none');
						cnt_error.setStyle('display','block');						
						this.dialogNextBtn.setStyle('display','none');
						this.dialogCloseNowBtn.setStyle('display','inline-block');						
					}.bind(this)
				}).send();				
				
			}.bind(this));
		}
		
		if (this.dialogType == 'usersecrets_code' || this.dialogType == 'reset_code' || this.dialogType == 'quit_code') {
			this.dialogNextBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogNextBtn]');
			this.dialogCloseNowBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogCloseBtn]');	
			this.dialogCloseNowBtn.setStyle('display','none').addEvent('click', function(e) { e.stop(); this.hideDialog(true); }.bind(this) );			
			var try_again = this.dialogForm.getElement('#try_again');
			var derror = this.dialogForm.getElement('#usersecrets_error');
			var dform = this.dialogForm.getElement('#usersecrets_form');			
			if (try_again && derror && dform) {
				try_again.addEvent('click', function(e) {
					e.stop();
					derror.setStyle('display','none');
					dform.setStyle('display', 'block');
					this.dialogCloseNowBtn.setStyle('display','none');
					this.dialogNextBtn.setStyle('display','inline-block');
					this.dialogForm.getElements('input').set('value','');
				}.bind(this));
			}			
			this.dialogNextBtn.addEvent('click', function(e) {
				e.stop();
				var qs = this.dialogForm.toQueryString();				
				var formdata = qs.parseQueryString();
				var action = this.dialogForm.get('action');
				if (action.charAt(0)=='/') { action = action.substr(1,action.length); }			
				var ajaxurl = '/_x/'+action;
				formdata.code = Base64.encode(formdata.code);
// dbug.log('formdata: '+JSON.encode(formdata));
/*
//testing:
if (this.dialogType=='reset_code' || this.dialogType == 'quit_code') { 
	if (this.dialogType=='reset_code') { this.showDialog('reset_edit'); }							
	else if (this.dialogType=='quit_code') { this.showDialog('quit_edit'); }	

return false;
}
*/

				new Request.JSON({
					url:ajaxurl
					, data: formdata
					, method:'post'
					, onSuccess: function(rJson, rText) {
						//this.sendInvoiceFormRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText, formdata]);
// dbug.log(rJson);
							
						if (rJson.success) {
							var dia = '';
							if (this.dialogType=='usersecrets_code') { dia = 'usersecrets'; }
							else if (this.dialogType=='reset_code') { dia = 'reset'; }							
							else if (this.dialogType=='quit_code') { dia = 'quit'; }		
							this.showDialog(dia+'_edit');
						} else {
							var derror = this.dialogForm.getElement('#usersecrets_error');
							var dform = this.dialogForm.getElement('#usersecrets_form');
							derror.setStyle('display', 'block');
							dform.setStyle('display','none');
							this.dialogNextBtn.setStyle('display','none');
							this.dialogCloseNowBtn.setStyle('display','inline-block');							
						}

					}.bind(this)
					, onRequest: function() {
						//this.sendInvoiceFormRequestStart();
					}.bind(this)
					, onFailure: function() {
						var derror = this.dialogForm.getElement('#usersecrets_error');
						var dform = this.dialogForm.getElement('#usersecrets_form');
						derror.setStyle('display', 'block');
						dform.setStyle('display','none');
						//this.dialogNextBtn.removeEvents('click');
						//this.dialogNextBtn.set('html', 'sluiten').addEvent('click', function(e) { this.hideDialog(true); }.bind(this));						
						this.dialogNextBtn.setStyle('display','none');
						this.dialogCloseNowBtn.setStyle('display','inline-block');						
					}.bind(this)
				}).send();				
			}.bind(this));						
		}

		
		this.dialogInvoiceSaveBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogInvoiceSaveBtn]');
		if (this.dialogInvoiceSaveBtn) {
			this.dialogInvoiceSaveBtn.addEvent('click', function(e) {
				e.stop();
				if (!this.dialogIsSaving) {	
					this.dialogIsSaving = true;									
					this.saveInvoiceForm();
				}
			}.bind(this));
		}

		this.dialogInvoiceSendBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogInvoiceSendBtn]');
		if (this.dialogInvoiceSendBtn) {
			this.dialogInvoiceSendBtn.addEvent('click', function(e) {
				e.stop();
				this.sendInvoiceForm();
			}.bind(this));
		}
		this.dialogInvoiceSaveSendNextBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogInvoiceSaveSendNextBtn]');
		this.dialogInvoiceSaveSendPrevBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogInvoiceSaveSendPrevBtn]');		
		this.dialogInvoiceSaveSendBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogInvoiceSaveSendBtn]');
		this.dialogInvoiceSaveConceptBtn = this.dialogFooter.getElement('a[class~=dialogactionbutton][class~=mmOverlayAllDialogInvoiceSaveConceptBtn]');
		if (this.dialogInvoiceSaveSendNextBtn && this.dialogInvoiceSaveSendPrevBtn && this.dialogInvoiceSaveSendBtn && this.dialogInvoiceSaveConceptBtn) {

			this.dialogInvoiceSaveSendNextBtn.addEvent('click', function(e) {
				e.stop();
				var step_choices = this.dialogForm.getElement('.step_choices');
				var step_choice_1 = this.dialogForm.getElement('.step_choice_1');
				var step_choice_2 = this.dialogForm.getElement('.step_choice_2');		
				var step_choice_3 = this.dialogForm.getElement('.step_choice_3');						
				if (step_choices.getStyle('display')=='block' && step_choice_1.getStyle('display')=='none' && step_choice_2.getStyle('display')=='none' && step_choice_3.getStyle('display')=='none') {				
					var qs = this.dialogForm.toQueryString();
					var dialogFormData = qs.parseQueryString();
					var choice = dialogFormData.invoice_save_send_choice;
					if (choice == 4) {
						// concept
						this.saveInvoiceForm();
					} else {
						step_choices.setStyle('display','none');						
						var choicediv = this.dialogForm.getElement('.step_choice_'+choice);
						if (choicediv) {
							choicediv.setStyle('display', 'block');
						}
						var recipient_email = document.id('recipient_email');
						var rec_email = document.id('dialog_recipient_email_'+choice);
						//var rec_email_span = this.dialogForm.getElement('span[rel=dialog_recipient_email_'+choice+']');
						var send_now = this.dialogForm.getElement('#dialog_send_now_'+choice);
						rec_email.set('value', recipient_email.get('value'));
						if (!$chk(rec_email.get('value')) && send_now.get('checked')) {
							rec_email.addClass('validation-failed');
						} 
						//rec_email_span.set('html', recipient_email.get('value'));	
						this.dialogInvoiceSaveSendBtn.setStyle('display','inline-block');
						this.dialogInvoiceSaveSendNextBtn.setStyle('display', 'none');					
						this.dialogInvoiceSaveSendPrevBtn.setStyle('display','inline-block');					
					}
				}
						
			}.bind(this));
			
			this.dialogInvoiceSaveConceptBtn.addEvent('click', function(e) {
				e.stop();
				var step_choices = this.dialogForm.getElement('.step_choices');
				var step_choice_1 = this.dialogForm.getElement('.step_choice_1');
				var step_choice_2 = this.dialogForm.getElement('.step_choice_2');		
				var step_choice_3 = this.dialogForm.getElement('.step_choice_3');						
				if (step_choices.getStyle('display')=='block' && step_choice_1.getStyle('display')=='none' && step_choice_2.getStyle('display')=='none' && step_choice_3.getStyle('display')=='none') {				

					var qs = this.dialogForm.toQueryString();
					var dialogFormData = qs.parseQueryString();
					var choice = dialogFormData.invoice_save_send_choice;
					if (choice == 4) {
						// concept
						this.saveInvoiceForm();
					} else {
						
					}
				}				
			}.bind(this));
			
			this.dialogInvoiceSaveSendPrevBtn.addEvent('click', function(e) {
				e.stop();
				var step_choices = this.dialogForm.getElement('.step_choices');
				var step_choice_1 = this.dialogForm.getElement('.step_choice_1');
				var step_choice_2 = this.dialogForm.getElement('.step_choice_2');
				var step_choice_3 = this.dialogForm.getElement('.step_choice_3');		
				if (step_choices.getStyle('display')=='none' && (step_choice_1.getStyle('display')=='block' || step_choice_2.getStyle('display')=='block' || step_choice_3.getStyle('display')=='block')) {
					step_choices.setStyle('display','block');                                     
					step_choice_1.setStyle('display','none');
					step_choice_2.setStyle('display','none');					
					step_choice_3.setStyle('display','none');										
					this.dialogInvoiceSaveSendPrevBtn.setStyle('display','none');
					this.dialogInvoiceSaveSendNextBtn.setStyle('display', 'inline-block');
					this.dialogInvoiceSaveSendBtn.setStyle('display','none');					
				}			
			}.bind(this));			
			
			this.dialogInvoiceSaveSendBtn.addEvent('click',function(e) {
				e.stop();
				var step_choices = this.dialogForm.getElement('.step_choices');
				var step_choice_1 = this.dialogForm.getElement('.step_choice_1');
				var step_choice_2 = this.dialogForm.getElement('.step_choice_2');				
				var step_choice_3 = this.dialogForm.getElement('.step_choice_3');				
			 	if (step_choices.getStyle('display')=='none') {
					this.saveInvoiceForm();
				}
			}.bind(this));
		}
	}
	, validateDialogForm:function() {
		if (this.dialogFormValidator.validate()) {
			return true;
		} else {
			var inputs = this.dialogForm.getElements('input, select, textarea');
			var failed = false;
			inputs.each(function(input) {
				if ( (input.hasClass('required') || (input.hasClass('validate-required-check'))) && input.hasClass('validation-failed')) {
					failed = true;
				} else if (!input.hasClass('required') && input.hasClass('validation-failed')) {
					input.removeClass('validation-failed');
				}
			},this);
			if (!failed) {
				return true;
			} else {
				return false;
			}
		}		
	}
	, sendInvoiceForm:function() {
// dbug.log('endInvoiceForm this dialogtype = '+this.dialogType);			
		if (this.dialogType == 'invoice_send') {
			if (!this.validateDialogForm()) {
				mm.noticeError.show({title:'onvoldoende gegevens', noFade:true});
				return false;
			}			
			
			var qs = this.dialogForm.toQueryString();
			var formdata = qs.parseQueryString();
			// if ($defined(formdata.send_attachment_extra_invoice) && $chk(formdata.send_attachment_extra_invoice)) {
			// 	formdata.send_attachment_extra_invoice
			// }
			var action = this.dialogForm.get('action');
			if (action.charAt(0)=='/') { action = action.substr(1,action.length); }			
			var ajaxurl = '/_x/'+action;
// dbug.log(formdata);
			new Request.JSON({
				url:ajaxurl
				, data: formdata
				, method:'post'
				, onSuccess: function(rJson, rText) {
					this.sendInvoiceFormRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText, formdata]);
				}.bind(this)
				, onRequest: function() {
					this.sendInvoiceFormRequestStart();
				}.bind(this)
				, onFailure: function() {
					this.sendInvoiceFormRequestFailure();
				}.bind(this)								
			}).send();
		}
	}
	, saveInvoiceForm:function() {
// dbug.log('saveInvoiceForm this dialogtype = '+this.dialogType);	
		var invoiceForm = false;
		if (this.dialogType == 'invoice_save') {
			invoiceForm = document.id('invoiceForm');
			var invoice_save = document.id('invoice_save');
			//var invoice_save_choices = this.dialogForm.getElement('#invoice_save_choice');
			var qs = this.dialogForm.toQueryString();
			var formdata = qs.parseQueryString();
			var invoice_save_choice = formdata.invoice_save_choice;
			if (invoice_save && invoice_save_choice) {
				invoice_save.set('value', invoice_save_choice);
			}			
// dbug.log('invoice save value = '+invoice_save.get('value'));			

				var qsI = invoiceForm.toQueryString();
				var action = invoiceForm.get('action');
				if (action.charAt(0)=='/') { action = action.substr(1,action.length); }		
				var ajaxurl = '/_x/savepageform/'+action;
				var formdataI = qsI.parseQueryString();
// dbug.log('SAVING INVOICE WITH DATA:');
// dbug.log(qsI);
				
				if (invoice_save_choice == 1) {
					formdataI.action = 'save_concept';
				} else if (invoice_save_choice == 2) {
					formdataI.action = 'save_estimate';
				} else if (invoice_save_choice == 3) {
					formdataI.action = 'save_invoice';
				}
// dbug.log(formdataI);								
				new Request.JSON({
					url:ajaxurl
					, data: formdataI
					, method:'post'
					, onSuccess: function(rJson, rText) {
						this.saveInvoiceFormRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText, formdataI]);
					}.bind(this)
					, onRequest: function() {
						this.saveInvoiceFormRequestStart();
					}.bind(this)
					, onFailure: function() {
						this.saveInvoiceFormRequestFailure();
					}.bind(this)
				}).send();
				

		} else if (this.dialogType == 'invoice_save_send') {			
			invoiceForm = document.id('invoiceForm');			
			var invoice_save_send = document.id('invoice_save_send');	
			var qs = this.dialogForm.toQueryString();
			var formdata = qs.parseQueryString();
			var invoice_save_send_choice = formdata.invoice_save_send_choice;
			if (invoice_save_send && invoice_save_send_choice) {
				invoice_save_send.set('value', invoice_save_send_choice);
			}		
			var dialog_recipient_email = document.id('dialog_recipient_email_'+invoice_save_send_choice);
			var invoice_recipient_email = document.id('recipient_email');
			var d_send_now = this.dialogForm.getElement('#dialog_send_now_'+invoice_save_send_choice);			
			
			if (dialog_recipient_email && invoice_recipient_email ) {
				if ($chk(dialog_recipient_email.get('value'))) {
					invoice_recipient_email.set('value', dialog_recipient_email.get('value'));
				} else {
					if (d_send_now.get('checked')) {
						dialog_recipient_email.addClass('validation-failed');
						mm.noticeError.show({title:'e-mail adres verplicht', noFade:true});
						return false;
					}
				}
			}
			var invoice_send_message = document.id('message');
			var dialog_send_message = document.id('dialog_send_message_'+invoice_save_send_choice);
			if (invoice_send_message && dialog_send_message) {
				invoice_send_message.set('value', dialog_send_message.get('value'));			
			}
			var invoice_cc_me = document.id('cc_me');
			if (invoice_cc_me) { invoice_cc_me.set('value',1); }
			// var dialog_cc_me = document.id('dialog_cc_me_'+invoice_save_send_choice);
			// if (invoice_cc_me && dialog_cc_me) {
			// 	if (dialog_cc_me.get('checked')) {
			// 		invoice_cc_me.set('value',1);
			// 	}
			//  			}
			var dialog_auto_invoice = document.id('dialog_auto_invoice');
			var invoice_auto_approve = document.id('auto_approve');
			if (invoice_auto_approve && dialog_auto_invoice) {
				if (dialog_auto_invoice.get('checked')) {
					invoice_auto_approve.set('value',1);
				}
			}
			// var dialog_auto_periodic_invoice = document.id('dialog_auto_periodic_invoice');
			// var invoice_auto_periodic = document.id('auto_periodic');
			// if (invoice_auto_periodic && dialog_auto_periodic_invoice) {
			// 	if (dialog_auto_periodic_invoice.get('checked')) {
			// 		invoice_auto_periodic.set('value',1);
			// 	}
			// }			
			
			var dialog_lock_estimate = this.dialogForm.getElement('#dialog_lock_estimate');
			var lock_estimate = document.id('lock_estimate');
			if (dialog_lock_estimate && lock_estimate) {						
				if (dialog_lock_estimate.get('checked')) { lock_estimate.set('value', 1); } else { lock_estimate.set('value', 0); }
			}
			
			var qsI = invoiceForm.toQueryString();
			var action = invoiceForm.get('action');
			if (action.charAt(0)=='/') { action = action.substr(1,action.length); }		
			var ajaxurl = '/_x/savepageform/'+action;
			var formdataI = qsI.parseQueryString();
			
			var dialog_invoice_save_send_action = document.id('dialog_invoice_save_send_action');
			var dialog_send_now = this.dialogForm.getElement('#dialog_send_now_'+invoice_save_send_choice);
			var do_send = false;
			
			var dialog_date_start = this.dialogForm.getElement('#dialog_date_start');
			var dialog_repeat = this.dialogForm.getElement('#dialog_repeat');
			var dialog_times = this.dialogForm.getElement('#dialog_invoice_save_times');			
			
			if ($defined(dialog_send_now) && dialog_send_now.get('checked')) { do_send = true; }
			if (dialog_invoice_save_send_action) {
				if (dialog_invoice_save_send_action.get('value') == 'choose') {
					if (invoice_save_send_choice == 1) {						
						formdataI.action = do_send ? 'save_send_estimate' : 'save_estimate' ;
						// if (dialog_auto_periodic_invoice.get('checked')) {
						// 	formdataI.is_periodic = 0;
						// 	formdataI.date_start = dialog_date_start.get('value');
						// 	formdataI.repeat = dialog_repeat.get('value');
						// 	formdataI.times = dialog_times.get('value');							
						// }						
						var dialog_send_attachment_extra = this.dialogForm.getElement('#dialog_send_attachment_extra_estimate');
						var dialog_attachment_extra = this.dialogForm.getElement('#dialog_attachment_extra_estimate');
						if (dialog_send_attachment_extra.get('checked') && dialog_attachment_extra.get('value') != '') {
							formdataI.extra_attachment = dialog_attachment_extra.get('value');
							formdataI.send_extra_attachment = dialog_send_attachment_extra.get('checked');
						}						
						if (formdataI.is_locked == 1 && formdataI.has_estimate == 1) {
							formdataI.action = do_send ? 'send_estimate' : 'no_save_estimate' ;
						}
					} else if (invoice_save_send_choice == 2) {						
						var dialog_send_attachment_extra = this.dialogForm.getElement('#dialog_send_attachment_extra_invoice');
						var dialog_attachment_extra = this.dialogForm.getElement('#dialog_attachment_extra_invoice');
						if (dialog_send_attachment_extra.get('checked') && dialog_attachment_extra.get('value') != '') {
							formdataI.extra_attachment = dialog_attachment_extra.get('value');
							formdataI.send_extra_attachment = dialog_send_attachment_extra.get('checked');
						}
						formdataI.action = do_send ? 'save_send_invoice' : 'save_invoice' ;												
					} else if (invoice_save_send_choice == 3) {
						formdataI.auto_send = 0;
						formdataI.action = do_send ? 'save_send_periodic' : 'save_periodic' ;
						formdataI.is_periodic = 1;
						formdataI.date_start = dialog_date_start.get('value');
						formdataI.repeat = dialog_repeat.get('value');
						formdataI.times = dialog_times.get('value');			
						if (do_send) {
							formdataI.auto_send = 1;
						}
					} else if (invoice_save_send_choice == 4) {
						formdataI.action = 'save_concept';
					}
								
				} else if (dialog_invoice_save_send_action.get('value') == 'resend') {
					if (invoice_save_send_choice == 1) {
						formdataI.action = 'send_estimate';
					} else if (invoice_save_send_choice == 2) {
						formdataI.action = 'send_invoice';
					} else if (invoice_save_send_choice == 3) {
						formdataI.action = 'send_periodic';
					}								
				}
			}
			
			
// dbug.log('SAVING AND SENDING INVOICE WITH DATA:');
// dbug.log(qsI);			
// dbug.log(formdataI);

			new Request.JSON({
				url:ajaxurl
				, data: formdataI
				, method:'post'
				, onSuccess: function(rJson, rText) {
					this.saveInvoiceFormRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText, formdataI]);
				}.bind(this)
				, onRequest: function() {
					this.saveInvoiceFormRequestStart();
				}.bind(this)
				, onFailure: function() {
					this.saveInvoiceFormRequestFailure();
				}.bind(this)
			}).send();

		}
	}
	, sendInvoiceFormRequestStart:function() {
		this.showNotice('loading', mm.lang.notice_info.sending);
		this.hideDialog();
	}
	, sendInvoiceFormRequestFailure:function() {
		
	}
	, sendInvoiceFormRequestSucces:function(rJson, rText, formdata) {
// dbug.log('sendInvoiceFormRequestSucces:')		
// dbug.log(rJson);
		if (rJson.sent) {
			if (rJson.invoice_id) {
				(function() { window.location.href = '/invoice/'+rJson.invoice_id; }).delay(200,this);					
			}
		}
	}
	, saveInvoiceFormRequestStart:function() {
		this.showNotice('loading', mm.lang.notice_info.saving);
		//mm.noticeInfo.show({title:mm.lang.notice_info.saving});		
		//this.showDialogOverlay(mm.lang.dialog_notice.saving);		
		this.hideDialog();
		
	}
	, saveInvoiceFormRequestFailure:function() {
		// error
	}
	, saveInvoiceFormRequestSucces:function(rJson, rText, formdata) {
// dbug.log('saveInvoiceFormRequestSucces: ');
// dbug.log(rJson);

		if (rJson.saved) {
			if (rJson.invoice_id) {
				if (formdata.action == 'save_concept') {
					(function() { window.location.href = '/invoices#concepts'; }).delay(200,this);					
//					(function() { window.location.href = '/invoice/'+rJson.invoice_id; }).delay(200,this);										
				} else {
					if (formdata.action =='save_send_periodic' || formdata.action == 'save_periodic') {
						(function() { window.location.href = '/invoices#periodic' }).delay(200,this);					
					} else {
						(function() { window.location.href = '/invoice/'+rJson.invoice_id; }).delay(200,this);					
					}
				}
			}
		}
		
	}
	, saveDailogForm:function() {
// dbug.log('saveDailogForm: dialog type = '+this.dialogType+' dialog action ='+this.dialogAction);	

		if (!this.validateDialogForm()) {
// dbug.log('error validating dialog form');
			//this.showNotice('error', mm.lang.notice.newpass_validation_error);		
			//(function() { this.hideInnerOverlay(); }).delay(this.options.innerOverlayDelay, this);													
			mm.noticeError.show({title:'onvoldoende gegevens', noFade:true});			
			this.dialogIsSaving = false;
			return false;			
		}
		if (this.dialogType == 'product') {
			var product_title = this.dialogForm.getElement('#product_title');
			var hidden_product_id = this.dialogForm.getElement('#product_id');
			var product_id = false;
			if (hidden_product_id && $chk(hidden_product_id.get('value'))) {
				product_id = hidden_product_id.get('value').toInt();
			}			
			if (product_title) {				
				this.checkProductAvailable(product_title, product_id);
				var productAvailable = product_title.retrieve('productAvailable',false);
				if (!productAvailable) {
					product_title.addClass('validation-failed');
					//mm.noticeError.show({title:'product titel bestaat al', noFade:true});			
					this.dialogIsSaving = false;
					return false;					
				}
			}
			var product_price = this.dialogForm.getElement('#product_price');
			if (product_price) {
				var pricevalue = product_price.get('value');
				var pricereplaced = pricevalue.replace(/\,/g, '.');
				product_price.set('value', pricereplaced.toFloat());
			}
		} else if (this.dialogType == 'client') {
			var client_name_company = this.dialogForm.getElement('#client_name_company');
			var hidden_client_id = this.dialogForm.getElement('#client_id');
			var client_id = false;
			if (client_name_company) {
				if ($chk(hidden_client_id.get('value'))) { client_id = hidden_client_id.get('value').toInt(); }
				this.checkClientAvailable(client_name_company, client_id);				
				var clientAvailable = client_name_company.retrieve('clientAvailable',false);
				if (!clientAvailable) {
					client_name_company.addClass('validation-failed');
					//mm.noticeError.show({title:'contact naam bestaat al', noFade:true});			
					this.dialogIsSaving = false;
					return false;					
				}
			}			
		} else if (this.dialogType == 'payment') {
			var payment_amount = this.dialogForm.getElement('#payment_amount');
			if (payment_amount) {
				var pricevalue = payment_amount.get('value');
				var pricereplaced = pricevalue.replace(/\,/g, '.');
				payment_amount.set('value', pricereplaced.toFloat());				
			}
			var payment_send_notification = this.dialogForm.getElement('#payment_send_notification');			
			var payment_continue = true;
			if (payment_send_notification.get('checked')) {
// dbug.log('mail notify checked');				
				var payment_notify_email = this.dialogForm.getElement('#payment_notify_email');			
				var payment_notify_message = this.dialogForm.getElement('#payment_notify_message');					
				var pass_mail = this.dialogFormValidator.test('validate-email', payment_notify_email);
				var pass_mail_required = this.dialogFormValidator.test('required', payment_notify_email);
				var pass_message = this.dialogFormValidator.test('required', payment_notify_message);
				if (!pass_mail || !pass_mail_required) { 
// dbug.log('foutje bij mail field');
					payment_notify_email.addClass('validation-failed');
					payment_continue = false;
				} else { payment_notify_email.removeClass('validation-failed'); }
				if (!pass_message) {
// dbug.log('foutje bij message');					
					payment_notify_message.addClass('validation-failed');
					payment_continue = false;
				} else { payment_notify_message.removeClass('validation-failed'); }
				if (!payment_continue) {
					mm.noticeError.show({title:'onvoldoende gegevens', noFade:true});			
					this.dialogIsSaving = false;
					return false;					
				} 
			}				
		} else if (this.dialogType == 'btwperiod') {
			var newperiodSelect = this.dialogForm.getElement('#dialog_btw_period');
			if (newperiodSelect) {
				var newperiod = newperiodSelect.get('value');
				
			}
		} else if (this.dialogType == 'usersecrets_edit') {
			//
			var do_continue = true;
			var dialog_create_newpassword = this.dialogForm.getElement('#dialog_create_newpassword');
			var dialog_newpassword = this.dialogForm.getElement('#dialog_newpassword');
			if (dialog_create_newpassword.get('checked')) {
				var newpass = dialog_newpassword.get('value');
				if (!dialog_newpassword.retrieve('isValid',false) || dialog_newpassword.hasClass('validation-failed')) {			
					do_continue = false;
				}
			} else {
				dialog_newpassword.set('value', '');
			}
			// var dialog_bank_account_nr = this.dialogForm.getElement('#dialog_bank_account_nr');
			// if (!dialog_bank_account_nr.retrieve('isValid',false) || dialog_bank_account_nr.hasClass('validation-failed') ) {
			// 	do_continue = false;
			// }
			var dialog_email = this.dialogForm.getElement('#dialog_email');
			if (!dialog_email.retrieve('isValid',false) || dialog_email.hasClass('validation-failed')) {
				do_continue = false;
			}
			
			if (!do_continue) {
				mm.noticeError.show({title:'onvoldoende gegevens', noFade:true});			
				this.dialogIsSaving = false;
				return false;
			}
		}
		var qs = this.dialogForm.toQueryString();
		var action = this.dialogForm.get('action');
		if (action.charAt(0)=='/') { action = action.substr(1,action.length); }		
		var ajaxurl = '/_x/savedialog/'+action;
		var formdata = qs.parseQueryString();
// dbug.log('save dialog data:');
// dbug.log(qs);		
		new Request.JSON({
			url:ajaxurl
			, data: formdata
			, method:'post'
			, onSuccess: function(rJson, rText) {
				this.saveDialogRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText, formdata]);
			}.bind(this)
			, onRequest: function() {
				this.saveDialogRequestStart();
			}.bind(this)
			, onFailure: function() {
				this.saveDialogRequestFailure();
			}.bind(this)
		}).send();
		
	}
	, saveDialogRequestSucces:function(rJson, rText, formdata) {
// dbug.log('saveDialogRequestSucces:');		
// dbug.log(rJson);		
		//mm.roar.alert('Opgeslagen', 'succesvol');
//		mm.noticeInfo.show({title:'opgeslagen'});		
		this.hideDialogOverlay();
		//this.hideDialog(true);
		this.afterSaveDialog(rJson, formdata);
	}
	, saveDialogRequestStart:function() {
		this.showNotice('loading', mm.lang.notice_info.saving);		
		//mm.noticeInfo.show({title:mm.lang.notice_info.saving});		
		//this.showDialogOverlay(mm.lang.dialog_notice.saving);		
		this.hideDialog();
	}
	, saveDialogRequestFailure: function() {
		this.dialogIsSaving = false;			
		this.hideDialogOverlay();		
	}
	, cancelDialogForm:function() {
// dbug.log('cancelDialogForm');		
		this.hideDialog(true);		
	}
	, afterSaveDialog: function(rJson, formdata) {
// dbug.log('afterSaveDialog: dialog type = '+this.dialogType+' dialog action ='+this.dialogAction+' current page request ='+mm.runtime.request);
		this.dialogIsSaving = false;	

		if (mm.runtime.request == this.dialogType+'s') {
			if (mm.runtime.request == 'clients') {
				window.location.href = '/client/'+rJson.insert_id;
			} else {
				(function() { window.location.href = '/'+mm.runtime.request; }).delay(500,mm);
			}
		} else if (mm.runtime.request == this.dialogType && this.dialogAction=='edit' ) {
			(function() { 
				var hash = '';
				if (window.location.hash != '') { hash = window.location.hash; }
				document.location.reload(true);
			 }).delay(500,mm);
		} else if (this.dialogType=='btwperiod') {
			this.hideDialog(true);				
			var btw_period_display = document.id('btw_period_display');
			var btwperiods = new Hash({'month':'per maand', 'quarter':'per kwartaal', 'year':'per jaar'});
			if (btw_period_display) {
				btw_period_display.set('html', btwperiods.get(formdata.btw_period));
			}
		} else if (this.dialogType == 'contract') {
			this.hideDialog(true);
dbug.log('afterSaveDialog contract rJson + formdata');			
dbug.log(rJson);
dbug.log(formdata);
			if (rJson.saved) {
				var notice_contract_not_agreed = document.id('notice_contract_not_agreed');
				var notice_contract_agreed = document.id('notice_contract_agreed');
				var contract_agreed_btn_container = document.id('contract_agreed_btn_container');
				if (notice_contract_not_agreed) {
					notice_contract_not_agreed.setStyle('display','none');
				}
				if (notice_contract_agreed) {
					var agreed_html = notice_contract_agreed.get('html');
					var todayStr = new Date().format('%d-%m-%Y');
					var agreed_html = agreed_html.substitute({agreed_date:todayStr, agreed_name:formdata.contract_name});
					notice_contract_agreed.setStyle('display','block').set('html', agreed_html);
					var dLink = notice_contract_agreed.getElement('a.dialogLink');
					if (dLink) {
						dLink.set('href', '/contract_read');
					}
					mm.ajax.ajaxReady(notice_contract_agreed);
				}				
				if (contract_agreed_btn_container) {
					contract_agreed_btn_container.setStyle('display','none');
				}
			} else {
				// dialog not saved
				if (contract_agreed_btn_container) { contract_agreed_btn_container.setStyle('display','block'); }
				if (notice_contract_not_agreed) { notice_contract_not_agreed.setStyle('display','block'); }				
			}
		} else if (this.dialogType == 'usersecrets_edit') {
			this.hideDialog(true);
			// document.id('user_email_display').set('html', formdata.email);
			// document.id('bank_account_nr_display').set('html', formdata.bank_account_nr.substr(4,10) );
			// document.id('bank_account_holder_display').set('html', formdata.bank_account_holder);			
			// document.id('api_key_display').set('html', formdata.api_key);
		} else if (this.dialogType == 'reset_edit') {
// dbug.log(rJson.resetArray);			
			this.hideDialog(true);			
		} else if (this.dialogType == 'quit_edit') {	
			if (rJson.saved) {
				window.location.href = '/logout';
			} else {
				this.hideDialog(true);
			}
		} else if (this.dialogType=='invoicenum') {
			this.hideDialog(true);
			var invoice_nr_preview_display = document.id('invoice_nr_preview_display');
			var invoice_nr_count_hidden = document.id('invoice_nr_count_hidden');
			if (invoice_nr_preview_display) {
				var prefix = formdata.invoice_nr_prefix;
				var count = formdata.invoice_nr_count.trim().toInt();
				if (isNaN(count)) { count = 0; }
				if (count > 0) {				
					var counter = sprintf("%05d",''+count);
					invoice_nr_preview_display.set('html', prefix+counter);	
					invoice_nr_count_hidden.set('value', count);
					var tab_warning = document.id('tab_warning_invoices');
					tab_warning.setStyle('display','none');
					var pdiv = invoice_nr_preview_display.getParent('div.contentCenterInnerArea');
					var warningContainer = pdiv.getElement('.warningContainer');
					warningContainer.setStyle('display','none');
				} 
			}
// hier nog uitroepteken uitzetten
		} else if (this.dialogType=='payment' || this.dialogType == 'payment_delete') {

			(function() { 
				var hash = '';
				if (window.location.hash != '') { hash = window.location.hash; }
				document.location.reload(true);
			 }).delay(500,mm);	

//dbug.log('aftersave payment formdata was: ');
//dbug.log(formdata);					
		} else if ((mm.runtime.request == 'invoice' || mm.runtime.request == 'purchase') && this.dialogType=='client' && this.dialogAction=='add') {
			this.hideDialog(true);			
			var selectClient = document.id('selectClient');
			var textareaClient = document.id('client_static_text');
			if (selectClient && textareaClient && rJson.insert_id) {
				//var options = selectClient.getElements('option');
//dbug.log( JSON.encode(formdata));				
				var newoption = new Element('option', {value:rJson.insert_id}).set('html',formdata.name_company).inject(selectClient);
				selectClient.removeEvents('click');
				selectClient.set('value',rJson.insert_id);	
				selectClient.fireEvent('change');			
			}
		} else if (mm.runtime.request == 'purchase' && this.dialogType=='purchasecategory' && this.dialogAction == 'add') {
			this.hideDialog(true);			
			var purchase_category_id = document.id('purchase_category_id');
			if (purchase_category_id && rJson.insert_id) {
				var newoption = new Element('option', {value:rJson.insert_id}).set('html',formdata.title).inject(purchase_category_id);
				purchase_category_id.set('value', rJson.insert_id);
			}
		} else if (mm.runtime.request == 'purchases' && this.dialogType=='purchasecategory' && (this.dialogAction =='add' || this.dialogAction == 'edit')) {
			(function() { 
				var hash = '';
				if (window.location.hash != '') { hash = window.location.hash; }
				document.location.reload(true);
			 }).delay(500,mm);
			
//dbug.log( JSON.encode(formdata));				
//dbug.log(rJson);		
		} else if (mm.runtime.request == 'invoice' && this.dialogType == 'product' && this.dialogAction == 'add') {
			this.hideDialog(true);			
			var productSelects = $$('select[class~=invoiceProductSelect]');
			if (productSelects.length > 0) {
				productSelects.each(function(sel) {
					var newoption = new Element('option', {value:rJson.insert_id}).set('html', formdata.title).inject(sel);
					sel.removeEvents('click');
				});
				var pricereplaced = formdata.price.replace(/\,/g,'.');
				mm.products.set(rJson.insert_id, new Hash({'title':formdata.title, 'price':pricereplaced.toFloat().round(2), 'btw_tariff':formdata.btw_tariff, 'description':formdata.description}));
				if (this.dialogExtraOptions) {
					if ($defined(this.dialogExtraOptions.parentRow)) {
						var updatesel = this.dialogExtraOptions.parentRow.getElement('select[class~=invoiceProductSelect]');
						if (updatesel) {
							updatesel.set('value', rJson.insert_id);
							updatesel.fireEvent('change');
						}
					}
				}
			}
		} else if (this.dialogType == 'periodic') {
			if (rJson.saved) {
				this.hideDialog(false);
				(function() { 
					var hash = '';
					if (window.location.hash != '') { hash = window.location.hash; }
					document.location.reload(true);
				 }).delay(500,mm);				
			} else {
				this.hideDialog(true);
				mm.noticeError.show({title:mm.lang.notice_error.save_error});
			}
		} else {
			this.hideDialog(true);			
			if (rJson.saved) {
				//mm.noticeInfo.show({title:mm.lang.notice_info.saved});									
			} else {
				mm.noticeError.show({title:mm.lang.notice_error.save_error});
			}			
		}
	}
		
	
}); mm.SignupClass = new Class({
    Implements: [Options, Events],
    options : {
		signupContainer: 'mmSignupContainer'
		, tweenDuration: 500
		, tweenTransition: 'quad:out'
		, noticeDuration: 100
		, noticeTransition: 'circ:in'
		, multiplier: 1
		, pwNotAllowed : [' ','/','\\','>','<','"','\'']
		, ajaxDelay : 1200 	// extra ajax request delay added when request is succesfull (ms)
		, tooltipDelays : {show: 500, hide: 1}
		, innerOverlayDelay : 500
		, innerOverlayOpacity : 0.85		
	},
	initialize: function(options) {
		this.setOptions(options);	
		if (document.id(this.options.signupContainer)) {
			this.element = document.id(this.options.signupContainer);
		}
//dbug.log('signup this elmeent id ='+this.element.get('id'));		
		this.bound = this.bound||{};		
		this.signupTyped = new Hash({'company':false, 'email':false, 'password':false, 'secret_answer':false, 'bank_account_nr':false, 'bank_account_holder':false});
		//this.verifyTyped = new Hash({'code':false});
		this.signupTabindex = [];		
		this.multiplier = this.options.multiplier;	
		this.curDisplayedForm = false;
		this.signupFormkeyOrg = '';	
		this.isOpen = false;		
		this.setupElements();
		this.setupEvents();
		this.checkStatus(false);		
	},
	setupElements: function() {
// dbug.log('mm.SignupClass setupElements');
		this.signupInner = this.element.getElement('#signupInner');
		this.signupInnerOverlay = this.element.getElement('#signupInnerOverlay');
		this.signupNoticeContainer = this.element.getElement('#signupNoticeContainer');
		this.signupNoticeText = this.element.getElement('#signupNoticeText');		
		this.signupNoticeIconOk = this.element.getElement('#signupNoticeIconOk');		
		this.signupNoticeIconInfo = this.element.getElement('#signupNoticeIconInfo');
		this.signupNoticeIconError = this.element.getElement('#signupNoticeIconError');
		this.signupNoticeIconLoading = this.element.getElement('#signupNoticeIconLoading');				

		this.signupNoticeIcons = [this.signupNoticeIconInfo, this.signupNoticeIconOk, this.signupNoticeIconError, this.signupNoticeIconLoading];

		this.signupFormContainer = this.element.getElement('#signupFormContainer');
		this.signupForm = this.element.getElement('#signupForm');
		
		
		this.verifyFormContainer = this.element.getElement('#verifyFormContainer');
		this.verifyForm = this.element.getElement('#verifyForm');		
		
		this.signupMessageFormContainer = this.element.getElement('#signupMessageFormContainer');
		this.signupMessageForm = this.element.getElement('#signupMessageForm');	
		this.signupMessageContainer	= this.signupMessageForm.getElement('#signupMessageContainer');
	
		this.signupMessageText = this.element.getElement('#signupMessageText');		
		this.signupMessageIconOk = this.element.getElement('#signupMessageIconOk');		
		this.signupMessageIconInfo = this.element.getElement('#signupMessageIconInfo');
		this.signupMessageIconError = this.element.getElement('#signupMessageIconError');
		this.signupMessageIconLoading = this.element.getElement('#signupMessageIconLoading');						
		this.signupMessageIcons = [this.signupMessageIconInfo, this.signupMessageIconOk, this.signupMessageIconError, this.signupMessageIconLoading];				

		this.signupCompany = this.signupForm.getElement('#signup_company');	
		this.signupAccount = this.signupForm.getElement('#signup_account');		
		this.signupEmail = this.signupForm.getElement('#signup_email');
		this.emailAvailableLoading = new Element('span', {'class':'signupEmailAvailableLoading'}).set('html', '&nbsp; &nbsp;').setStyle('background-position','-100px 0px').inject(this.signupEmail,'after');						
		this.signupPassword = this.signupForm.getElement('#signup_password');
		this.signupSecretQuestion = this.signupForm.getElement('#signup_secret_question'); // hidden
		this.signupSecretAnswer = this.signupForm.getElement('#signup_secret_answer');		
		this.signupSecretQuestionsDefault = this.signupForm.getElement('#signup_secret_questions_default');				
		this.signupSecretQuestionInputContainer = this.signupForm.getElement('#secret_question_input_container');
		this.signupSecretQuestionInput = this.signupForm.getElement('#signup_secret_question_input');
		
		this.signupBankAccountTypes = this.signupForm.getElements('input[type=radio][class~=signup_bank_account_type]');
		this.signupBankAccountNr = this.signupForm.getElement('#signup_bank_account_nr');
		this.signupBankAccountHolder = this.signupForm.getElement('#signup_bank_account_holder');	
		this.signupKvk = this.signupForm.getElement('#signup_kvk_nr');				
		
		this.signupAgree = this.signupForm.getElement('#signup_agree');

		
		this.signupHidden = this.signupForm.getElement('#signup_dosignup');
		this.signupFormkey = this.signupForm.getElement('#signup_formkey');		
		this.signupSubmit = this.signupForm.getElement('#signup_submit');
		// this.signupCancel = this.signupForm.getElement('#signup_cancel');		
		
		this.verifyHidden = this.verifyForm.getElement('#verify_doverify');
		this.verifyFormkey = this.verifyForm.getElement('#verify_formkey');
		this.verifyHash = this.verifyForm.getElement('#verify_hash');		
		
		
		this.signupMessageContinue = this.signupMessageForm.getElement('#signup_message_continue');
		this.signupMessageOk = this.signupMessageForm.getElement('#signup_message_ok');			

		this.signupCompany.store('errorIcon', document.id('signup_company_vicon'));
		this.signupAccount.store('errorIcon', document.id('signup_account_vicon'));		
		this.signupEmail.store('errorIcon', document.id('signup_email_vicon'));
		this.signupPassword.store('errorIcon', document.id('signup_password_vicon'));
		this.signupSecretAnswer.store('errorIcon', document.id('signup_secret_answer_vicon'));
		this.signupSecretQuestionInput.store('errorIcon', document.id('signup_secret_question_input_vicon'));

		this.signupBankAccountNr.store('errorIcon', document.id('signup_bank_account_nr_vicon'));
		this.signupBankAccountHolder.store('errorIcon', document.id('signup_bank_account_holder_vicon'));		
		this.signupKvk.store('errorIcon', document.id('signup_kvk_nr_vicon'));
		this.signupAgree.store('errorIcon', document.id('signup_agree_vicon'));		
		
		this.signupTermsLink = this.signupForm.getElement('#signup_terms');
		this.signupTermsElement = document.id('mmSignupTermsContainer');
		this.signupTermsContainer = this.signupTermsElement.getElement('#signupTermsContainer');
		this.signupTermsTop = this.signupTermsContainer.getElement('#signupTermsTop');		
		this.signupTermsBody = this.signupTermsContainer.getElement('#signupTermsBody');
		this.signupTermsContent = this.signupTermsContainer.getElement('#signupTermsContent');
		this.signupTermsClose = this.signupTermsContainer.getElement('#signup_terms_close');
		
		this.signupTabindex = [this.signupCompany, this.signupAccount, this.signupEmail ,this.signupPassword, this.signupSecretQuestionsDefault, this.signupSecretQuestionInput, this.signupSecretAnswer, this.signupBankAccountNr, this.signupBankAccountHolder, this.signupKvk, this.signupAgree, this.signupTermsLink, this.signupSubmit];		


	},
	setupEvents: function() {
// dbug.log('mm.SignupClass setupEvents');
		this.signupStrength = new mm.PasswordstrengthClass({container:this.signupForm.getElement('#signup_password_strength'), inputElement:this.signupPassword});				
		
		this.signupForm.addEvent('submit', function(e) { return false; });
		this.verifyForm.addEvent('submit', function(e) { return false; });		
		
		// opera needs keypress = tab preventDefault instead of doing this in keydown !
		if (Browser.Engine.presto) {
			this.signupTabindex.each(function(el) {
				el.addEvent('keypress', function(e) {
					if (e.key == 'tab') { e.preventDefault(); }
				});
			});	
		}		
		
		this.signupCompany.store('validators', [FormValidator.getValidator('minLength'), FormValidator.getValidator('required')]);		
		if (this.signupFormkey) { this.signupFormkeyOrg = this.signupFormkey.get('value'); }	
		this.signupEmail.store('validators', [FormValidator.getValidator('validate-email'), FormValidator.getValidator('required')]);		
		this.signupPasswordMask = new mm.PasswordmaskClass({inputElement:this.signupPassword});			
		this.signupAccountName = new mm.AccountnameClass({container:this.signupForm.getElement('#signup_account_name'), inputElement:this.signupAccount});			
		this.signupBankAccountHolder.store('validators', [FormValidator.getValidator('minLength'), FormValidator.getValidator('required')]);	
		this.signupSecretAnswer.store('validators', [FormValidator.getValidator('minLength'), FormValidator.getValidator('required')]);	
		this.signupSecretQuestionInput.store('validators', [FormValidator.getValidator('minLength'), FormValidator.getValidator('required')]);	
		this.signupKvk.store('validators', [FormValidator.getValidator('minLength'), FormValidator.getValidator('maxLength'), FormValidator.getValidator('validate-numeric'), FormValidator.getValidator('required')]);
		this.signupValidationFields = [this.signupEmail, this.signupCompany, this.signupSecretQuestionInput, this.signupSecretAnswer, this.signupBankAccountHolder, this.signupKvk];
			
				

		this.signupNoticeContainer.set('tween', {duration: this.options.noticeDuration, transition:this.options.noticeTransition, link:'chain', onComplete:function() { this.tweenNoticeComplete(); }.bind(this) });
		this.element.set('tween', {duration: this.options.tweenDuration, transition: this.options.tweenTransition, link:'ignore', onComplete:function() { this.tweenComplete(); }.bind(this) });
		this.signupInnerOverlay.set('tween', {duration: 'short', transition: 'sine:in:out', link:'ignore', onComplete:function() { this.tweenCompleteInnerOverlay(); }.bind(this) });		
		var signupLink = document.id('showSignupForm');
		if (signupLink) {
			signupLink.addEvent('click', function(e) {
				e.stop();
				this.resetForms();
				//this.signupFormContainer.setStyles({'display':'block'});
				this.displaySignupForm();
				this.open();
			}.bind(this));
		}		
		// this.signupCancel.addEvent('click', function(e) {
		// 	e.stop();
		// 	this.signupAccount.set('value', '');			
		// 	this.signupEmail.set('value', '');
		// 	this.signupPassword.set('value', '');						
		// 	this.modalHide();
		// }.bind(this));		
		this.signupSubmit.addEvent('click', function(e) {
			e.stop();
			this.submitSignupForm(e);
		}.bind(this));		
		

		this.signupAgree.addEvents({
			'click':function(e) {
				if (!this.signupAgree.get('checked')) {
					this.signupAgree.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'});
				} else {
					this.signupAgree.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px -24px'});								
					this.hideTip.delay(10,this.signupAgree.retrieve('errorIcon'));				
				}			
			}.bind(this)
			, 'keydown' : function(e) {
				if (e.key=='enter'||e.key=='space') {
					if (!this.signupAgree.get('checked')) {
						this.signupAgree.set('checked', true);
						this.signupAgree.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px -24px'});								
						this.hideTip.delay(10,this.signupAgree.retrieve('errorIcon'));
					} else {
						this.signupAgree.set('checked', false);						
						this.signupAgree.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'});
					}					
				}
			}.bind(this)
		});		

		
		
		this.signupTooltips = new mm.Tips('#mmSignupContainer .mmTooltip', {className:'mmTip', text: function(el){ return false; }, showDelay:this.options.tooltipDelays.show, hideDelay:this.options.tooltipDelays.hide});
		this.signupTooltips.addEvents({
			'show': function(tip, el){		
		    	tip.fade(1);
			},
			'hide': function(tip, el) {
				//tip.fade(0);
				tip.setStyle('opacity',0);
			}
		});	

		this.signupErrorTooltips = new mm.Tips('#mmSignupContainer .mmTooltipError', {className:'mmTipError', showDelay:1, hideDelay:0});
		this.signupErrorTooltips.addEvents({
			'show': function(tip, el){		
				// only show error tooltip when needed:
				if (el.getStyle('background-position') != '0px -24px') {
		    		tip.fade(1);
				}
			},
			'hide': function(tip, el) {
				//tip.fade(0);
				tip.setStyle('opacity',0);
			}
		});	
		
		
		this.bound.reposition = this.reposition.bind(this);		
		window.addEvent('resize', this.bound.reposition);
		this.signupAccount.addEvents({
			'keydown':this.keydown.bindWithEvent(this,this.signupAccount)
		});		
		this.signupCompany.addEvents({
			'keydown':this.keydown.bindWithEvent(this,this.signupCompany)
			, 'keyup': this.validateField.bind(this, this.signupCompany)
			, 'blur': this.validateField.bind(this, this.signupCompany)
			, 'change': this.validateField.bind(this, this.signupCompany)
		});		
		this.signupCompany.addEvent('blur', this.generateAccountNameFromCompany.bind(this));
		this.signupEmail.addEvents({
			'keydown':this.keydown.bindWithEvent(this,this.signupEmail)
			, 'keyup': this.validateField.bind(this, this.signupEmail)
			, 'blur': this.validateField.bind(this, this.signupEmail)
			, 'change': this.validateField.bind(this, this.signupEmail)
		});	
		this.signupEmail.addEvents({
			'keyup': this.checkEmailAvailable.bind(this)
			, 'blur': this.checkEmailAvailable.bind(this)
		});
		this.signupPassword.addEvent('keydown', this.keydown.bindWithEvent(this,this.signupPassword));
	
		
		this.signupSecretAnswer.addEvents({
			'keydown':this.keydown.bindWithEvent(this,this.signupSecretAnswer)			
			, 'keyup': this.validateField.bind(this, this.signupSecretAnswer)
			, 'blur': this.validateField.bind(this, this.signupSecretAnswer)
		});
		this.signupSecretQuestionInput.addEvents({
			'keydown': this.keydown.bindWithEvent(this, this.signupSecretQuestionInput)			
			, 'keyup': this.validateField.bind(this, this.signupSecretQuestionInput)
			, 'blur': this.validateField.bind(this, this.signupSecretQuestionInput)
		});		
		this.signupSecretQuestionInput.addEvents({
			'blur': function(e) {				
				this.signupSecretQuestion.set('value',this.signupSecretQuestionInput.get('value'));
			}.bind(this)
		});
						
		
		this.signupBankAccountHolder.addEvents({
			'keydown': this.keydown.bindWithEvent(this, this.signupBankAccountHolder)
			, 'keyup': this.validateField.bind(this, this.signupBankAccountHolder)
			, 'blur': this.validateField.bind(this, this.signupBankAccountHolder)
		});
		this.signupKvk.addEvents({
			'keydown': this.keydown.bindWithEvent(this, this.signupKvk)
			, 'keyup': this.validateField.bind(this, this.signupKvk)
			, 'blur': this.validateField.bind(this, this.signupKvk)
		});
		
		this.signupBankAccountTypes.each(function(btype) {
			btype.addEvent('click', function(e) { 
// dbug.log('btype click');				
				this.checkBankAccountNr();
// dbug.log('after checkbanknr');				
			}.bind(this));
		},this);		
		
		this.signupBankAccountNr.addEvents({
			'keydown' : this.keydown.bindWithEvent(this, this.signupBankAccountNr)
			, 'keyup': this.checkBankAccountNr.bind(this)
			, 'blur': this.checkBankAccountNr.bind(this)
		});		
		
		this.signupAgree.addEvent('keydown', this.keydown.bindWithEvent(this,this.signupAgree));		
		this.signupSubmit.addEvent('keydown', this.keydown.bindWithEvent(this,this.signupSubmit));		
		// this.signupCancel.addEvent('keydown', this.keydown.bindWithEvent(this,this.signupCancel));	
		
		this.signupSecretQuestionsDefault.addEvent('change', function(e) {
			e.stop();
			var secret = this.signupSecretQuestionsDefault.get('value');
			this.signupSecretQuestion.set('value',secret); 
			if (secret=='') {
				this.signupSecretQuestionInputContainer.setStyle('display','block');
			} else {
				this.signupSecretQuestionInputContainer.setStyle('display','none');
			}
		}.bind(this));
		
		// adding focus events: 
		[this.signupCompany, this.signupAccount, this.signupEmail, this.signupPassword, this.signupSecretQuestionInput, this.signupSecretAnswer, this.signupBankAccountNr, this.signupBankAccountHolder, this.signupKvk].each(function(input){
			input.store('inputFocus', new InputFocus(input, {focusedClass:'focused',hideOutline:true}));
			input.addEvents({
				'mousedown':this.hideTip.bind(input)
				,'focus':this.hideTip.bind(input)
				,'keydown':this.hideTip.bind(input)
			},this);
		},this);					
		if (this.signupTermsLink) {
			this.signupTermsLink.addEvent('click', this.showTerms.bindWithEvent(this));
			this.signupTermsLink.addEvent('keydown', this.keydown.bindWithEvent(this,this.signupTermsLink));			
			if (Browser.Engine.presto) {
				this.signupTermsLink.addEvent('keypress', function(e) {
					if (e.key=='enter' || e.key=='space') {
						e.preventDefault();
					}
				});
			}
		}		
		this.signupTermsClose.addEvent('click', this.hideTerms.bindWithEvent(this));	
		
		this.emailAvailableRequest = new Request.JSON({
			url: '/_x/emailavailable'
			, method: 'post'
			, link: 'cancel'
			, noCache: true
			, onSuccess: function(rJson, rText) {
				this.emailAvailableRequestSucces(rJson, rText);	//(rJson, rText);
			}.bind(this)
			, onRequest: function() {
				this.emailAvailableRequestStart();
			}.bind(this)
			, onFailure: function() {
				this.emailAvailableRequestFailure();
			}.bind(this)
		});			
		$clear(this.emailAvailableTimer);
		this.emailAvailableTimer = this.checkEmailAvailable.delay(500,this);		
	},
	hideTip: function() {
		if (this.retrieve('mmTip') && this.retrieve('mmTip').tip.getStyle('display') == 'block') { this.retrieve('mmTip').hide(this); }			
	},
	emailAvailableRequestStart:function() {
//dbug.log('emailAvailableRequestStart');	
		this.emailAvailableLoading.setStyle('background-position','center left');	
	},
	emailAvailableRequestFailure:function() {
		this.emailAvailableRequestEnd();		
	},
	emailAvailableRequestSucces:function(rJson, rText) {
// dbug.log(rJson);		
		this.emailAvailableRequestEnd();
		if (rJson.available) {
			this.signupEmail.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px -24px'});
			this.signupEmail.removeClass('validation-failed');
			this.signupEmail.store('emailAvailable', true);									
		} else {
			this.signupEmail.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'});			
			this.signupEmail.store('emailAvailable', false);
			this.signupEmail.addClass('validation-failed');		
		}
// dbug.log('signupEmail retrieve available = '+this.signupEmail.retrieve('emailAvailable'));		
	},
	emailAvailableRequestEnd:function() {
//dbug.log('emailAvailableRequestEnd');		
		this.emailAvailableLoading.setStyle('background-position','-100px 0px');
	},
	checkEmailAvailable:function() {
//dbug.log('checkEmailAvailable');		
		if (this.signupEmail.retrieve('isValid', false)) {
			this.emailAvailableRequest.cancel();
			this.emailAvailableRequest.send('checkemail='+this.signupEmail.get('value')+'&docheckemail='+1);			
		}
	},
	checkStatus:function(opening, extra) {
//dbug.log('checkStatus opening='+opening);
		if (!$defined(extra)) { extra = false; }
 		if (extra=='verify') {
//	if (!opening) { this.open.delay(500,this); }								
			this.displayVerifyForm();
			this.showNotice('loading',mm.lang.notice.verify_loading);
			this.submitVerifyForm.delay(500,this);
		} else if (extra=='loggedin') {
			this.displaySignupMessageForm();
		} else {
			this.displaySignupForm();
		}	
	},	
	checkBankAccountNr:function() {
		var value = 0;
		this.signupBankAccountTypes.each(function(btype, index) {
// dbug.log('radio	index='+index+' checked = '+btype.get('checked')+' value = '+btype.get('value'));		
			if (btype.get('checked')) {
				value = btype.get('value').toInt();
			}
		},this);
		var giro = false;
		if (value === 2) {
			// giro
			giro = true;
		} 
		var num = this.signupBankAccountNr.get('value');
		var hasLetters = num.test(/\D/);
		if (hasLetters) {
			num = num.replace(/\D/, "");		
			this.signupBankAccountNr.set('value', num);
		}
		var valid = mm.main.validateAccountNumber(num, giro);
		if (valid) {
			this.signupBankAccountNr.removeClass('validation-failed');
			this.signupBankAccountNr.retrieve('errorIcon').setStyles({'display':'block', 'background-position':'0px -24px'});
		} else {
			this.signupBankAccountNr.addClass('validation-failed');			
			this.signupBankAccountNr.retrieve('errorIcon').setStyles({'display':'block', 'background-position':'0px 0px'});			
		}
// dbug.log('checkBankAccountNr giro='+giro+' num='+num+' valid='+valid);		
	},
	showTerms: function(e) {
		e.stop();
//alert('terms and conditions: bla');	
//		overlaySize = this.overLay.getSize();
//		elSize = this.signupTermsElement.getDimensions();
//		this.signupTermsElement.setStyle('display','block').pin().setStyles({'top':((overlaySize.y/2)-(elSize.y/2))+'px','left':((overlaySize.x/2)-(elSize.x/2))+'px'});
//		this.getTerms();	
		mm.overlayAll.showPublicDialog('/terms');
	},
	hideTerms: function(e) {
		e.stop();
		this.signupTermsElement.setStyle('display', 'none');
	},	
	getTerms: function() {
		//this.signupTermsElement.setStyles({'display':'block'});
		this.termsRequest = new Request.HTML({
			url: '/_x/signupterms'
			, method: 'get'
			, link: 'ignore'			
			, noCache: true
			, onSuccess: function(rTree, rElements, rHtml, rJs)	{
				this.termsRequestSucces(rTree, rElements, rHtml, rJs);
			}.bind(this)
			/*
			, onSuccess: function(rJson, rText) {
				this.loginRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText]);
			}.bind(this)
			*/
			, onRequest: function() {
				this.termsRequestStart();
			}.bind(this)
			, onFailure: function() {
				this.termsRequestFailure();
			}.bind(this)
		}).send();
	},
	termsRequestStart:function() {
// dbug.log('termsRequestStart');		
	},
	termsRequestEnd:function() {
// dbug.log('termsRequestEnd');				
	},
	termsRequestSucces:function(rTree, rElements, rHtml, rJs){
// dbug.log('rTree ='+rTree);		
// dbug.log('rElements ='+rElements);
// dbug.log('rHtml ='+rHtml);
// dbug.log('rJs ='+rJs);
		this.termsRequestEnd();
		this.signupTermsContent.set('html', rHtml);
	},
	termsRequestFailure:function() {
		
	},
	resetForms: function() {
		this.signupInnerOverlay.setStyle('display','none');		
		this.signupAccountName.resetPreview();		
		this.signupAccount.set('value', '');		
		this.signupCompany.set('value', '').retrieve('errorIcon').setStyle('display','none');		
		this.signupEmail.set('value', '').retrieve('errorIcon').setStyle('display','none');		
		this.signupSecretQuestion.set('value', '');		
		this.signupSecretQuestionInput.set('value', '').retrieve('errorIcon').setStyle('display','none');				
		this.signupSecretAnswer.set('value', '').retrieve('errorIcon').setStyle('display','none');						
		this.signupBankAccountNr.set('value', '').retrieve('errorIcon').setStyle('display','none');						
		this.signupBankAccountHolder.set('value', '').retrieve('errorIcon').setStyle('display','none');	
		this.signupKvk.set('value', '').retrieve('errorIcon').setStyle('display','none');						
		this.signupPassword.set('value', '');		
		this.signupNoticeText.set('html', '');
		this.signupNoticeIcons.each(function(icon) {
			icon.setStyle('display','none');
		},this);		
	},
	keyup:function(e, el) {
		this.validateField(el);
	},	
	setFocusElement:function(el, back) {
// dbug.log('setNextFocusElement el.id:'+el.get('id'));		
		var curPos = 0;
		var elList = [];
		switch(this.curDisplayedForm) {
			case this.signupForm :
				elList = this.signupTabindex;
			break;
			case this.verifyForm :
				elList = this.verifyTabindex;
			break;			
		}		
		curPos = elList.indexOf(el);
		if (back) {
			nextEl = elList[curPos-1] || elList.getLast() || false;			
		} else {
			nextEl = elList[curPos+1] || elList[0] || false;
		}
// dbug.log('next el = '+nextEl.get('id'));				
		if (nextEl) { nextEl.focus(); }
	},	
	keydown:function(e, el) {
		e = new Event(e);

		// checking if field is typed:
		if (el==this.signupCompany ) { 
			this.signupTyped.set('company', true);
			this.signupCompany.set('value',this.signupCompany.get('value').replace('  ',' '));
		}				
		if (el==this.signupEmail ) { this.signupTyped.set('email', true); }
		if (el==this.signupSecretAnswer ) { this.signupTyped.set('secret_answer', true); }		
		if (el==this.signupBankAccountNr ) { this.signupTyped.set('bank_account_nr', true); }				
		if (el==this.signupBankAccountHolder ) { this.signupTyped.set('bank_account_holder', true); }						
		if (el==this.signupPassword ) { 
			if (e.key == 'space' || this.options.pwNotAllowed.contains(e.key)) { 
				e.stop();
			} else {
				this.signupTyped.set('password', true); 				
			}
		}
		if (el==this.signupTermsLink && (e.key=='enter' || e.key =='space')) { this.showTerms(e); }
		// setting hidden inputs
//dbug.log('typed compnay: '+this.signupTyped.get('company'));
// dbug.log('typed email: '+this.signupTyped.get('email'));
// dbug.log('typed password: '+this.signupTyped.get('password'));
// dbug.log('typed secret_answer: '+this.signupTyped.get('secret_answer'));
// dbug.log('typed bank_account_nr: '+this.signupTyped.get('bank_account_nr'));
// dbug.log('typed bank_account_holder: '+this.signupTyped.get('bank_account_holder'));		
		if (this.signupTyped.get('company') && this.signupTyped.get('email') && this.signupTyped.get('password') && this.signupTyped.get('secret_answer') && this.signupTyped.get('bank_account_nr') && this.signupTyped.get('bank_account_holder')) {
			this.signupHidden.set('value', 1);
// dbug.log('SIGNUPHIDDEN NOW = 1');			
		}		

//dbug.log('keydown key = '+e.key);		
		if (e.key == 'tab') {
//dbug.log('tab keydown on el.id:'+el.get('id')+' shift = '+e.shift);			
			e.preventDefault(); 
			if (e.shift) {
//				this.setFocusElement(el, true);
				this.setFocusElement.delay(50, this, [el, true]);
			} else {
//				this.setFocusElement(el, false);				
				this.setFocusElement.delay(50, this, [el, false]);				
//				e.preventDefault();
			}
			return false;
		}		
		
		if ((e.key=='enter' || e.key=='space')) {			
			var noSpacesEls = [this.signupCompany, this.signupSecretQuestionInput, this.signupSecretAnswer, this.signupBankAccountHolder, this.signupKvk];
			if (!noSpacesEls.contains(el)) { e.stop(); }
//			if (el!=this.signupCompany) { e.stop(); }
			if (el == this.signupSubmit) {
				e.stop();
				this.submitSignupForm(e);
			} 			
		}		

	},
	generateAccountNameFromCompany:function() {
		if (this.signupCompany.get('value')!='') {
			this.signupAccount.set('value',this.signupAccountName.clean(this.signupCompany.get('value')));
			this.signupAccountName.preview(); //.delay(10,this.signupAccountName);
// dbug.log('generateAccountNameFromCompany');		
		}
	},
	validateField:function(el) {
//dbug.log('validateField el='+el.get('id'));		
		var validators = el.retrieve('validators');
		var valid = true;
		if (validators) {
			validators.each(function(validator) {								
				if (!validator.test(el)) { valid = false; }
//dbug.log('validator:'+validator.className+' = '+validator.test(el));
			} );
		}
		if (valid) {			
			el.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px -24px'});
			el.retrieve('errorIcon').retrieve('mmTip').hide();
			if (el == this.signupEmail) { this.signupEmail.store('isValid', true); }
			el.removeClass('validation-failed');			
		} else {
			el.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'});
			if (el == this.signupEmail) { this.signupEmail.store('isValid', false); }			
			el.addClass('validation-failed');
		}
		return valid;
	},
	submitVerifyForm: function(e) {
		this.showInnerOverlay();				
		var qs = this.verifyForm.toQueryString();
		var qsdata = qs.parseQueryString(); 
		qsdata.formkey = qsdata.formkey * this.multiplier;
		if (qsdata.hash) {
			qsdata.hash = Base64.encode(qsdata.formkey+qsdata.hash+qsdata.formkey);
		}
// dbug.log(qsdata);
		
		new Request.JSON({
			url: '/_x/verify'
			, data: qsdata
			, method: 'post'
			, link: 'ignore'			
			, noCache: true
			, onSuccess: function(rJson, rText) {
				this.verifyRequestSucces.delay(500, this, [rJson, rText]);
			}.bind(this)
			, onRequest: function() {
				this.verifyRequestStart();
			}.bind(this)
			, onFailure: function() {
				this.verifyRequestFailure();
			}.bind(this)
		}).send();		
		
	},	
	checkEmptyFields: function() {
/*
		if (!this.signupAgree.get('checked')) { this.signupAgree.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }
		if (this.signupEmail.get('value')=='' || !this.signupTyped.get('email')) { this.signupEmail.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }
		if (this.signupPassword.get('value')=='' || !this.signupTyped.get('password')) { this.signupPassword.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }		
		if (this.signupAccount.get('value')=='') { this.signupAccount.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }				
		if (this.signupCompany.get('value')=='' || !this.signupTyped.get('company')) { this.signupCompany.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }
		if (this.signupSecretAnswer.get('value')=='' || !this.signupTyped.get('secret_answer')) { this.signupSecretAnswer.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }		
		if (this.signupBankAccountNr.get('value')=='' || !this.signupTyped.get('bank_account_nr')) { this.signupBankAccountNr.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }				
		if (this.signupBankAccountHolder.get('value')=='' || !this.signupTyped.get('bank_account_holder')) { this.signupBankAccountHolder.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }						
		if ((this.signupSecretQuestionsDefault.get('value')=='') && (this.signupSecretQuestionInput.get('value')=='')) { this.signupSecretQuestionInput.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }
*/
		if (!this.signupAgree.get('checked')) { this.signupAgree.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }
		if (this.signupEmail.get('value')=='' ) { this.signupEmail.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }
		if (this.signupPassword.get('value')=='' ) { this.signupPassword.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }		
		if (this.signupAccount.get('value')=='') { this.signupAccount.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }				
		if (this.signupCompany.get('value')=='' ) { this.signupCompany.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }
		if (this.signupSecretAnswer.get('value')=='' ) { this.signupSecretAnswer.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }		
		if (this.signupBankAccountNr.get('value')=='' ) { this.signupBankAccountNr.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }				
		if (this.signupBankAccountHolder.get('value')=='' ) { this.signupBankAccountHolder.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }						
		if ((this.signupSecretQuestionsDefault.get('value')=='') && (this.signupSecretQuestionInput.get('value')=='')) { this.signupSecretQuestionInput.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }		
//if (this.signupSecretQuestion.get('value')=='' ) { this.signupCompany.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'}); }								
		
	},
	submitSignupForm: function(e) {
		this.showInnerOverlay();
		/*
		if (!this.signupTyped.get('company') || !this.signupTyped.get('email') || !this.signupTyped.get('password') || !this.signupTyped.get('secret_answer') || !this.signupTyped.get('bank_account_nr') || !this.signupTyped.get('bank_account_holder')
			|| this.signupCompany.get('value')=='' 
			|| this.signupEmail.get('value')=='' || this.signupPassword.get('value')=='' || this.signupAccount.get('value') == '' || this.signupAgree.get('checked')==false
			|| this.signupBankAccountNr.get('value')=='' || this.signupBankAccountHolder.get('value')=='' || this.signupSecretAnswer.get('value') == '' || this.signupSecretQuestion.get('value')== ''
		) {
			this.checkEmptyFields();
			(function() { this.hideInnerOverlay(); }).delay(this.options.innerOverlayDelay, this);	
			this.showNotice('error', mm.lang.notice.no_input);	
			document.getElement('body').scrollTo(0,0);		
			return false;			
		}		
		*/
		if (this.signupCompany.get('value')=='' || this.signupEmail.get('value')=='' || this.signupPassword.get('value')=='' || this.signupAccount.get('value') == '' || this.signupAgree.get('checked')==false
			|| this.signupBankAccountNr.get('value')=='' || this.signupBankAccountHolder.get('value')=='' || this.signupKvk.get('value')=='' || this.signupSecretAnswer.get('value') == '' || this.signupSecretQuestion.get('value')== ''
		) {
			this.checkEmptyFields();
			(function() { this.hideInnerOverlay(); }).delay(this.options.innerOverlayDelay, this);	
			this.showNotice('error', mm.lang.notice.no_input);	
			document.getElement('body').scrollTo(0,0);		
			return false;			
		}		
		this.signupHidden.set('value',1);

		this.signupAccount.set('value', this.signupAccount.get('value').stripTags().clean());		
		this.signupEmail.set('value', this.signupEmail.get('value').stripTags().clean());
		this.signupPassword.set('value', this.signupPassword.get('value').stripTags().clean());		
		this.signupSecretQuestion.set('value', this.signupSecretQuestion.get('value').stripTags().clean());
		this.signupSecretAnswer.set('value', this.signupSecretAnswer.get('value').stripTags().clean());		
		this.signupBankAccountNr.set('value', this.signupBankAccountNr.get('value').stripTags().clean());		
		this.signupBankAccountHolder.set('value', this.signupBankAccountHolder.get('value').stripTags().clean());
		this.signupKvk.set('value', this.signupKvk.get('value').stripTags().clean());								
//this.signupHidden.get('value').toInt() !== 1
		if (!this.validateSignupForm() || !this.signupEmail.retrieve('emailAvailable',false) ) {
// dbug.log('validateSignupForm = '+this.validateSignupForm());
// dbug.log('signupHidden = '+this.signupHidden.get('value').toInt());
// dbug.log('emailAvailable = '+this.signupEmail.retrieve('emailAvailable',false));
			(function() { this.hideInnerOverlay(); }).delay(this.options.innerOverlayDelay, this);	
			this.showNotice('error', mm.lang.notice.validation_error);	
			this.showValidationErrors();		
			document.getElement('body').scrollTo(0,0);				
			return false;			
		}		
		var qs = this.signupForm.toQueryString();
		var qsdata = qs.parseQueryString(); 
		qsdata.formkey = qsdata.formkey * this.multiplier;
		qsdata.company = Base64.encode(qsdata.formkey+qsdata.company+qsdata.formkey);		
		qsdata.account = Base64.encode(qsdata.formkey+qsdata.account+qsdata.formkey);
		if (qsdata.account_real) {
			qsdata.account_real = Base64.encode(qsdata.formkey+qsdata.account_real+qsdata.formkey);
		}
		qsdata.email = Base64.encode(qsdata.formkey+qsdata.email+qsdata.formkey);
		qsdata.password = Base64.encode(qsdata.formkey+qsdata.password+qsdata.formkey);		
		qsdata.secret_question = Base64.encode(qsdata.formkey+qsdata.secret_question+qsdata.formkey);
		qsdata.secret_answer = Base64.encode(qsdata.formkey+qsdata.secret_answer+qsdata.formkey);		
		qsdata.bank_account_nr = Base64.encode(qsdata.formkey+qsdata.bank_account_nr+qsdata.formkey);		
		qsdata.bank_account_holder = Base64.encode(qsdata.formkey+qsdata.bank_account_holder+qsdata.formkey);
		qsdata.kvk_nr = Base64.encode(qsdata.formkey+qsdata.kvk_nr+qsdata.formkey);				
dbug.log(qsdata);
		document.getElement('body').scrollTo(0,0);	
		new Request.JSON({
			url: '/_x/signup'
			, data: qsdata
			, method: 'post'
			, link: 'ignore'			
			, noCache: true
			, onSuccess: function(rJson, rText) {
				this.signupRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText]);
			}.bind(this)
			, onRequest: function() {
				this.signupRequestStart();
			}.bind(this)
			, onFailure: function() {
				this.signupRequestFailure();
			}.bind(this)
		}).send();				
		
	},
	tweenNoticeComplete: function() {
		var opac = this.signupNoticeContainer.getStyle('opacity');
		if (opac == 0) {
			this.signupNoticeContainer.setStyle('display','none');
		}		
	},
	tweenComplete: function() {
		var opac = this.element.getStyle('opacity');
		if (opac == 0) {
			this.element.setStyle('display', 'none');
			this.isOpen = false;			
		}		
	},
	reposition:function() {
// dbug.log('reposition called');		
		if (!this.isOpen) { return false; }
//		overlaySize = this.overLay.getSize();
//		elSize = this.element.getSize();
//		this.element.pin().setStyles({'top':((overlaySize.y/2)-(elSize.y/2))+'px','left':((overlaySize.x/2)-(elSize.x/2))+'px'});
	},
	displaySignupForm:function() {
// dbug.log('displaySignupForm');		
		this.verifyFormContainer.setStyle('display','none');		
		this.signupFormContainer.setStyle('display','block');
		this.signupMessageFormContainer.setStyle('display','none');								
		this.curDisplayedForm = this.signupForm;		
		this.showNotice('info', mm.lang.notice.signup_info);
		// this.signupCompany.focus();
	},	
	displayVerifyForm:function() {
		this.verifyFormContainer.setStyle('display','block');						
		this.signupFormContainer.setStyle('display','none');		
		this.signupMessageFormContainer.setStyle('display','none');						
		this.curDisplayedForm = this.verifyForm;		
		this.showNotice('info', mm.lang.notice.verify_info);		
	},	
	displaySignupMessageForm: function() {
		this.signupMessageFormContainer.setStyle('display','block');		
		this.verifyFormContainer.setStyle('display','none');						
		this.signupFormContainer.setStyle('display','none');		
		this.curDisplayedForm = this.signupMessageForm;		
		
		if (mm.runtime.loggedin) {
			this.showNotice('info', mm.lang.notice.signup_loggedin);			
			this.showMessage('info', mm.lang.message.signup_loggedin);			
			this.signupMessageOk.addEvent('click', function(e) {
				e.stop();
				//this.modalHide();							
				window.location.href = '/signup?logout';
			}.bind(this));	
			this.signupMessageContinue.addEvent('click', function(e) {
				e.stop();
				window.location.href = mm.runtime.auth.portal;
			}.bind(this));

		}
	},
	open: function(extra) {
// dbug.log('mm.SignupClass open');
		if (!$defined(extra)) { extra = false; }
// dbug.log('extra = '+extra);			

		this.checkStatus(true, extra);
		this.isOpen = true;		
		//this.modalShow();		
//		this.overLay = document.id(this.options.modalOptions.layerId);				
		this.element.setStyles({'display':'block','opacity':0});
		this.reposition();
		this.element.fade('in');
	},	
	close:function() {
// dbug.log('mm.SignupClass close');		
		this.element.setStyles({'display':'block','opacity':1}).fade('out');		
	},
	validateVerifyForm: function() {
		var isValid = true;
		this.verifyValidationFields.each(function(field) {
			if (!this.validateField(field)) { isValid = false; }
		},this);
		return isValid;		
	},
	verifyRequestStart: function() {
		this.requestStart('verify');
	},	
	verifyRequestFailure: function() {
		
	},	
	verifyRequestSucces: function(rJson, rText) {
// dbug.log(rJson);
		//if (!rJson || !$defined(rJson.verify.verified)) { return false; }
		if(rJson.verify == true) {
// dbug.log('verified');			
			this.requestEnd();
			this.signupMessageOk.setStyle('display','none')			
			this.displaySignupMessageForm();
			this.showNotice('none','');
			this.showMessage('ok', mm.lang.message.verify_ok);

				this.signupMessageContinue.setStyle('display','block').addEvent('click', function(e) {
					e.stop();
					(function() { window.location.href = '/login'; }).delay(1000,this);
				}.bind(this));

		} else {
			this.requestEnd();
			this.showNotice('error', mm.lang.notice.verify_error);			
// dbug.log('not_verified');			
		}

	},	
	redirectVerified:function(portal)	{
		var rForm = new Element('form', {'method':'post', 'action':portal}).inject(this.element);
		rForm.set('send', {url:portal, method: 'post'});		
		var rHiddenKey = new Element('input', {'type':'hidden','name':'mmredirectedlogin'}).set('value',portal).inject(rForm);				
		rForm.submit();
	},
	validateSignupForm: function() {
		var isValid = true;
		this.signupValidationFields.each(function(field,index) {
// dbug.log('0validateSignupForm index='+index+' field = '+field.get('id'));
			if (field != this.signupSecretQuestionInput) {
				if (!this.validateField(field)) { 
					isValid = false; 
//dbug.log('^ = FALSE'); 
				}
			} else {
				if (this.signupSecretQuestionsDefault.get('value') == '') {
					if (!this.validateField(field)) { 
						isValid = false; 
//dbug.log('^ = FALSE'); 
					}					
				}
			}
		},this);
 // dbug.log('1validateSignupForm isValid='+isValid);		
		if (this.signupStrength.verdict != 'good' && this.signupStrength.verdict != 'strong') { isValid = false; }		
 // dbug.log('2validateSignupForm isValid='+isValid);		
		if (!this.signupAccountName.isAvailable) { isValid = false; }
 // dbug.log('3validateSignupForm isValid='+isValid+' account name is available ='+this.signupAccountName.isAvailable);
		return isValid;
	},	
	signupRequestStart: function() {
		this.requestStart('signup');		
	},
	signupRequestFailure: function() {
		
	},	
	signupRequestSucces: function(rJson, rText) {
dbug.log(rJson);		
		if (rJson.signup) {
			//this.requestEnd();
			var account_real = rJson.account_real;
			this.signupAccount.set('value','');			
			this.signupEmail.set('value','');
			this.signupPassword.set('value','');			
			this.signupAgree.set('checked', false);
			this.showNotice('ok', mm.lang.notice.signup_ok);							
			(function() { window.location.href = 'https://'+account_real+'.'+rJson.rootHost+'/app'; }).delay(1000,this);			
		} else {
			this.requestEnd();
			this.showNotice('error', mm.lang.notice.singup_error);
		}
	},	
	showInnerOverlay:function() {
		this.signupInnerOverlay.setStyles({'display':'block', 'opacity':0}).fade(this.options.innerOverlayOpacity);		
	}, 
	hideInnerOverlay:function() {
		//this.loginInnerOverlay.setStyles({'display':'none', 'opacity':0});				
		this.signupInnerOverlay.fade(0);
	},
	tweenCompleteInnerOverlay:function() {
		var opac = this.signupInnerOverlay.getStyle('opacity');
		if (opac == 0) { this.signupInnerOverlay.setStyle('display','none'); }
	},	
	requestStart:function(which) {
// dbug.log('requestStart');		
		this.showInnerOverlay();
		this.showNotice('loading', mm.lang.notice[which+'_loading']);
	},
	requestEnd:function() {
		this.hideInnerOverlay();	
	},	
	showValidationErrors: function() {
		//var error = this.signupNoticeContainer
	},	
	showMessage: function(mtype, message) {
		this.signupMessageContainer.setStyles({'display':'none', 'opacity':0});
		this.signupMessageIcons.each(function(icon) {
			icon.setStyle('display','none');
		},this);		
		switch(mtype) {
			case 'none' : 
			break;
			case 'ok' :
				this.signupMessageIconOk.setStyle('display','block');
			break; 
			case 'info' :
				this.signupMessageIconInfo.setStyle('display','block');
			break;			
		}
		this.signupMessageText.set('html', message);	
		this.signupMessageContainer.setStyles({'display':'block'}).fade('in');			
	},	
	showNotice:function(ntype, notice) {
		this.signupNoticeContainer.setStyles({'display':'none','opacity':0});
		this.signupNoticeIcons.each(function(icon) {
			icon.setStyle('display','none');
		},this);

		switch(ntype) {
			case 'none' :
				
			break;
			case 'info' :
				this.signupNoticeIconInfo.setStyle('display','block');
			break;
			case 'ok' :
				this.signupNoticeIconOk.setStyle('display','block');
			break;			
			case 'error' :
				this.signupNoticeIconError.setStyle('display','block');
			break;			
			case 'loading' :
				this.signupNoticeIconLoading.setStyle('display','block');
			break;			
		}
		this.signupNoticeText.set('html', notice);
		if (ntype=='loading') {
			this.signupNoticeContainer.setStyles({'display':'block','opacity':1,'visibility':'visible'});			
		} else {
			this.signupNoticeContainer.setStyles({'display':'block'}).fade('in');
		}
	}	
	
	
}); mm.LoginClass = new Class({
    Implements: [Options, Events],
    options : {
		requestType : false
		, loginContainer: 'mmLoginContainer'
		, tweenDuration: 500
		, tweenTransition: 'circ:in:out'
		, noticeDuration: 100
		, noticeTransition: 'circ:in'
		, multiplier: 1
		, pwNotAllowed : [' ','/','\\','>','<','"','\'']
		, ajaxDelay : 1200 	// extra ajax request delay added when request is succesfull (ms)
		, tooltipDelays : {show: 500, hide: 1}	
		, innerOverlayDelay : 800	
		, innerOverlayOpacity : 0.85
		 
	},
	initialize: function(options) {
		this.setOptions(options);	
		if (document.id(this.options.loginContainer)) {
			this.element = document.id(this.options.loginContainer);
		}
//dbug.log('login this elmeent id ='+this.element.get('id'));		
		this.requestType = this.options.requestType;
		//this.modalOptions = this.options.modalOptions;
//dbug.log('mm.LoginClass initialize');


		this.bound = this.bound||{};
		this.loginFormkeyOrg = '';
		this.forgotFormkeyOrg = '';
		this.newpassFormkeyOrg = '';				
		this.loginTyped = new Hash({'email':false, 'password':false});
		this.forgotTyped = new Hash({'email':false});	
		this.newpassTyped = new Hash({'password':false, 'confirm':false, 'secret_answer':false});			
		this.multiplier = this.options.multiplier;	
		this.curDisplayedForm = false;
		this.isOpen = false;
		this.loginTabindex = [];
		this.forgotTabindex = [];
		this.newpassTabindex = [];
		this.setupElements();
		this.setupEvents();
		this.checkStatus(false);	
	},
	setupElements:function() {
//dbug.log('mm.LoginClass setupElements');
		this.loginContainer = this.element.getElement('#loginContainer');
		this.loginInner = this.element.getElement('#loginInner');
		this.loginInnerOverlay = this.element.getElement('#loginInnerOverlay');
		this.loginClose = document.id('loginClose');
		this.loginNoticeContainer = this.element.getElement('#loginNoticeContainer');
		this.loginNoticeText = this.element.getElement('#loginNoticeText');		
		this.loginNoticeIconOk = this.element.getElement('#loginNoticeIconOk');		
		this.loginNoticeIconInfo = this.element.getElement('#loginNoticeIconInfo');
		this.loginNoticeIconError = this.element.getElement('#loginNoticeIconError');
		this.loginNoticeIconLoading = this.element.getElement('#loginNoticeIconLoading');						
		this.loginNoticeIcons = [this.loginNoticeIconInfo, this.loginNoticeIconOk, this.loginNoticeIconError, this.loginNoticeIconLoading];
		if (this.requestType !== 'portal') {
			this.loginSlideBtn = document.id('loginSlideButton');
		}
		
		this.loginForm = this.element.getElement('#loginForm');
		this.logoutForm = this.element.getElement('#logoutForm');		
		this.forgotForm = this.element.getElement('#forgotForm');	
		this.newpassForm = this.element.getElement('#newpassForm');			
		this.loginMessageForm = this.element.getElement('#loginMessageForm');		
		this.loginFormContainer = this.element.getElement('#loginFormContainer');	
		this.logoutFormContainer = this.element.getElement('#logoutFormContainer');			
		this.forgotFormContainer = this.element.getElement('#forgotFormContainer');	
		this.newpassFormContainer = this.element.getElement('#newpassFormContainer');				
		this.loginMessageFormContainer = this.element.getElement('#loginMessageFormContainer');		
		
		this.loginMessageContainer	= this.loginMessageForm.getElement('#loginMessageContainer');		
		this.loginMessageText = this.element.getElement('#loginMessageText');		
		this.loginMessageIconOk = this.element.getElement('#loginMessageIconOk');		
		this.loginMessageIconInfo = this.element.getElement('#loginMessageIconInfo');
		this.loginMessageIconError = this.element.getElement('#loginMessageIconError');
		this.loginMessageIconLoading = this.element.getElement('#loginMessageIconLoading');						
		this.loginMessageIcons = [this.loginMessageIconInfo, this.loginMessageIconOk, this.loginMessageIconError, this.loginMessageIconLoading];		

		this.loginEmail = this.loginForm.getElement('#login_email');
		this.loginPassword = this.loginForm.getElement('#login_password');
		
		this.loginHidden = this.loginForm.getElement('#login_dologin');
		this.loginRemember = this.loginForm.getElement('#login_remember');
		this.loginFormkey = this.loginForm.getElement('#login_formkey');
		this.loginForgotLink = this.element.getElement('#login_forgot');		
		this.loginSubmit = this.loginForm.getElement('#login_submit');
		// this.loginCancel = this.loginForm.getElement('#login_cancel');		

		this.loginEmail.store('errorIcon', document.id('login_email_vicon'));
		this.loginPassword.store('errorIcon', document.id('login_password_vicon'));		

		this.logoutSubmit = this.logoutForm.getElement('#logout_submit');
		// this.logoutCancel = this.logoutForm.getElement('#logout_cancel');		

		this.forgotEmail = this.forgotForm.getElement('#forgot_email');
		this.forgotHidden = this.forgotForm.getElement('#forgot_doforgot');		
		this.forgotFormkey = this.forgotForm.getElement('#forgot_formkey');	
		this.forgotUnique = this.forgotForm.getElement('#forgot_unique');			

		this.forgotSubmit = this.forgotForm.getElement('#forgot_submit');	
		this.forgotBack = this.forgotForm.getElement('#forgot_back');	
		// this.forgotCancel = this.forgotForm.getElement('#forgot_cancel');
		
		this.loginMessageContinue = this.loginMessageForm.getElement('#login_message_continue');						
		this.loginMessageOk = this.loginMessageForm.getElement('#login_message_ok');								
		
		this.forgotEmail.store('errorIcon', document.id('forgot_email_vicon'));

		this.newpassHidden = this.newpassForm.getElement('#newpass_donewpass');
		this.newpassFormkey = this.newpassForm.getElement('#newpass_formkey');	
		this.newpassAnswer = this.newpassForm.getElement('#newpass_secret_answer');
		this.newpassPassword = this.newpassForm.getElement('#newpass_password');			
		//this.newpassConfirm = this.newpassForm.getElement('#newpass_confirm');
		
		this.newpassAsnwerList = this.newpassForm.getElement('#newpass_secret_answer_list');
		this.newpassNewpassList = this.newpassForm.getElement('#newpass_newpass_list');
				
		this.newpassErrors = this.newpassForm.getElement('#newpassErrors');	
		this.newpassAnswerSubmit = this.newpassForm.getElement('#newpass_secret_answer_submit');
		this.newpassSubmit = this.newpassForm.getElement('#newpass_submit');		
		//  this.newpassCancel = this.newpassForm.getElement('#newpass_cancel');

		this.newpassPassword.store('errorIcon', document.id('newpass_password_vicon'));		
		this.newpassAnswer.store('errorIcon', document.id('newpass_secret_answer_vicon'));
		//this.newpassConfirm.store('errorIcon', document.id('newpass_confirm_vicon'));

		this.loginTabindex = [this.loginEmail, this.loginPassword, this.loginRemember, this.loginSubmit, this.loginForgotLink];
		this.forgotTabindex = [this.forgotEmail, this.forgotSubmit];
		this.newpassTabindex = [this.newpassAnswer, this.newpassAnswerSubmit, this.newpassPassword, this.newpassSubmit];
	},
	setupEvents:function() {
//dbug.log('mm.LoginClass setupEvents requestType = '+this.requestType);		
		this.slidePanel = document.id('subheaderLogin');
		this.bound.slideComplete = this.slideComplete.bind(this);
		this.bound.slidePanelClick = this.slidePanelClick.bindWithEvent(this);
		this.bound.closePanel = this.closePanel.bindWithEvent(this);
		this.slideFx = new Fx.Tween(this.slidePanel, {
			duration:this.options.tweenDuration
			, transition: this.options.tweenTransition
			, onComplete: this.bound.slideComplete
		});
		if (this.requestType !== 'portal') {		
			if (window.location.protocol !== 'https:') {
				this.loginSlideBtn.addEvent('click', function(e) {
					e.stop();
					window.location.href = 'https://'+window.location.hostname+'/login';
				});						
			} else {
// dbug.log('loginclass window location protocol:'+window.location.protocol);	
				if (mm.runtime.loggedin == true && mm.runtime.auth.username!='' && mm.runtime.auth.portal!='') {
					this.loginSlideBtn.addEvent('click', function(e) {
						e.stop();
						window.location.href = mm.runtime.auth.portal;
					});
				} else {
					this.loginSlideBtn.addEvent('click', this.bound.slidePanelClick);		
				}
			}
			this.slidePanel.addEvent('outerClick', function(e) { 
				if (this.isOpen) { 			
					// not stopping event bubbling, because otherwise no link would work anymore
					this.resetForms(); 
					this.loginSlideBtn.removeClass('active'); 	
					this.slidePanel.addEvent('click', this.bound.slidePanelClick); 
					this.close(); 
				}
			}.bind(this));
			this.loginClose.addEvent('click', this.bound.closePanel);			
			this.slidePanel.addEvent('click', this.bound.slidePanelClick);			
		} else {
			this.loginClose.hide();
			this.open();
		}

		this.newpassStrength = new mm.PasswordstrengthClass({container:this.newpassForm.getElement('#newpass_password_strength'), inputElement:this.newpassPassword});				
		// preventing default submits of the forms in some browsers:
		this.loginForm.addEvent('submit', function(e) { return false; });
		this.forgotForm.addEvent('submit', function(e) { return false; });		
		this.newpassForm.addEvent('submit', function(e) { return false; });				
		// opera needs keypress = tab preventDefault instead of doing this in keydown !
		if (Browser.Engine.presto) {
			this.loginTabindex.each(function(el) {
				el.addEvent('keypress', function(e) {
					if (e.key == 'tab') { e.preventDefault(); }
				});
			});	
			this.forgotTabindex.each(function(el) {
				el.addEvent('keypress', function(e) {
					if (e.key == 'tab') { e.preventDefault(); }
				});
			});		
			this.newpassTabindex.each(function(el) {
				el.addEvent('keypress', function(e) {
					if (e.key == 'tab') { e.preventDefault(); }
				});
			});				
		}
		//this.loginPasswordMask = new wm.PasswordmaskClass({inputElement:this.loginPassword});
		if (this.loginFormkey) { this.loginFormkeyOrg = this.loginFormkey.get('value'); }
		if (this.forgotFormkey) { this.forgotFormkeyOrg = this.forgotFormkey.get('value'); }
		if (this.newpassFormkey) { this.newpassFormkeyOrg = this.newpassFormkey.get('value'); }		

		this.loginEmail.store('validators', [FormValidator.getValidator('validate-email'), FormValidator.getValidator('required')]);
		this.loginPassword.store('validators', [FormValidator.getValidator('minLength'), FormValidator.getValidator('required')]);
		this.forgotEmail.store('validators', [FormValidator.getValidator('validate-email'), FormValidator.getValidator('required')]);
		//this.newpassPassword.store('validators', [FormValidator.getValidator('required'), FormValidator.getValidator('validate-wmpassword')]);
		this.newpassPasswordMask = new mm.PasswordmaskClass({inputElement:this.newpassPassword});

		this.loginValidationFields = [this.loginEmail, this.loginPassword];
		this.forgotValidationFields = [this.forgotEmail];
		//this.newpassValidationFields = [this.newpassPassword];
		this.loginNoticeContainer.set('tween', {duration: this.options.noticeDuration, transition:this.options.noticeTransition, link:'chain', onComplete:function() { this.tweenNoticeComplete(); }.bind(this) });
		this.loginMessageContainer.set('tween', {duration: this.options.noticeDuration, transition:this.options.noticeTransition, link:'chain', onComplete:function() { this.tweenMessageComplete(); }.bind(this) });		
		this.element.set('tween', {duration: this.options.tweenDuration, transition: this.options.tweenTransition, link:'ignore', onComplete:function() { this.tweenComplete(); }.bind(this) });
		this.loginInnerOverlay.set('tween', {duration: 350, transition: 'sine:in:out', link:'ignore', onComplete:function() { this.tweenCompleteInnerOverlay(); }.bind(this) });
		loginLink = document.id('showLoginForm');
		if (loginLink) {
			loginLink.addEvent('click', function(e) {
				e.stop();
// dbug.log('click');				
				this.resetForms();
				
				this.loginFormContainer.setStyles({'display':'block'});
				this.forgotFormContainer.setStyles({'display':'none'});				
				this.open();
			}.bind(this));
		}

		// this.loginCancel.addEvent('click', function(e) {
		// 	e.stop();
		// 	this.loginEmail.set('value', '');
		// 	this.loginPassword.set('value', '');			
		// 	this.forgotEmail.set('value', '');
		// 	this.loginRemember.set('checked', '');
		// 	this.modalHide();
		// }.bind(this));
		// 
		// this.forgotCancel.addEvent('click', function(e) {
		// 	e.stop();
		// 	this.resetForms();
		// 	this.modalHide();
		// }.bind(this));		
		// 
		// this.newpassCancel.addEvent('click', function(e) {
		// 	e.stop();
		// 	this.resetForms();
		// 	this.modalHide();
		// 	window.location.href = '/logout';			
		// }.bind(this));		

		this.loginSubmit.addEvent('click', function(e) {
			e.stop();
			this.submitLoginForm(e);
		}.bind(this));
		
		this.forgotSubmit.addEvent('click', function(e) {
			e.stop();
			this.submitForgotForm(e);
		}.bind(this));
		
		this.forgotBack.addEvent('click', function(e) {
			e.stop();
			this.displayLoginForm();			
		}.bind(this));
		
		this.newpassSubmit.addEvent('click', function(e) {
			e.stop();
			this.submitNewpassForm(e);
		}.bind(this));
		
		this.newpassAnswerSubmit.addEvent('click', function(e) {
			e.stop();
			this.submitNewpassAnswerForm(e);
		}.bind(this));		
		
		
		this.loginMessageOk.addEvent('click', function(e) {
			e.stop();
			this.resetForms();
			this.close();
		}.bind(this));		
		
		this.logoutSubmit.addEvent('click', function(e) {
			e.stop();
			this.resetForms();
			this.close();
			window.location.href = '/logout';			
		}.bind(this));
		
		// this.logoutCancel.addEvent('click', function(e) {
		// 	e.stop();
		// 	this.resetForms();
		// 	this.modalHide();
		// }.bind(this));		
			
		if (this.loginForgotLink) {
			this.loginForgotLink.addEvent('click', this.forgotPassword.bindWithEvent(this));
			if (Browser.Engine.presto) {
				this.loginForgotLink.addEvent('keypress', function(e) {
					if (e.key=='enter' || e.key=='space') {
						e.preventDefault();
					}
				});
			}			
		}
		

		this.loginTooltips = new mm.Tips('#mmLoginContainer .mmTooltip', {className:'mmTip', text: function(el){ return false; }, showDelay:this.options.tooltipDelays.show, hideDelay:this.options.tooltipDelays.hide});
		this.loginTooltips.addEvents({
			'show': function(tip, el){		
		    	tip.fade(1);
			},
			'hide': function(tip, el) {
				//tip.fade(0);
				tip.setStyle('opacity',0);
			}
		});		
		
		this.loginErrorTooltips = new mm.Tips('#mmLoginContainer .mmTooltipError', {className:'mmTipError', showDelay:1, hideDelay:0});
		this.loginErrorTooltips.addEvents({
			'show': function(tip, el){		
				if (el.getStyle('background-position') != '0px 24px') {
		    		tip.fade(1);
				}
			},
			'hide': function(tip, el) {
				//tip.fade(0);
				tip.setStyle('opacity',0);
			}
		});		


		this.bound.reposition = this.reposition.bind(this);		
		window.addEvent('resize', this.bound.reposition);		
		this.loginEmail.addEvents({
			'keydown':this.keydown.bindWithEvent(this,this.loginEmail)
			//, 'keyup': this.validateField.bind(this, this.loginEmail)
			//, 'blur': this.validateField.bind(this, this.loginEmail)
			//, 'change': this.validateField.bind(this, this.loginEmail)
		});	
		
		this.loginPassword.addEvent('keydown', this.keydown.bindWithEvent(this,this.loginPassword));					
		//this.loginPassword.addEvent('keyup', this.validateField.bind(this, this.loginPassword));	
		//this.loginPassword.addEvent('blur', this.validateField.bind(this, this.loginPassword));	
		//this.loginPassword.addEvent('change', this.validateField.bind(this, this.loginPassword));			

		this.forgotEmail.addEvent('keydown', this.keydown.bindWithEvent(this,this.forgotEmail));			
		//this.forgotEmail.addEvent('keyup', this.validateField.bind(this, this.forgotEmail));	
		//this.forgotEmail.addEvent('blur', this.validateField.bind(this, this.forgotEmail));
		//this.forgotEmail.addEvent('change', this.validateField.bind(this, this.forgotEmail));		

		this.forgotSubmit.addEvent('keydown', this.keydown.bindWithEvent(this,this.forgotSubmit));

		this.newpassPassword.addEvent('keydown', this.keydown.bindWithEvent(this,this.newpassPassword));			
		this.newpassAnswer.addEvent('keydown', this.keydown.bindWithEvent(this, this.newpassAnswer));
		this.loginRemember.addEvent('keydown', this.keydown.bindWithEvent(this, this.loginRemember));		
		this.loginSubmit.addEvent('keydown', this.keydown.bindWithEvent(this, this.loginSubmit));		
		this.loginForgotLink.addEvent('keydown', this.keydown.bindWithEvent(this, this.loginForgotLink));	
		
		this.newpassSubmit.addEvent('keydown', this.keydown.bindWithEvent(this,this.newpassSubmit));					
					
		this.newpassAnswerSubmit.addEvent('keydown', this.keydown.bindWithEvent(this, this.newpassAnswerSubmit));
					
		//this.newpassPassword.addEvent('keyup', this.validateField.bind(this, this.newpassPassword));	
		//this.newpassPassword.addEvent('blur', this.validateField.bind(this, this.newpassPassword));	
		//this.newpassPassword.addEvent('change', this.validateField.bind(this, this.newpassPassword));
		
		// this.newpassConfirm.addEvent('keydown', this.keydown.bindWithEvent(this,this.newpassConfirm));					
		// this.newpassConfirm.addEvent('keyup', this.validateField.bind(this, this.newpassConfirm));	
		// this.newpassConfirm.addEvent('blur', this.validateField.bind(this, this.newpassConfirm));	
		// this.newpassConfirm.addEvent('change', this.validateField.bind(this, this.newpassConfirm));					

		
		// adding focus events: 
		[this.loginEmail, this.loginPassword, this.forgotEmail, this.newpassPassword, this.newpassAnswer].each(function(input){
			input.store('inputFocus', new InputFocus(input, {focusedClass:'focused',hideOutline:true}));
/*
			input.addEvent('focus', function() {
				var tip =  this.retrieve('wmTip');
				if (tip) { tip.hide(this); }				
			}.bind(input));*/
			input.addEvents({
				'mousedown':this.hideTip.bind(input)
				,'focus':this.hideTip.bind(input)
				,'keydown':this.hideTip.bind(input)
			},this);
		},this);
				
	},
	closePanel: function(e) {
		//
		if (this.isOpen) { 			
			e.stop();			
			this.resetForms(); 
			this.loginSlideBtn.removeClass('active'); 	
			this.slidePanel.addEvent('click', this.bound.slidePanelClick); 
			this.close(); 
		}		
	}, 
	slidePanelClick: function(e) {
		e.stop();
		if (this.isOpen) {
			this.close();
			this.resetForms();				
			this.loginSlideBtn.removeClass('active');
			this.slidePanel.addEvent('click', this.bound.slidePanelClick);
		} else {
			this.open(); 				
		}
	},
	showSlideButtons: function() {
		this.loginSlideBtn.setStyle('display',this.loginSlideBtn.retrieve('old_display'));
		this.signupSlideBtn.setStyle('display',this.signupSlideBtn.retrieve('old_display'));
	},
	hideSlideButtons: function() {
		this.loginSlideBtn.store('old_display',this.loginSlideBtn.getStyle('display')).setStyle('display','none'); 
		this.signupSlideBtn.store('old_display',this.signupSlideBtn.getStyle('display')).setStyle('display','none');
	},
	slideToggle:function() {
//dbug.log('slideToggle');		
		var mtop = this.slidePanel.getStyle('margin-top').toInt();
		if (mtop == -240) {
			this.slideFx.start('margin-top', 0);
		} else {
			this.slideFx.start('margin-top', -240);			
		}
	},
	hideTip:function() {
		if (this.retrieve('mmTip') && this.retrieve('mmTip').tip.getStyle('display') == 'block') { this.retrieve('mmTip').hide(this); }		
	},
	resetForms:function() {
		this.loginInnerOverlay.setStyle('display','none');
		
		this.loginEmail.set('value', '').retrieve('errorIcon').setStyle('display','none');
		this.loginPassword.set('value', '').retrieve('errorIcon').setStyle('display','none');
		this.loginRemember.set('checked', '');
		
		this.forgotEmail.set('value', '').retrieve('errorIcon').setStyle('display','none');		
		this.newpassPassword.set('value', '');

//		this.newpassConfirm.set('html', '').retrieve('errorIcon').setStyle('display','none');
		
		this.forgotSubmit.setStyle('display','block');
		this.newpassSubmit.setStyle('display','block');
		// this.forgotCancel.setStyle('display','block');
		// this.newpassCancel.setStyle('display','block');						
		
		this.loginNoticeText.set('html', '');
		this.loginNoticeIcons.each(function(icon) {
			icon.setStyle('display','none');
		},this);
	},
	keyup:function(e, el) {
		this.validateField(el);
	},	
	validateField:function(el) {
		var validators = el.retrieve('validators');
		var valid = true;
		if (validators) {
			validators.each(function(validator) {								
				if (!validator.test(el)) { valid = false; }
//dbug.log('validator:'+validator.className+' = '+validator.test(el));
			} );
		}
		if (el==this.newpassPassword) {
			if (this.newpassStrength.verdict != 'good' && this.newpassStrength.verdict != 'strong') { valid = false; }			
		}
		if (valid) {
			el.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 24px'});
			el.retrieve('errorIcon').retrieve('mmTip').hide();
		} else {
			el.retrieve('errorIcon').setStyles({'display':'block','background-position':'0px 0px'});
		}
		return valid;
	},	
	setFocusElement:function(el, back) {
// dbug.log('setFocusElement el.id:'+el.get('id'));	
		var curPos = 0;
		var elList = [];
		switch(this.curDisplayedForm) {
			case this.loginForm :
				elList = this.loginTabindex;
			break;
			case this.forgotForm : 
				elList = this.forgotTabindex;
			break;
			case this.newpassForm : 
				elList = this.newpassTabindex;
			break;			
		}		
		curPos = elList.indexOf(el);
		if (back) {
			nextEl = elList[curPos-1] || elList.getLast() || false;			
		} else {
			nextEl = elList[curPos+1] || elList[0] || false;
		}
// dbug.log('next el = '+nextEl.get('id'));
		if (nextEl) { nextEl.focus(); }
	},	
	keydown:function(e, el) {
		e = new Event(e);
		
		// checking if field is typed:
		if (el==this.loginEmail ) { this.loginTyped.set('email', true); }
		if (el==this.loginPassword ) { 
			if (e.key == 'space' || this.options.pwNotAllowed.contains(e.key)) { 
				e.stop();
			} else {
				/*
dbug.log('password key = '+e.key +' code ='+e.code +' char = '+String.fromCharCode(e.code) );						
				if (e.key != 'space' && e.key != 'backspace' && e.key != 'enter') { // && e.key != 'up' && e.key != 'down' && e.key != 'left' && e.key != 'right' && e.key != 'delete' && e.key != 'esc') {
					this.showLoginPasswordChar(String.fromCharCode(escape(e.code)));				
					this.clearLoginPasswordChar.delay(800,this);
				}
				*/
				this.loginTyped.set('password', true); 				
			}
		}

		if (el==this.forgotEmail) { this.forgotTyped.set('email',true); }
		
		if (el==this.newpassPassword) { this.newpassTyped.set('password',true); }
		if (el == this.newpassAnswer) { this.newpassTyped.set('secret_answer', true); }
		//if (el==this.newpassConfirm) { this.newpassTyped.set('confirm',true); }		


		// setting hidden inputs
		if (this.loginTyped.get('email') && this.loginTyped.get('password')) {
			//this
			// change loginformkey to something checkable in php (base64)
			this.loginHidden.set('value', 1);
		}		
		if (this.forgotTyped.get('email')) { this.forgotHidden.set('value',1); }
		if (this.newpassTyped.get('password')) {		
			this.newpassHidden.set('value',1);
		}
		
		if (e.key == 'tab') {
// dbug.log('tab keydown on el.id:'+el.get('id')+' shift = '+e.shift);	
			e.stop(); 
			if (e.shift) {
//				this.setFocusElement(el, true);
				this.setFocusElement.delay(50, this, [el, true]);				
			} else {
//				this.setFocusElement(el, false);				
				this.setFocusElement.delay(50, this, [el, false]);				
			}
			return false;
		}
				
		if ((e.key=='enter' || e.key=='space') ) {
			if (el != this.newpassAnswer) {
				e.stop();
			}
			if (el == this.loginSubmit) {
				e.stop();
				this.submitLoginForm(e);
			} else if (el == this.forgotSubmit) {
				e.stop();
				this.submitForgotForm(e);				
			} else if (el == this.newpassSubmit) {
				e.stop();
				this.submitNewpassForm(e);				
			} else if (el == this.newpassAnswerSubmit) {
				e.stop();
				this.submitNewpassAnswerForm(e);
			} else if (el == this.loginForgotLink) {
				this.forgotPassword(e);
			}
			
			if (e.key=='enter' && el==this.loginPassword) {
				e.stop();
				if (this.loginEmail.get('value') != '' && this.loginPassword.get('value') != '') {
					this.submitLoginForm();
				}
			} else if (e.key=='enter' && el==this.forgotEmail) {
				e.stop();
				if (this.forgotEmail.get('value') != '') {
					this.forgotTyped.set('email',true);
					this.forgotHidden.set('value',1);					
					//this.submitForgotForm();
				}
			} else if (e.key=='enter' && el==this.newpassPassword) {
				e.stop();
				if (this.newpassPassword.get('value') != '') {
					this.newpassTyped.set('password',true);					
					this.newpassHidden.set('value',1);
					//this.submitNewpassForm();
				}				
			}

		} 	
		/*
		if (e.key == 'enter' && (el==this.loginEmail || el==this.loginPassword)) {
			e.stop();
			this.submitLoginForm(e);
		} else if (e.key=='enter' && el==this.forgotEmail) {
			e.stop();
			this.submitForgotForm(e);
		} else if (e.key == 'enter' && (el==this.newpassPassword)) {	
			e.stop();
			this.submitNewpassForm(e);
		}
		*/
//dbug.log(el.get('id'));		

	},
	forgotPassword:function(e) {
		e.stop();
// dbug.log('forgotlink clicked');	
		this.displayForgotForm();		
		
	},	
	slideComplete: function() {
		var mtop = this.slidePanel.getStyle('margin-top').toInt();
		if (mtop != 0) {
			//this.showSlideButtons();			
		} 
	},
	tweenComplete: function() {
		var opac = this.element.getStyle('opacity');
		if (opac == 0) {
			this.element.setStyle('display', 'none');
			this.isOpen = false;			
		} 
	},
	tweenNoticeComplete: function () {
		var opac = this.loginNoticeContainer.getStyle('opacity');
		if (opac == 0) {
			this.loginNoticeContainer.setStyle('display','none');
		} 
	},	
	tweenMessageComplete: function () {
		var opac = this.loginMessageContainer.getStyle('opacity');
		if (opac == 0) {
			this.loginMessageContainer.setStyle('display','none');
		} 
	},	
	checkStatus:function(opening, extra) {
		if (!$defined(extra)) { extra = false; }
// dbug.log('checkStatus opening='+opening+' extra ='+extra);		
		if (extra == 'newpass') {
			this.displayNewpassForm();
			if (!opening) { this.open.delay(500,this); }
		} else if (extra !== false) {
			this.displayLoginForm();
			var logindetails = JSON.decode(Base64.decode(extra));
			if ($type(logindetails)=='array') {
// dbug.log('is array');
				this.showNotice('info', mm.lang.notice.login_nosession_info);
				this.loginEmail.set('value', logindetails[0]);
				//this.loginPassword.set('value', logindetails[1]);
				this.loginPassword.focus.delay(800,this.loginPassword);
				this.loginTyped.set('email',true); 
				//this.submitLoginForm();
			}
// dbug.log(logindetails);			
		} else {
			if (mm.runtime.loggedin) {
				this.displayLogoutForm();
			} else {
				this.displayLoginForm();				
			}
		} 
	},
	displayLoginMessageForm:function() {
		this.loginMessageFormContainer.setStyle('display','block');						
		this.logoutFormContainer.setStyle('display','none');		
		this.loginFormContainer.setStyle('display','none');
		this.forgotFormContainer.setStyle('display','none');
		this.newpassFormContainer.setStyle('display','none');

		this.curDisplayedForm = this.loginMessageForm;
		
	},	
	displayLogoutForm:function() {
		this.logoutFormContainer.setStyle('display','block');	
		this.loginMessageFormContainer.setStyle('display','none');			
		this.loginFormContainer.setStyle('display','none');
		this.forgotFormContainer.setStyle('display','none');
		this.newpassFormContainer.setStyle('display','none');
		this.showNotice('info', mm.lang.notice.logout_info);	
		var portalUrl = '';
		if (mm.runtime.auth.portal) {
			portalUrl = '<a href="'+mm.runtime.auth.portal+'">'+mm.runtime.auth.portal+'</a>';
		}
		var portalLink = portalUrl;
		this.logoutForm.getElement('#logoutFormPortalNotice').set('html', portalLink);
		this.curDisplayedForm = this.logoutForm;
		
	},
	displayLoginForm:function() {
// dbug.log('displayLoginForm');		
		this.logoutFormContainer.setStyle('display','none');		
		this.loginFormContainer.setStyle('display','block');
		this.loginMessageFormContainer.setStyle('display','none');					
		this.forgotFormContainer.setStyle('display','none');
		this.newpassFormContainer.setStyle('display','none');		
		this.curDisplayedForm = this.loginForm;		
		this.showNotice('info', mm.lang.notice.login_info);
		//this.loginEmail.focus.delay(150,this.loginEmail);
		this.loginEmail.addClass('focused').focus();
	},
	displayForgotForm:function() {
		this.logoutFormContainer.setStyle('display','none');		
		this.loginFormContainer.setStyle('display','none');
		this.loginMessageFormContainer.setStyle('display','none');					
		this.forgotFormContainer.setStyle('display','block');
		this.newpassFormContainer.setStyle('display','none');		
		this.curDisplayedForm = this.forgotForm;	
		this.showNotice('info', mm.lang.notice.forgot_info);		
		this.forgotEmail.focus();			
	},
	displayNewpassForm:function() {
		this.logoutFormContainer.setStyle('display','none');		
		this.loginFormContainer.setStyle('display','none');
		this.loginMessageFormContainer.setStyle('display','none');					
		this.forgotFormContainer.setStyle('display','none');
		this.newpassFormContainer.setStyle('display','block');

		this.curDisplayedForm = this.newpassForm;	
		this.showNotice('info', mm.lang.notice.newpass_answer_info);		

	},
	open: function(extra) {
		if (!$defined(extra)) { extra = false; }
		this.checkStatus(true, extra);				
		this.isOpen = true;					
		if (this.requestType !== 'portal') {			
			this.loginSlideBtn.addClass('active');	
		}							
		this.slidePanel.removeEvent('click', this.bound.slidePanelClick);			
		this.slideFx.start('margin-top', 0);		
//		this.element.setStyles({'display':'block','opacity':0});
//		this.reposition();
//		this.element.fade('in'); 

	},
	reposition:function() {
// dbug.log('reposition called');		
		// if (!this.isOpen) { return false; }
		// overlaySize = this.overLay.getSize();
		// elSize = this.element.getSize();
		// this.element.pin().setStyles({'top':((overlaySize.y/2)-(elSize.y/2))+'px','left':((overlaySize.x/2)-(elSize.x/2))+'px'});
	},
	close:function() {
// dbug.log('mm.LoginClass close');		
		//this.element.setStyles({'display':'block','opacity':1}).fade('out');
		this.slideFx.start('margin-top', -320); 	// -300
		this.isOpen = false;
		//	this.element.dissolve();
	},
	
	validateLoginForm: function() {
		var isValid = true;
		this.loginValidationFields.each(function(field) {
			if (!this.validateField(field)) { isValid = false; }
		},this);
		return isValid;
	},
	validateForgotForm: function() {
		var isValid = true;
		this.forgotValidationFields.each(function(field) {
			if (!this.validateField(field)) { isValid = false; }
		},this);
		return isValid;
	},	
	validateNewpassForm: function() {
		var isValid = true;
/*		
		this.newpassValidationFields.each(function(field) {
			if (!this.validateField(field)) { isValid = false; }
		},this);
*/		
		if (this.newpassStrength.verdict != 'good' && this.newpassStrength.verdict != 'strong') { isValid = false; }
		return isValid;
	},
	
	submitLoginForm: function(e) {
		this.showInnerOverlay();
/*
		if (!this.loginTyped.get('email') || !this.loginTyped.get('password') || this.loginEmail.get('value')=='' || this.loginPassword.get('value')=='') {
//alert('no spam entrance');
			this.showNotice('error', mm.lang.notice.no_input);			
			(function() { this.hideInnerOverlay(); }).delay(this.options.innerOverlayDelay, this);	
			if (!this.loginTyped.get('email') || this.loginEmail.get('value')=='' || !this.validateField(this.loginEmail)) { 
				this.loginEmail.retrieve('errorIcon').setStyle.delay(this.options.innerOverlayDelay-50, this.loginEmail.retrieve('errorIcon'), ['display','block']); 
			}
			if (!this.loginTyped.get('password') || this.loginPassword.get('value')=='' || !this.validateField(this.loginPassword)) { 
				this.loginPassword.retrieve('errorIcon').setStyle.delay(this.options.innerOverlayDelay-50, this.loginPassword.retrieve('errorIcon'), ['display','block']); 
			}			
			return false;			
		}		*/

		if (this.loginEmail.get('value')=='' || this.loginPassword.get('value')=='') {
			this.showNotice('error', mm.lang.notice.no_input);			
			(function() { this.hideInnerOverlay(); }).delay(this.options.innerOverlayDelay, this);	
			if (this.loginEmail.get('value')=='' || !this.validateField(this.loginEmail)) { 
				this.loginEmail.retrieve('errorIcon').setStyle.delay(this.options.innerOverlayDelay-50, this.loginEmail.retrieve('errorIcon'), ['display','block']); 
			}
			if (this.loginPassword.get('value')=='' || !this.validateField(this.loginPassword)) { 
				this.loginPassword.retrieve('errorIcon').setStyle.delay(this.options.innerOverlayDelay-50, this.loginPassword.retrieve('errorIcon'), ['display','block']); 
			}			
			return false;			
		}		
		this.loginHidden.set('value',1);
		this.loginEmail.set('value', this.loginEmail.get('value').stripTags().clean());
		this.loginPassword.set('value', this.loginPassword.get('value').stripTags().clean());		
		if (!this.validateLoginForm() || this.loginHidden.get('value').toInt() !== 1) {
//alert('error validating form');
			this.showNotice('error', mm.lang.notice.validation_error);			
			(function() { this.hideInnerOverlay(); }).delay(this.options.innerOverlayDelay, this);					
			return false;			
		}		

		var qs = this.loginForm.toQueryString();

		var qsdata = qs.parseQueryString();
// dbug.log('LOGIN FORM: FORMKEY = '+qsdata.formkey.toInt()+' MULTIPLIER = '+this.multiplier.toInt() + ' data formkey = '+(qsdata.formkey.toInt() * this.multiplier.toInt()));		
		qsdata.formkey = qsdata.formkey.toInt() * this.multiplier.toInt();
		qsdata.email = Base64.encode(qsdata.formkey+qsdata.email+qsdata.formkey);
		qsdata.password = Base64.encode(qsdata.formkey+qsdata.password+qsdata.formkey);		
// dbug.log(qsdata);

		new Request.JSON({
			url: '/_x/login'
			, data: qsdata
			, method: 'post'
			, link: 'ignore'			
			, noCache: true
			, onSuccess: function(rJson, rText) {
				this.loginRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText]);
			}.bind(this)
			, onRequest: function() {
				this.loginRequestStart();
			}.bind(this)
			, onFailuer: function() {
				this.loginRequestFailure();
			}.bind(this)
		}).send();		

	},
	
	submitForgotForm:function(e) {		
		this.showInnerOverlay();
		if (!this.forgotTyped.get('email') || this.forgotEmail.get('value')=='') {
			this.forgotEmail.retrieve('errorIcon').setStyle.delay(this.options.innerOverlayDelay-50, this.forgotEmail.retrieve('errorIcon'), ['display','block']); 
			this.showNotice('error', mm.lang.notice.no_input);	
			(function() { this.hideInnerOverlay(); }).delay(this.options.innerOverlayDelay, this);												
			return false;			
		}	
		this.forgotEmail.set('value', this.forgotEmail.get('value').stripTags().clean());			
		if (!this.validateForgotForm() || this.forgotHidden.get('value').toInt() !== 1) {
//alert('error validating form');
			this.showNotice('error', mm.lang.notice.validation_error);
			(function() { this.hideInnerOverlay(); }).delay(this.options.innerOverlayDelay, this);							
			return false;			
		}		
		var qs = this.forgotForm.toQueryString();
		var qsdata = qs.parseQueryString();
		qsdata.formkey = qsdata.formkey * this.multiplier;		
		qsdata.email = Base64.encode(qsdata.formkey+qsdata.email+qsdata.formkey);
		if (qsdata.unique) {
			qsdata.unique = Base64.encode(qsdata.formkey+qsdata.unique+qsdata.formkey);			
		}
// dbug.log(qsdata);

		new Request.JSON({
			url: '/_x/forgot'
			, data: qsdata
			, method: 'post'
			, link: 'ignore'
			, noCache: true
			, onSuccess: function(rJson, rText) {
				this.forgotRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText]);	//(rJson, rText);
			}.bind(this)
			, onRequest: function() {
				this.forgotRequestStart();
			}.bind(this)
			, onFailuer: function() {
				this.forgotRequestFailure();
			}.bind(this)
		}).send();		
	},

	submitNewpassAnswerForm:function(e) {
		this.showInnerOverlay();
		if (!this.newpassTyped.get('secret_answer') || this.newpassAnswer.get('value').length < 6) {
			this.showNotice('error', mm.lang.notice.no_input);		
			(function() { this.hideInnerOverlay(); }).delay(this.options.innerOverlayDelay, this);											
			return false;			
		}
		var qs = this.newpassForm.toQueryString();
		var qsdata = qs.parseQueryString(); 
// dbug.log(qsdata);		
		qsdata.formkey = qsdata.formkey * this.multiplier;		
		qsdata.secret_answer = Base64.encode(qsdata.formkey+qsdata.secret_answer+qsdata.formkey);
		//qsdata_hash = Base64.encode(qsdata.formkey+qsdata.hash+qsdata.formkey);  // no encoding of token, doesn't work
// dbug.log(qsdata);

		new Request.JSON({
			url: '/_x/newpassanswer'
			, data: qsdata
			, method: 'post'
			, link: 'ignore'
			, noCache: true
			, onSuccess: function(rJson, rText) {
				//this.hideInnerOverlay();				
				this.newpassAnswerRequestSucces.delay(500, this, [rJson, rText]);	//(rJson, rText);
			}.bind(this)
			, onRequest: function() {
				//this.newpassRequestStart();
				this.requestStart('newpassanswer');
			}.bind(this)
			, onFailuer: function() {
				this.newpassRequestFailure();
			}.bind(this)
		}).send();
		
	},

	submitNewpassForm:function(e) {
		this.showInnerOverlay();		
		if (!this.newpassTyped.get('password') ||  this.newpassPassword.get('value')=='') {
			//alert('no spam entrance');	
			this.showNotice('error', mm.lang.notice.no_input);		
			(function() { this.hideInnerOverlay(); }).delay(this.options.innerOverlayDelay, this);											
			return false;			
		}
		this.newpassPassword.set('value', this.newpassPassword.get('value').stripTags().clean());		
		//this.newpassConfirm.set('value', this.newpassConfirm.get('value').stripTags().clean());				
		if (!this.validateNewpassForm() || this.newpassHidden.get('value').toInt() !== 1) {
			//alert('error validating form');
			this.showNotice('error', mm.lang.notice.newpass_validation_error);		
			(function() { this.hideInnerOverlay(); }).delay(this.options.innerOverlayDelay, this);													
			return false;			
		}
		var qs = this.newpassForm.toQueryString();
		var qsdata = qs.parseQueryString(); 
		qsdata.formkey = qsdata.formkey * this.multiplier;		
		qsdata.password = Base64.encode(qsdata.formkey+qsdata.password+qsdata.formkey);
		//qsdata_hash = Base64.encode(qsdata.formkey+qsdata.hash+qsdata.formkey);  // no encoding of token, doesn't work
// dbug.log(qsdata);
		new Request.JSON({
			url: '/_x/newpass'
			, data: qsdata
			, method: 'post'
			, link: 'ignore'
			, noCache: true
			, onSuccess: function(rJson, rText) {
				this.newpassRequestSucces.delay(this.options.ajaxDelay, this, [rJson, rText]);	//(rJson, rText);
			}.bind(this)
			, onRequest: function() {
				this.newpassRequestStart();
			}.bind(this)
			, onFailuer: function() {
				this.newpassRequestFailure();
			}.bind(this)
		}).send();
		
	},	
	showInnerOverlay:function() {
		// this.loginContainer.setStyle('opacity',0.85);
// dbug.log('showing inner overlay');		
		this.loginInnerOverlay.setStyles({'display':'block', 'opacity':0}).fade(this.options.innerOverlayOpacity);		
	}, 
	hideInnerOverlay:function() {
// dbug.log('hiding inner overlay');		
		this.loginInnerOverlay.fade(0);
		// this.loginContainer.setStyle('opacity',1);		
	},
	tweenCompleteInnerOverlay:function() {
		var opac = this.loginInnerOverlay.getStyle('opacity');
		if (opac == 0) { this.loginInnerOverlay.setStyle('display','none'); }
// dbug.log('tweenCompleteInnerOverlay opac = '+opac);
	},
	requestStart:function(which) {
		//this.loginInner.setStyle('opacity',0.2);
		this.showInnerOverlay();
//dbug.log(wm['lang'].notice.login_loading);	//	<== also possible
		this.showNotice('loading', mm.lang.notice[which+'_loading']);
	},
	requestEnd:function() {
		this.hideInnerOverlay();
	},
	/*
		errors and notices:
	*/
	loginRequestStart:function() {
		//
// dbug.log('loginRequestStart (need ajaxloader here, opacity of form)');		
//		this.loginInnerOverlayText.set('html', 'validating account ...');
		this.requestStart('login');
	},
	loginRequestSucces:function(rJson, rText) {
// dbug.log('loginRequestSucces returnvalue = ');	
// dbug.log(JSON.encode(rJson));	
		if (!rJson.session) {
			this.showNotice('info', mm.lang.notice.login_nosession);
			var email = this.loginEmail.get('value');
			//var pass = this.loginPassword.get('value');
			var details = Base64.encode(JSON.encode([email]));
			(function() { window.location.href = '/login/'+details; }).delay(this.options.ajaxDelay, this);			
		} else {
			if(rJson.loggedin==true) {
					this.loginEmail.set('value','');
					this.loginPassword.set('value','');	
					this.loginSubmit.focus();
					if ($defined(rJson.portal) && (rJson.portal!='')) {
						this.showNotice('ok', mm.lang.notice.login_ok_portalredirect);						
						//this.redirectLogin(rJson.loggedin.portal, rJson.loggedin.portal_key);
						rJson.portal_key = '';
						this.redirectLogin.delay(this.options.ajaxDelay, this, [rJson.portal, rJson.portal_key]);
						// (function() { window.location.href = rJson.loggedin.portal+'/login/l'; }).delay(10,this);						
					} else { 			 
						this.showNotice('ok', mm.lang.notice.login_ok);					
						(function() { window.location.href = '/'; }).delay(this.options.ajaxDelay, this);
					}
			} else {
				this.requestEnd();
				this.showNotice('error', mm.lang.notice.login_error);
			}
		}
	},
	redirectLogin:function(portal,portal_key) {
		var location = window.location.protocol+'//'+window.location.host; 
		
// dbug.log('location = '+location+ ' portal = '+portal+' portal_key = '+portal_key);		
/*
		if (portal !== location) { 
			var rForm = new Element('form', {'method':'post', 'action':portal}).inject(this.element);
			rForm.set('send', {url:portal, method: 'post'});		
			var rHiddenKey = new Element('input', {'type':'hidden','name':'mmautologin'}).set('value',portal_key).inject(rForm);				
			rForm.submit();
		} else {
			*/			
			(function() { window.location.href = portal; }).delay(20,this);			
		//}
	},
	loginRequestFailure:function() {
// dbug.log('loginRequestFailure');	
		this.requestEnd();
		this.showNotice('error', mm.lang.notice.request_error);
	},	
	
	forgotRequestStart:function() {
// dbug.log('forgotRequestStart');		
		//showAjaxWaiter here
//		this.loginInnerOverlayText.set('html', 'validating e-mail and sending password ...');		
		this.requestStart('forgot');		
	},
	forgotRequestSucces:function(rJson, rText) {
// dbug.log('forgotRequestSucces returnvalue = ');	
// dbug.log(rJson);	
		this.requestEnd();
		if(rJson.forgot==true) {
//dbug.log('loggedin = true');
			//window.location.href = '/';
			var oldmail = this.forgotEmail.get('value');
			
			this.displayLoginMessageForm();
			this.loginEmail.set('value', oldmail);
			this.loginMessageContinue.setStyle('display','none');
			this.showMessage('none', '');			
			this.showNotice('ok', mm.lang.message.forgot_ok);
			//this.showMessage('ok', mm.lang.message.forgot_ok);
			//this.loginTyped['email'] = true;
			//this.loginPassword.focus();	
		} else {
//dbug.log('loggedin = '+rJson.loggedin);			
			this.showNotice('error', mm.lang.notice.forgot_error);
		}
	},	
	forgotRequestFailure:function() {
// dbug.log('forgotRequestFailure');		
		this.requestEnd();
		this.showNotice('error', mm.lang.notice.request_error);
	},	
	
	newpassRequestStart:function() {
// dbug.log('newpassRequestStart');		
		//showAjaxWaiter here
//		this.loginInnerOverlayText.set('html', 'storing new password ...');		
		this.requestStart('newpass');		
	},
	newpassRequestSucces:function(rJson, rText) {
// dbug.log('newpassRequestSucces returnvalue = ');	
// dbug.log(rJson);	
		this.requestEnd();
		if(rJson.newpass==true) {
//dbug.log('loggedin = true');
			//window.location.href = '/';
			this.newpassPassword.set('value', '');
			this.displayLoginMessageForm();			
			this.showMessage('none', '');			
			this.showNotice('ok', mm.lang.message.newpass_ok);			
			this.loginMessageOk.setStyle('display','none');
			this.loginMessageContinue.setStyle('display','block').addEvent('click', function(e) {
				e.stop();
				(function() { window.location.href = '/login'; }).delay(50,this);
			}.bind(this)).focus();			
				
		} else {
//dbug.log('loggedin = '+rJson.loggedin);			
			this.showNotice('error', mm.lang.notice.newpass_error);
		}
		//this.showError('loggedin_failure');				
	},	
	newpassAnswerRequestSucces:function(rJson, rText) {
//dbug.log(rJson);		
		this.requestEnd();
			//this.hideInnerOverlay();		
		if (rJson.newpassanswer == true) {
			this.newpassAsnwerList.setStyle('display','none');
			this.newpassNewpassList.setStyle('display','block');
			this.showNotice('info', mm.lang.notice.newpass_info);			
		} else {
			this.showNotice('error', mm.lang.notice.newpassanswer_error);
		}
	},	
	newpassRequestFailure:function() {
// dbug.log('newpassRequestFailure');	
		this.requestEnd();	
		this.showNotice('error',mm.lang.notice.request_error);
	},	
	
	showForgotNotice:function(notice) {
		this.forgotSubmit.setStyle('display','none');
		// this.forgotCancel.setStyle('display','none');		
	},
	showNewpassNotice:function(notice) {
		this.newpassSubmit.setStyle('display','none');
		// this.newpassCancel.setStyle('display','none');		

	},
	showMessage: function(mtype, message) {
		this.loginMessageContainer.setStyles({'display':'none', 'opacity':0});
		this.loginMessageIcons.each(function(icon) {
			icon.setStyle('display','none');
		},this);		
		switch(mtype) {
			case 'none' : 
			break;
			case 'ok' :
				this.loginMessageIconOk.setStyle('display','block');
			break; 
		}
		this.loginMessageText.set('html', message);	
		this.loginMessageContainer.setStyles({'display':'block'}).fade('in');			
	},
	showNotice:function(ntype, notice) {
		this.loginNoticeContainer.setStyles({'display':'none','opacity':0});
		this.loginNoticeIcons.each(function(icon) {
			icon.setStyle('display','none');
		},this);

		switch(ntype) {
			case 'none' :
				
			break;
			case 'info' :
				this.loginNoticeIconInfo.setStyle('display','block');
			break;
			case 'ok' :
				this.loginNoticeIconOk.setStyle('display','block');
			break;			
			case 'error' :
				this.loginNoticeIconError.setStyle('display','block');
			break;			
			case 'loading' :
				this.loginNoticeIconLoading.setStyle('display','block');
			break;			
		}
		this.loginNoticeText.set('html', notice);		
		if (ntype=='loading') {
			this.loginNoticeContainer.setStyles({'display':'block','opacity':1,'visibility':'visible'});			
		} else {
			this.loginNoticeContainer.setStyles({'display':'block'}).fade('in');
		}
	}	
	
	
	
}); mm.LoginPollClass = new Class({
	Implements: [Events, Options],		
	options: {
		interval: 60000	// 60000 miliseconds periodic ajax login poll interval, needs to update session expire if succesfull
	},
	initialize: function(options) {
		this.setOptions(options);	
		this.interval = this.options.interval;		
		this.pRequest;
		this.setupPoller();
		this.loggedin = true;
// dbug.log('mm.LoginPoll initialize, this.interval = '+this.interval);		
	},
	setupPoller:function() {
		this.periodical = this.poll.periodical(this.interval,this);				
	},
	stopPoller:function() {
		$clear(this.periodical);
	},
	startPoller:function() {
		this.poll();
		this.setupPoller();
	},
	pausePoller:function(duration) {
		if ($chk(duration)) {
			this.stopPoller();
			this.startPoller.delay(duration.toInt(), this);
		}
	},
	poll:function() {
		if (!this.loggedin) { return; }
//dbug.log('PERIODIC POLLER'+$time());		
	
		var ajaxurl = '/_x/loginpoll';
		var postData = new Hash({
			'context': JSON.encode(mm.runtime)	// the context part of the wm.runtime is an array so we need to json encode it again
		});
		this.pRequest = new Request.JSON({
			url: ajaxurl
			, data: postData
			, method: 'post'
			, onSuccess: function(rJson, rText) {
				this.pollRequestSucces(rJson, rText);		
			}.bind(this)
			, onRequest: function() {
				this.pollRequestStart();
			}.bind(this)
			, onFailure: function(xhr) {				
				this.pollRequestFailure(xhr);
			}.bind(this)			
		}).send();
	},
	pollRequestStart: function() {
		
	},
	pollRequestSucces: function(rJson, rText) {
//dbug.log('poll request succes, rJson:');
//dbug.log(rJson);	
		if (rJson.loginpoll) {
			this.loggedin = true;
		} else {
			this.loggedin = false;
			// extra delete cookie (if not pressed on btn)
			if ($defined(mm.runtime.auth.cookieName) && mm.runtime.auth.cookieName!='') {
				//Cookie.dispose(mm.runtime.auth.cookieName);
			}			
			mm.overlayAll.showStaticDialog('loginpoll', 'loginpoll_expired');
//alert('[nice ui from wmOverlayAll ] => SESSION EXPIRED, NOT LOGGED IN ANYMORE, after closing you will be redirected to your login screen');
//			window.location.href='/logout';			
		}		
	},
	pollRequestFailure: function(xhr) {
		//this.loggedin = false;		
		this.stopPoller();
// dbug.log('poll request failed');				
//alert('[nice ui from wmOverlayAll !] => LOGIN POLL REQUEST FAILED, ARE YOU OFFLINE? check your internet connection to continue');
		mm.overlayAll.showStaticDialog.delay(500, mm.overlayAll, ['loginpoll', 'loginpoll_failure', true]);
		//window.location.href='/logout';		
		
	}
	
}); mm.Graph = new Class({

	Implements: [Options, Events]
	, options: {		
		containerId : false
		, size : {width:600, height:400}
		, gutter: {top:20,bottom:20,left:20,right:20}
		, background: 'transparent'
		, gridLines: {x:0, y:6, color:'#cbcbcb',width:1, labelColor:'#a4a4a4', labelFont: 'Trebuchet MS', labelFontSize: '11px', labelFontColor: '#737373'}
		, data: [
				[
				  50,100.33333367,70
				]
				, [
					40,4,85.49
				]
			]
		// , dataColors: [
		// 		['270-#4c4c4c-#000000','270-#0be52f-#019412']
		// 		,['270-#9a9a9a-#7b7b7b','270-#ff1a00-#cd0000']
		// 	]
		, dataColors: [
				['270-#cfcfcf-#b5b5b5','270-#0be52f-#019412']
				,['270-#9a9a9a-#7b7b7b','270-#ff1a00-#cd0000']
			]			
		, dataLabels: ['Omzet','Kosten']
		, axesLabels: ['Apr', 'Mei', 'Jun']
		, dataValueCeilings : [5000, 10000, 2500, 50000, 100000, 25000, 500000]
		, barTipOffsets : {x:16,y:-16}
		, scaleMax : 5000
		, barMinHeight: 6	// min pixel height of bar when value is low relative to grid scale
		, drawProfit: false
		, noDataLabel: 'geen gegevens'
		// #cbcbcb gridlines
		// axesLabels: #a4a4a4	
	}
	, initialize: function(options) {
		this.setOptions(options);	
		this.createCanvas();	
		this.axes = [];
		this.grid = [];
		this.bars = [];
		this.data = this.options.data;
		this.drawBackground();
		this.getMaxValue();
		this.createProfitData();
		this.drawGridLines();
		this.drawAxesLabels();
		if (this.maxValue==0) {
			this.drawNoData();
		} else {
			this.drawData();		
		}
	}
	, createCanvas:function() {
		this.canvas = new Raphael(this.options.containerId, this.options.size.width, this.options.size.height);
		this.origin = {top:this.options.gutter.top, left:this.options.gutter.left, right: this.options.size.width-this.options.gutter.right, bottom:this.options.size.height-this.options.gutter.bottom}
		this.graphSize = {width: this.options.size.width-(this.options.gutter.left+this.options.gutter.right), height: this.options.size.height-(this.options.gutter.top+this.options.gutter.bottom) };
		this.canvasCoords = $(this.options.containerId).getCoordinates();
		this.barTip = new Element('div', {id:'graphBarTip', 'class':'canvasBarTip'}).inject($(this.options.containerId));		
//		this.barTip = new Element('div', {id:'graphBarTip', 'class':'canvasBarTip'}).inject(document.body);		
	}
	, drawBackground:function() {
		if (this.options.background == 'transparent') { return; }
		this.bg = this.canvas.rect(0,0,this.options.size.width, this.options.size.height).attr({fill:this.options.background});
	}
	, getMaxValue:function() {
		var maxValue = 0;
		this.data.each(function(dataSet) {
			if ($type(dataSet)=='array') {

					var subMax = dataSet.max();
					if (subMax > maxValue) { maxValue = subMax; }
//dbug.log('subMax = '+subMax);					

			}
		},this);
		this.maxValue = maxValue;
		this.maxValueCeiling = 500;
		this.yLabels = [];
		var sub = 100;
		if (this.maxValue < 500) {
			sub = 500/5;
			this.maxValueCeiling = 500;
		} else if (this.maxValue > 500 && this.maxValue <= 1000) {
			sub = 1000/5;
			this.maxValueCeiling = 1000;			
		} else if (this.maxValue > 1000 && this.maxValue <= 2500 ) {
			sub = 2500/5;			
			this.maxValueCeiling = 2500;						
		} else if (this.maxValue > 2500 && this.maxValue <= 5000 ) {
			sub = 5000/5;		
			this.maxValueCeiling = 5000;				
		} else if (this.maxValue > 5000 && this.maxValue <= 10000) {
			sub = 10000/5;
			this.maxValueCeiling = 10000;			
		} else if (this.maxValue > 10000 && this.maxValue <= 25000) {			
			sub = 25000/5;
			this.maxValueCeiling = 25000;			
		} else if (this.maxValue > 25000 && this.maxValue <= 50000) {
			sub = 50000/5;
			this.maxValueCeiling = 50000;			
		} else if (this.maxValue > 50000 && this.maxValue <= 100000) {
			sub = 100000/5;
			this.maxValueCeiling = 100000;			
		} else if (this.maxValue > 100000 && this.maxValue <= 500000) {
			sub = 500000/5;
			this.maxValueCeiling = 500000;			
		} else if (this.maxValue > 500000 && this.maxValue <= 1000000) {
			sub = 1000000/5;
			this.maxValueCeiling = 1000000;			
		} else if (this.maxValue > 1000000 && this.maxValue <= 5000000) {
			sub = 5000000/5;
			this.maxValueCeiling = 5000000;			
		} else if (this.maxValue > 5000000 && this.maxValue <= 10000000) {
			sub = 10000000/5;
			this.maxValueCeiling = 10000000;			
		}
		for (i=0; i<6; i++) {
			this.yLabels.push(i*sub);
//dbug.log('yLabels push '+(i*sub));			
		}		
// dbug.log('maxValue = '+this.maxValue);		
// dbug.log('yLabels: '+JSON.encode(this.yLabels));
	}
	, createProfitData: function() {
		this.dataProfit = [];
		var first = this.data[0];
		var second = this.data[1];
		first.each(function(set,index) {
			this.dataProfit[index] = set - second[index];
		},this);
// dbug.log('profit = '+JSON.encode(this.dataProfit));		
	}
	, drawGridLines:function() {
		var stepX = this.graphSize.width / (this.options.gridLines.x-1);
		var stepY = (this.graphSize.height / (this.options.gridLines.y-1)).toFloat();
//dbug.log('stepY = '+stepY);		
		for (i=0; i<this.options.gridLines.x; i++) {
			// M5,5 L10,10
			var pathStr = 'M'+(this.origin.left+ (stepX*(i+0)) )+','+(this.origin.top)+' L'+(this.origin.left+ (stepX*(i+0)))+','+this.origin.bottom;
			var line = this.canvas.path(pathStr).attr({stroke:this.options.gridLines.color, 'stroke-width':this.options.gridLines.width});
			this.grid.push(line);
		}
		var stroke_width = this.options.gridLines.width;
		for (i=0; i<this.options.gridLines.y; i++) {
			// M5,5 L10,10
			var pathStr = 'M'+(this.origin.left  )+','+(this.origin.top + (stepY*(i+0)))+' L'+(this.origin.right)+','+(this.origin.top + (stepY*(i+0)));
			if (i == (this.options.gridLines.y-1)) {
				stroke_width = this.options.gridLines.width + 1;
			} 
			var line = this.canvas.path(pathStr).attr({stroke:this.options.gridLines.color, 'stroke-width':stroke_width});
//dbug.log('o top :'+this.origin.top+' + stepY*(i*): '+(stepY*(i+0))+' when i = '+ i+' label = '+this.yLabels[5-i]);			
			var label = this.canvas.text(this.origin.left-15,(this.origin.top.toFloat() + (stepY*i).toFloat()).toFloat(),' '+this.yLabels[5-i]);
			//var label = this.canvas.text(this.origin.left-10,20,this.yLabels[5-i]+'ja');			
//dbug.log('left:'+(this.origin.left-10)+' top:'+	(this.origin.top.toFloat() + (stepY*i).toFloat()).toFloat() + ' label:' + this.yLabels[5-i]);		
			label.attr({'text-anchor':'end',fill: this.options.gridLines.labelFontColor, stroke: "none", opacity: 1, "font-family": this.options.gridLines.labelFont, "font-size": this.options.gridLines.labelFontSize});
			
			this.grid.push(line);
		} 
		 
		// this.canvas.text(50, 50, "This is a test")		
//		this.canvas.rect(30,30,500,300).attr({fill:'#456789'});
		
		this.toFrontGrid();

	}
	, drawAxesLabels:function() {
		
	}
	, drawNoData:function() {
		var halfx = (this.graphSize.width / 2);
		var halfy = (this.graphSize.height / 2);
		
		var r = this.canvas.rect(this.origin.left + (halfx/2) + 64, this.origin.top + (halfy - 16), halfx - 128, 32, 5);		
		r.attr({stroke:'#cfcfcf', "stroke-width": 1, fill:'#F0F0F0'});		
		var label = this.canvas.text(this.origin.left + (halfx),this.origin.top + (halfy),this.options.noDataLabel);
		label.attr({'text-anchor':'middle',fill: this.options.gridLines.labelFontColor, stroke: "none", opacity: 1, "font-family": this.options.gridLines.labelFont, "font-size": this.options.gridLines.labelFontSize});		
	}
	, drawData:function() {		
		var dataLength = this.data.length;	//how many bars together?
		var subBars = [];
		var self = this;
		this.data.each(function(dataSet, index) {
			if ($type(dataSet)=='array') {
				var gutter = 10; 
				var barWidth = 50;
				if (dataSet.length == 1) {
					barWidth = 70;
				} else if (dataSet.length == 3) {
					barWidth = 50;
				} else if (dataSet.length > 3 && dataSet.length < 13) {		
					barWidth = 22;					
				} else if (dataSet.length > 12) {
					barWidth = 9;								
				}
				gutter = (this.graphSize.width - (dataSet.length*barWidth) ) / (dataSet.length+1);				
				dataSet.each(function(dataSubset, subindex) {
					var startx = this.origin.left + (gutter * (subindex+1)) + (barWidth * (subindex)) ;  	// equally spaced startx
					var offsetx = (barWidth/dataLength) - (index*barWidth) + (index*(barWidth/5)) - ((barWidth/5)/2);				// 
					var dataHeight = ((dataSubset / this.maxValueCeiling ) * this.graphSize.height).round();
					if (dataHeight < this.options.barMinHeight && dataSubset !== 0) { dataHeight = this.options.barMinHeight; }
					var bar = this.canvas.rect( startx - offsetx , this.origin.bottom.toInt() - dataHeight.toInt(), barWidth, dataHeight.toInt() );
					var bottomstart = this.origin.bottom - dataHeight.toInt();
// dbug.log('canvas RECT START: '+bottomstart + ' height = '+dataHeight.toInt());					
					var gradientNormal = this.options.dataColors[index][0];
					var gradientHover = this.options.dataColors[index][1];					

					bar.attr({gradient:gradientNormal, 'stroke-width':0, stroke:this.options.gridLines.labelColor});
					if (index == 1) {
						var axisXlabel = this.canvas.text(startx-offsetx, this.origin.bottom+20, this.options.axesLabels[subindex]).attr({fill: this.options.gridLines.labelColor, stroke: "none", opacity: 1, "font-family": this.options.gridLines.labelFont, "font-size": this.options.gridLines.labelFontSize});
					}
					subBars.push(bar);				
// dbug.log('drawing index='+index);		
					if (!Browser.Engine.trident) {
						bar.node.addEvents({
							'mouseenter' : function(e) {									
								this.attr({gradient:gradientHover});
	//dbug.log('data:'+dataSubset);
	//dbug.log(self.barTip);								
								self.barTip.set('html',self.options.dataLabels[index]+':<br />&euro; &nbsp; '+dataSubset.numberFormat(2,',','.')).setStyles({top:e.page.y-self.canvasCoords.top+self.options.barTipOffsets.y,left:e.page.x-self.canvasCoords.left+self.options.barTipOffsets.x,'display':'block','opacity':0}).fade(1);
							}.bind(bar)
							, 'mouseleave': function(e) {
								this.attr({gradient:gradientNormal});				
								self.barTip.set('html', '').hide();								
							}.bind(bar)
							, 'mousemove': function(e) {
								self.barTip.setStyles({top:e.page.y-self.canvasCoords.top+self.options.barTipOffsets.y,left:e.page.x-self.canvasCoords.left+self.options.barTipOffsets.x});
							}.bind(bar)
						});
					} else {
						bar.node.onmouseenter = function(e) {
							e = new Event(e);						
							this.attr({gradient:gradientHover});
							self.barTip.set('html',self.options.dataLabels[index]+':<br />&euro; &nbsp; '+dataSubset.numberFormat(2,',','.')).setStyles({top:e.page.y-self.canvasCoords.top+self.options.barTipOffsets.y,left:e.page.x-self.canvasCoords.left+self.options.barTipOffsets.x,'display':'block','opacity':0}).fade(1);												
						}.bind(bar);
						bar.node.onmouseleave = function(e) {
							e = new Event(e);
							this.attr({gradient:gradientNormal});				
							self.barTip.set('html', '').hide();						
						}.bind(bar);
						bar.node.onmousemove = function(e) {
							e = new Event(e);
								self.barTip.setStyles({top:e.page.y-self.canvasCoords.top+self.options.barTipOffsets.y,left:e.page.x-self.canvasCoords.left+self.options.barTipOffsets.x});						
						}.bind(bar);					
					}
					
				},this);
				this.bars.push(subBars);
							

				if (this.dataProfit.length > 1 && this.options.drawProfit && index==1) {
//					var dotgutter = (this.graphSize.width - (this.dataProfit.length*barWidth) ) / (dataSet.length+1);									
					var dotCount = this.dataProfit.length;				
					this.dataProfit.each(function(dot, dotindex) {						
//dbug.log('starx = '+startx+ ' orig :'+(this.graphSize.width/dotCount) + ' dotcount:'+dotCount);						
						if (dotindex!==0) {							
							var dotHeight = (dot / this.maxValueCeiling) * this.graphSize.height;							
							var nextDotHeight =(this.dataProfit[dotindex-1] / this.maxValueCeiling) * this.graphSize.height;
							var startx = this.origin.left + ((this.graphSize.width/dotCount) * dotindex) + barWidth; //+ (gutter * dotindex);							
							var lastx = this.origin.left + ((this.graphSize.width/dotCount) * (dotindex-1)) + barWidth; //+ (gutter * dotindex-1);							
							var pathStr = 'M'+lastx+','+(this.origin.bottom - nextDotHeight)+' L'+(startx)+','+(this.origin.bottom - dotHeight)+'';
						} else {
// dbug.log('gutter = '+gutter);							
							var startx = this.origin.left + ((this.graphSize.width/dotCount) * dotindex) + gutter;							
							var dotHeight = (dot / this.maxValueCeiling) * this.graphSize.height;							
							var pathStr = 'M'+startx+','+(this.origin.bottom - dotHeight)+' L'+(startx)+','+(this.origin.bottom - dotHeight)+'';
						}
//dbug.log('yo: '+pathStr);						
						this.canvas.path(pathStr).attr({stroke:'#0000ff','stroke-width':3});
					},this);
				}				
				
			}
		},this);
		
//dbug.log(JSON.encode(this.data));		
//dbug.log(JSON.encode(this.bars));
	}
	, toFrontGrid:function() {
		this.grid.each(function(line) {
			line.toFront();
		});		
	}
	
}); mm.Pie = new Class({

	Implements: [Options, Events]
	, options: {		
		containerId : false
		, size : {width:200, height:200}
		, gutter: {top:20,bottom:20,left:20,right:20}
		, background: 'transparent'
		, gridLines: {x:0, y:6, color:'#cbcbcb',width:1, labelColor:'#a4a4a4', labelFont: 'Trebuchet MS', labelFontSize: '11px', labelFontColor: '#737373'}
		, data: []
		, dataColors: [[],[]]
		, dataLabels: []
		, noDataLabel: 'No data'
		, pieTipOffsets : {x:16,y:-16}
		, pieMinSize: 5	// min pixel height of bar when value is low relative to grid scale
		, minPercentage: 1 // minimum percentage for a pie of the total, if smaller this will be used to display minimum pie size
	}
	, initialize: function(options) {
		this.setOptions(options);	
		this.createCanvas();	
		this.pies = [];
		this.total = 0;
		this.data = this.options.data;
		this.drawBackground();
		this.calculateTotal();
		this.drawPie();
	}
	, createCanvas:function() {
		this.canvas = new Raphael(this.options.containerId, this.options.size.width, this.options.size.height);
//dbug.log('createCanvas');	
		this.origin = {top:this.options.gutter.top, left:this.options.gutter.left, right: this.options.size.width-this.options.gutter.right, bottom:this.options.size.height-this.options.gutter.bottom}
		this.graphSize = {width: this.options.size.width-(this.options.gutter.left+this.options.gutter.right), height: this.options.size.height-(this.options.gutter.top+this.options.gutter.bottom) };
		this.center = {x:this.origin.left+(this.graphSize.width/2),y:this.origin.top+(this.graphSize.height/2)};
		this.radius = this.graphSize.width/2;
		this.canvasCoords = $(this.options.containerId).getCoordinates();
		this.pieTip = new Element('div', {id:'graphPieTip', 'class':'canvasPieTip'}).inject($(this.options.containerId));		
//		this.barTip = new Element('div', {id:'graphBarTip', 'class':'canvasBarTip'}).inject(document.body);		
	}
	, drawBackground:function() {
		if (this.options.background == 'transparent') { return; }
		this.bg = this.canvas.rect(0,0,this.options.size.width, this.options.size.height).attr({fill:this.options.background});
	}
	, calculateTotal:function() {
		this.data.each(function(amount) {
			this.total += amount;
		},this);
	}
	, drawPie:function() {
		if (this.total > 0 && this.data.length > 1) {
			var self = this;			
			var angleplus = 0, angle=0, popangle=0, percentage=0;
			var normalColors = this.options.dataColors[0];
			var hoverColors = this.options.dataColors[1];			
			var gradientNormal = '';
			var gradientHover = '';
			
			
			//var minpercentage = 1;
			this.percentages = [];
			this.percentages_org = [];
			this.smallerIndexes = [];
			var leftover = 0;
//dbug.log('total = '+this.total);			
			this.data.each(function(amount, index) {
				var perc = 100 * (amount/this.total);
//dbug.log('amount = '+amount+' index = '+index+ ' perc = '+perc);				
				this.percentages_org.push(perc);
				if (perc < this.options.minPercentage) {
					this.smallerIndexes.push(index);
					leftover += (this.options.minPercentage - perc).toFloat();
//dbug.log('leftover + '+ (this.options.minPercentage - perc).toFloat());					
					this.percentages.push(this.options.minPercentage);
				} else {
					this.percentages.push(perc);				
				}


			},this);

//dbug.log(JSON.encode(this.percentages));			
//dbug.log(JSON.encode(this.smallerIndexes));
//dbug.log('leftover = '+leftover);

			if (leftover > 0) {
				var divperc = (100 - leftover) / 100;
				this.percentages.each(function(perc, index) {
					if (!this.smallerIndexes.contains(index)) {
						this.percentages[index] = perc * divperc;
					}
				},this);
			}			

//			this.data.each(function(amount, index) 
//				angleplus = 360 * amount/this.total;
//				percentage = ((amount/this.total) * 100);
//				var pstr = percentage.numberFormat(1,',','.')+'%';
//				if (angleplus < this.options.pieMinSize) { angleplus = this.options.pieMinSize; }			
			this.percentages.each(function(percentage, index) {
				amount = this.data[index];			
				angleplus = 360 * (percentage / 100);				
				var pstr = this.percentages_org[index].numberFormat(1,',','')+'%';
				
				popangle = angle + (angleplus/2);
				gradientNormal = popangle+'-'+normalColors[1]+'-'+normalColors[0];
				gradientHover = popangle+'-'+hoverColors[1]+'-'+hoverColors[0];
				var testangle = 90;
				gradientNormal = testangle+'-'+normalColors[1]+'-'+normalColors[0];
				gradientHover = testangle+'-'+hoverColors[1]+'-'+hoverColors[0];				
//dbug.log('gradientNormal = '+gradientNormal);				
				var pie = this.drawSector(this.center.x,this.center.y,this.radius, angle, angle+angleplus, {gradient:gradientNormal, stroke:'#ffffff', 'stroke-width':2});

				if (!Browser.Engine.trident) {
					pie.node.addEvents({
						'mouseenter':function(e) {
							this.attr({gradient:gradientHover});
							this.animate({scale: [1.05, 1.05, self.center.x, self.center.y]}, 500, "elastic");
							self.pieTip.set('html',self.options.dataLabels[index]+': <br />&euro; &nbsp; '+self.data[index].numberFormat(2,',','.')+' ( '+pstr+' )').setStyles({top:e.page.y-self.canvasCoords.top+self.options.pieTipOffsets.y,left:e.page.x-self.canvasCoords.left+self.options.pieTipOffsets.x,'display':'block','opacity':0}).fade(1);						
						}.bind(pie)
						, 'mouseleave':function(e) {
							this.attr({gradient:gradientNormal});
							this.animate({scale: [1, 1, self.center.x, self.center.y]}, 500, "elastic");
							self.pieTip.set('html', '').hide();						
						}.bind(pie)	
						, 'mousemove': function(e) {
							self.pieTip.setStyles({top:e.page.y-self.canvasCoords.top+self.options.pieTipOffsets.y,left:e.page.x-self.canvasCoords.left+self.options.pieTipOffsets.x});
						}.bind(pie)									
					});
				} else {
					pie.node.onmouseenter = function(e) {
						e = new Event(e);											
						this.attr({gradient:gradientHover});
						this.animate({scale: [1.05, 1.05, self.center.x, self.center.y]}, 500, "elastic");
						self.pieTip.set('html',self.options.dataLabels[index]+': <br />&euro; &nbsp; '+amount.numberFormat(2,',','.')+' ( '+pstr+' )').setStyles({top:e.page.y-self.canvasCoords.top+self.options.pieTipOffsets.y,left:e.page.x-self.canvasCoords.left+self.options.pieTipOffsets.x,'display':'block','opacity':0}).fade(1);					
					}.bind(pie);
					pie.node.onmouseleave = function(e) {
						e = new Event(e);											
						this.attr({gradient:gradientNormal});
						this.animate({scale: [1, 1, self.center.x, self.center.y]}, 500, "elastic");
						self.pieTip.set('html', '').hide();					
					}.bind(pie);
					pie.node.onmousemove = function(e) {
						e = new Event(e);											
						self.pieTip.setStyles({top:e.page.y-self.canvasCoords.top+self.options.pieTipOffsets.y,left:e.page.x-self.canvasCoords.left+self.options.pieTipOffsets.x});					
					}.bind(pie);					
				}

				this.pies.push(pie);
				angle += angleplus;	
			},this);

		} else if (this.total > 0 && this.data.length == 1) {
			var self = this;			
			var normalColors = this.options.dataColors[0];
			var hoverColors = this.options.dataColors[1];
			var gradientNormal = '';
			var gradientHover = '';						
			var testangle = 90;
			gradientNormal = testangle+'-'+normalColors[1]+'-'+normalColors[0];
			gradientHover = testangle+'-'+hoverColors[1]+'-'+hoverColors[0];			
			var pie = this.canvas.circle(this.center.x,this.center.y,this.radius).attr({gradient:gradientNormal, stroke:'#ffffff','stroke-width':2});			
			if (!Browser.Engine.trident) {			
				pie.node.addEvents({
					'mouseenter':function(e) {
						this.attr({gradient:gradientHover});
						this.animate({scale: [1.05, 1.05, self.center.x, self.center.y]}, 500, "elastic");
						self.pieTip.set('html',self.options.dataLabels[0]+': <br />&euro; &nbsp; '+self.data[0].numberFormat(2,',','.')+' ( 100,00% )').setStyles({top:e.page.y-self.canvasCoords.top+self.options.pieTipOffsets.y,left:e.page.x-self.canvasCoords.left+self.options.pieTipOffsets.x,'display':'block','opacity':0}).fade(1);						
					}.bind(pie)
					, 'mouseleave':function(e) {
						this.attr({gradient:gradientNormal});
						this.animate({scale: [1, 1, self.center.x, self.center.y]}, 500, "elastic");
						self.pieTip.set('html', '').hide();						
					}.bind(pie)	
					, 'mousemove': function(e) {
						self.pieTip.setStyles({top:e.page.y-self.canvasCoords.top+self.options.pieTipOffsets.y,left:e.page.x-self.canvasCoords.left+self.options.pieTipOffsets.x});
					}.bind(pie)									
				});
			} else {
				pie.node.onmouseenter = function(e) {
					e = new Event(e);					
					this.attr({gradient:gradientHover});
					this.animate({scale: [1.05, 1.05, self.center.x, self.center.y]}, 500, "elastic");
					self.pieTip.set('html',self.options.dataLabels[0]+': <br />&euro; &nbsp; '+self.data[0].numberFormat(2,',','.')+' ( 100,00% )').setStyles({top:e.page.y-self.canvasCoords.top+self.options.pieTipOffsets.y,left:e.page.x-self.canvasCoords.left+self.options.pieTipOffsets.x,'display':'block','opacity':0}).fade(1);					
				}.bind(pie);
				pie.node.onmouseleave = function(e) {
					e = new Event(e);					
					this.attr({gradient:gradientNormal});
					this.animate({scale: [1, 1, self.center.x, self.center.y]}, 500, "elastic");
					self.pieTip.set('html', '').hide();					
				}.bind(pie);
				pie.node.onmousemove = function(e) {
					e = new Event(e);					
					self.pieTip.setStyles({top:e.page.y-self.canvasCoords.top+self.options.pieTipOffsets.y,left:e.page.x-self.canvasCoords.left+self.options.pieTipOffsets.x});					
				}.bind(pie);
			}
			this.pies.push(pie);			
		} else {
			//draw no data, empty circle
			//F0F0F0
			this.canvas.circle(this.center.x,this.center.y,this.radius).attr({fill:'#ffffff','stroke-width':1, stroke:'#cfcfcf'});
			var halfx = (this.graphSize.width / 2);
			var halfy = (this.graphSize.height / 2);
			var r = this.canvas.rect(this.origin.left + (halfx/2) - 32, this.origin.top + (halfy - 16), halfx + 64, 32, 5);		
			r.attr({stroke:'#cfcfcf', "stroke-width": 1, fill:'#F0F0F0'});
			
						
			var label = this.canvas.text(this.center.x,this.center.y,this.options.noDataLabel);
			label.attr({'text-anchor':'middle',fill: this.options.gridLines.labelFontColor, stroke: "none", opacity: 1, "font-family": this.options.gridLines.labelFont, "font-size": this.options.gridLines.labelFontSize});			
		}
	}
	, makeSectors:function() {
		
	}
	, drawSector:function(cx, cy, r, startAngle, endAngle, params) {
		var rad = Math.PI / 180;
        var x1 = cx + r * Math.cos(-startAngle * rad),
            x2 = cx + r * Math.cos(-endAngle * rad),
            y1 = cy + r * Math.sin(-startAngle * rad),
            y2 = cy + r * Math.sin(-endAngle * rad);
        return this.canvas.path(["M", cx, cy, "L", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2, "z"]).attr(params);		
	}
	
});
 mm.Color = new Class({

	Implements: [Options, Events]
	, options: {		
		tweenProps: {duration:20, transition:'circ:in:out'}
		, 'containerColor': '#000000'
		, 'contrastLimits': [255, 180, 255]
		, showKnobLabels: true
		, openOnHover: true
		, alwaysOpen: false
		, offsets: {x:0, y:4}
		, autoFontColor: false
		, onChange: $empty
	}
	, initialize:function(inputEl, options) {
		this.setOptions(options);
		this.element = $(inputEl);
		this.colorValues = [0,0,0];
		this.fontColor = '#000000';
		this.sliders = [];
		this.inputs = [];
		this.bound = {};
		this.isOpen = false;
		this.updateInput = false;
		this.setupElements();
		this.setupEvents();
	}
	, setupElements:function() { 
		this.inputHidden = new Element('input', {'type':'hidden','name':this.element.get('name')}).inject(this.element,'after');
		this.element.set('name', this.element.get('name')+'_display');
		this.slidersContainer = new Element('div', {'class':'mmColorSlidersContainer'});//.setStyles({'background-color':this.options.containerColor});
		this.sliderR = new Element('div', {'class':'mmColorSlider'}).inject(this.slidersContainer);
		this.knobR = new Element('div', {'class':'mmColorKnob'}).setStyles({'background-position':'0px 0px'}).inject(this.sliderR);
		if (this.options.showKnobLabels) { this.knobR.set('html', 'R'); }
		this.inputR = new Element('input', {'class':'mmColorInput'}).inject(this.sliderR);
		this.sliderG = new Element('div', {'class':'mmColorSlider'}).inject(this.slidersContainer);
		this.knobG = new Element('div', {'class':'mmColorKnob'}).setStyles({'background-position':'0px -14px'}).inject(this.sliderG);
		if (this.options.showKnobLabels) { this.knobG.set('html', 'G'); }
		this.inputG = new Element('input', {'class':'mmColorInput'}).inject(this.sliderG);		
		this.sliderB = new Element('div', {'class':'mmColorSlider'}).inject(this.slidersContainer);				
		this.knobB = new Element('div', {'class':'mmColorKnob'}).setStyles({'background-position':'0px -28px'}).inject(this.sliderB);
		if (this.options.showKnobLabels) { this.knobB.set('html', 'B'); }		
		this.inputB = new Element('input', {'class':'mmColorInput'}).inject(this.sliderB);		
		var elCoords = this.element.getCoordinates(this.element.getParent());
		this.slidersContainer.setStyles({'display':'block','opacity':0, 'top':(elCoords.top+elCoords.height+this.options.offsets.y)+'px', 'left':(elCoords.left+this.options.offsets.x)+'px'});	
		this.slidersContainer.set('tween', {
			duration: this.options.tweenProps.duration
			, transition: this.options.tweenProps.transition
		});
		this.inputs = [this.inputR, this.inputG, this.inputB];
		this.slidersContainer.inject(this.element, 'after');	

	}
	, setupEvents:function() {
		var self = this;
		[this.sliderR, this.sliderG, this.sliderB].each(function(el, i) {
			var slider = new Slider(el, el.getElement('.mmColorKnob'), {
				steps: 255,  // Steps from 0 to 255
				wheel: true, // Using the mousewheel is possible too
				onChange: function(step){
					// Based on the Slider values set an RGB value in the color array
//dbug.log('step = '+step);					
					this.colorValues[i] = step;
					this.inputs[i].set('value', step).fireEvent('change');
					// and update the output to the new value
					//this.updateFromSliders();
				}.bind(this)
			}); //.set(0);
			this.sliders.include(slider);			
		},this);	

		this.bound.updateFromInput = this.updateFromInput.bindWithEvent(this);
		this.bound.blur = this.blur.bindWithEvent(this);
		this.bound.focus = this.focus.bindWithEvent(this);
		this.bound.close = this.close.bindWithEvent(this);
		this.bound.open = this.open.bindWithEvent(this);
		this.bound.keyup = this.keyup.bindWithEvent(this);
		this.element.addEvents({
			//'keydown': this.updateFromInput.bindWithEvent(this)
			 //'keyup': this.bound.updateFromInput
			'keyup': this.bound.keyup
			 ,'blur': this.bound.blur
			//, 'focus': this.bound.focus
			//, 'click': this.bound.open
		});
		if (this.options.openOnHover) {
			this.element.addEvent('mouseenter', this.bound.open);
		}
		this.slidersContainer.addEvents({
			'mouseleave':this.bound.close
		});
		this.inputs.each(function(input,i){
			input.setStyle('z-index',1);
			input.addEvents({
				'mousedown':function(e) {
					e.stopPropagation();
				}.bind(this)
				, 'keyup':function(e) {
					this.updateFromColorInput(i);
				}.bind(this)
				, 'change':function(e) {
					this.updateFromColorInput(i);					
				}.bind(this)
				, 'blur':function(e) {
					var val = input.get('value');
					if (isNaN(val)) { val = 0; }
					if (val=='') { val = 0; }
					if (val < 0) { val - 0; }
					if (val > 255) { val = 255; }
					input.set('value', val);
				}.bind(this)
			});
		},this);
		
		// start values:
		var hex = this.element.get('value');
		if (hex.charAt(0)!='#') { hex = '#'+hex; }
		var len = hex.length;
		if (len < 7) {
			var missing = 7-len;
			hex = hex + '0'.repeat(missing);
		} else if (len > 7) {
			hex = hex.substr(0,7);
		}
		this.colorValues = hex.hexToRgb(true);
		this.calcHexFromValues(true);	
		
		var startEvents = ['click'];
		var remainEvents = ['mouseenter'];
		var endEvents = ['mouseleave'];
		if (this.options.openOnHover) {
			startEvents = ['mouseenter'];
		} 
		new HoverGroup({
			elements: [this.element, this.slidersContainer]
			, delay: 250
			, start: startEvents
			, remain: remainEvents
			, end: endEvents
			, onEnter: function(){
				this.open();
			}.bind(this)
			, onLeave: function(){
				this.close();
			}.bind(this)
		});			
		if (this.options.alwaysOpen) {
			this.slidersContainer.setStyles({'position':'relative', 'top':'5px','left':'0px'});
			this.open();
		}		
		
	}
	, open: function(e) {
		if (!this.isOpen) {
			this.slidersContainer.setStyles({'display':'block','opacity':0}).fade(1);		
			this.isOpen = true;			
		}
	}
	, close: function(e) {
		if (this.isOpen && !this.options.alwaysOpen) {
			this.slidersContainer.fade(0);		
			this.isOpen = false;				
		}
	}
	, focus:function(e) {
		this.isOpen = true;
		this.slidersContainer.setStyles({'display':'block','opacity':0}).fade(1);
	}
	, blur:function(e) {
		this.updateFromInput(e,true);
		// if (this.options.openOnHover) {
		// 	this.slidersContainer.fade(0);	
		// 	this.isOpen = false;		
		// }					
		
	}
	, updateFromSliders:function() {
//dbug.log('update'+ this.colorValues);		
		this.calcHexFromValues(true);
	}
	, keyup:function(e) {
		if (e.key == 'enter') {
			e.stop();
			this.updateFromInput(e,true);
		} else {
			this.updateFromInput(e,false);			
		}
	}
	, updateFromInput:function(e, updateInput) {
//dbug.log(this.colorValues.sum());		
		var hex = this.element.get('value');
		if (hex.charAt(0)!='#') { hex = '#'+hex; }
		var len = hex.length;
		if (len < 7) {
			var missing = 7-len;
//dbug.log('missing:'+missing);
			hex = hex + '0'.repeat(missing);
		} else if (len > 7) {
			hex = hex.substr(0,7);
		}
		this.colorValues = hex.hexToRgb(true);
		this.updateInput = updateInput;
		this.calcHexFromValues(false);
	}
	, updateFromColorInput:function(i) {
		var thisval = this.inputs[i].get('value').toInt();
		if (isNaN(thisval)) { thisval = 0; }
		if (thisval > 255) { thisval = 255; }
		this.colorValues[i] = thisval;
		this.calcHexFromValues(true);
	}
	, calcHexFromValues:function(updateInput) {
		var hex = this.colorValues.rgbToHex();
		this.element.setStyle('background-color', hex);//
		if (this.updateInput == true) {
//dbug.log('input update');			
			this.element.set('value', hex);
		}
		this.inputHidden.set('value', hex);
		var sum = this.colorValues.sum();
		this.calcContrast();	
		if (this.options.autoFontColor) {	
			this.element.setStyle('color', this.fontColor);					
		}
		this.setSliders();	
		this.fireEvent('change', [hex, this.fontColor]);
		this.updateInput = true;	
	}
	, setSliders:function() {
		this.colorValues.each(function(val, i) {
			this.sliders[i].set(val);
		},this);
	}
	, calcContrast:function() {
		var contrast = false;
		if ( (this.colorValues[0] > this.options.contrastLimits[0]) 
			|| (this.colorValues[1] > this.options.contrastLimits[1]) 
			|| (this.colorValues[2] > this.options.contrastLimits[2]) 
			|| ((this.colorValues[0] > 225) && (this.colorValues[2] > 225))
		) {
			contrast = true;
		}
		if (contrast) { this.fontColor = '#000000'; } else { this.fontColor = '#ffffff'; }
	}
	
});
 mm.Switch = new Class({
	Implements: [Options, Events]
	, options: {
		elements: 'input[type=checkbox][class=mmSwitch]'
		, classContainer:'mmSwitchContainer'
		, classSlider: 'mmSwitchSlider'
		, classLabelOn: 'mmSwitchOn'
		, classLabelOff: 'mmSwitchOff'
		, classHandle: 'mmSwitchHandle'
		, labels: { on:'on', off:'off' }
		, size: { x: 60, y:20 }
		, sliderTween: { duration: 200, transition: 'circ:out' }
		, onSwitch : $empty

	}
	, initialize: function(el, options) {
		this.setOptions(options);
		this.labels = this.options.labels;
		if ($type(el)=='string') {
			elements = $$(el);
			elements.each(function(elem) {
				//this.setupSwitch(el);
				new mmSwitch(elem);
			},this);			
		} else if ($type(el)=='element') {
			this.element = document.id(el);			
			this.setupSwitch();
		}


	}
	, setupSwitch:function() {
		this.element.setStyles({'opacity':0});
		var alt = this.element.get('alt');
		if ($defined(alt) && alt.trim() !='') {
			var splitted = alt.split('_');
			if ($defined(splitted[0]) && $defined(splitted[1])) {
				this.labels.on = splitted[0];
				this.labels.off = splitted[1];				
			}
		}
		this.container = new Element('span',{
			'class': this.options.classContainer
		}).inject(this.element.getParent());
		this.container.setStyles({'width':this.options.size.x, 'height':this.options.size.y});
		this.dimensions = this.container.getSize();		
		var borderWidth = this.container.getStyle('borderWidth');
		var borderWidths = borderWidth.split(' ');
// dbug.log(this.container.getStyle('borderLeftWidth'));
		
// dbug.log('borderw = '+borderWidth);		
// dbug.log('bleft = '+borderWidths[1].toInt());
// dbug.log('bright = '+borderWidths[3].toInt());
		this.half = (this.dimensions.x - (borderWidths[1].toInt() + borderWidths[3].toInt()))/ 2;
		var newheight = this.dimensions.y - (borderWidths[0].toInt() + borderWidths[2].toInt());
		//this.half = (this.dimensions.x)/ 2;		
		this.slider = new Element('div', {'class':this.options.classSlider}).setStyles({'width':(this.half*3)+0,'height':newheight}).inject(this.container);		
		this.slider.set('tween', {duration:this.options.sliderTween.duration,transition:this.options.sliderTween.transition});
		this.labelOn = new Element('div', {'class':this.options.classLabelOn}).setStyles({'padding-right':'5px','width':this.half,'height':newheight,'line-height':newheight}).inject(this.slider);

		this.labelHandle = new Element('div', {'class':this.options.classHandle}).setStyles({'margin-left':'-5px','width':this.half,'height':newheight,'line-height':newheight}).inject(this.slider);
		var handleBorder = this.labelHandle.getStyle('borderLeftWidth').toInt();
		if (handleBorder > 0) {
			this.labelHandle.setStyles({'width':this.half - (handleBorder*2), 'height':newheight - (handleBorder*2),'line-height':newheight - (handleBorder*2)});
		}
		this.labelOff = new Element('div', {'class':this.options.classLabelOff}).setStyles({'width':this.half,'height':newheight,'line-height':newheight}).inject(this.slider);				
		this.labelOn.set('html', this.labels.on);
		this.labelOff.set('html', this.labels.off);	
		this.element.inject(this.container,'bottom');

		this.switchDrag = new Drag(this.slider, {
		    snap: 0
			, handle:this.labelHandle
			, modifiers:{x:'left',y:false}
			, limit: {x:[-(this.half),0],y:[0,0]}
			, onBeforeStart:function(el) {
// dbug.log('onBeforeStart')				
			}
			, onStart: function(el) {
				
			}
			, onDrag: function(el, e) {
				
			}
		    , onComplete: function(el){
				var left = el.getStyle('left').toInt();
// dbug.log('left = '+left);				
				//var range = (this.dimensions.x/2);
				var moved = 0 - left;
				if (moved > (this.half/2)) {
//					el.tween('left',-this.half);
					this.switchOnOff(false);
				} else {
					//el.tween('left',0);
					this.switchOnOff(true);
				}
		    }.bind(this)
		});
		
		this.labelOn.setStyle('cursor','pointer').addEvent('click', function(e) {
//			this.slider.tween('left',-this.half);
			this.switchOnOff(false);			
		}.bind(this));
		this.labelOff.setStyle('cursor','pointer').addEvent('click', function(e) {
//			this.slider.tween('left',0);
			this.switchOnOff(true);
		}.bind(this));		
		
		this.labelOn.addEvents({	
			'selectstart':function(){
				return false;
			},
			'mousedown':function(){
				return false;
			}
		});
		this.labelOff.addEvents({	
			'selectstart':function(){
				return false;
			},
			'mousedown':function(){
				return false;
			}
		});		
		
		this.on = this.element.get('checked');
		this.switchOnOff(this.on);
		/*
		if (this.on) {
			this.slider.setStyle('left', 0);
		} else {
			this.slider.setStyle('left', -this.half);			
		}
		*/
		
	}
	, switchOnOff:function(onoff) {
		if (onoff) {
			this.slider.tween('left',0);			
		} else {
			this.slider.tween('left',-this.half);			
		}
		this.on = onoff;		
		this.element.set('checked', onoff);
// dbug.log('input checked = '+this.element.get('checked'));	
//		if ($defined(this.options.onSwitch)) {
			this.fireEvent('switch',[onoff, this.element]);
//		}
	}
});

this.IPhoneCheckboxes = new Class({

	//implements
	Implements: [Options],

	//options
	options: {
	    changeEvent: $empty, // new, this is the callback function
		checkedLabel: '|',
		uncheckedLabel: '0',
		background: '#fff',
		containerClass: 'iPhoneCheckContainer',
		labelOnClass: 'iPhoneCheckLabelOn',
		labelOffClass: 'iPhoneCheckLabelOff',
		handleClass: 'iPhoneCheckHandle',
		handleBGClass: 'iPhoneCheckHandleBG',
		handleSliderClass: 'iPhoneCheckHandleSlider',
		elements: 'input[type=checkbox][class=mooswitch]'
	},

	//initialization
	initialize: function(options) {
		//set options
		this.setOptions(options);
		//elements
		this.elements = $$(this.options.elements);
		//observe checkboxes
		this.elements.each(function(el) {
			this.observe(el);
		},this);
	},

	//a method that does whatever you want
	observe: function(el) {
		//turn off opacity
		el.set('opacity',0);
		//create wrapper div
		var wrap = new Element('div',{
			'class': this.options.containerClass
		}).inject(el.getParent());
		//inject this checkbox into it
		el.inject(wrap);
		//now create subsquent divs and labels
		var handle = new Element('div',{'class':this.options.handleClass}).inject(wrap);
		var handlebg = new Element('div',{'class':this.options.handleBGClass,'style':this.options.background}).inject(handle);
		var handleSlider = new Element('div',{'class':this.options.handleSliderClass}).inject(handle);
		var offLabel = new Element('label',{'class':this.options.labelOffClass,text:this.options.uncheckedLabel}).inject(wrap);
		var onLabel = new Element('label',{'class':this.options.labelOnClass,text:this.options.checkedLabel}).inject(wrap);
		var rightSide = wrap.getSize().x - 39;
		//fx instances
		el.offFx = new Fx.Tween(offLabel,{'property':'opacity','duration':200});
		el.onFx = new Fx.Tween(onLabel,{'property':'opacity','duration':200});
		//mouseup / event listening
		wrap.addEvent('mouseup',function() {
		    // changed whole function, was not working well with over 50 checkboxes on screen
			var new_state = (el.get("checked")) ? false : true;

			var new_left = (new_state ? rightSide : 0), bg_left = (new_state ? 34 : 0);

			handlebg.hide();
			new Fx.Tween(handle,{
				duration: 100,
				'property': 'left',
				onComplete: function() {
					handlebg.setStyle('left',bg_left).show();
				}
			}).start(new_left);

			//label animations
			if (new_state) {
				el.offFx.start(0);
				el.onFx.start(1);
			}
			else {
				el.offFx.start(1);
				el.onFx.start(0);
			}

			//set checked
			el.set('checked', new_state);

			// run callback functions
			this.options.changeEvent.run([new_state, el]);
		}.bind(this));

		//initial load
		if (el.get("checked")) {
			offLabel.set('opacity',0);
			onLabel.set('opacity',1);
			handle.setStyle('left',rightSide);
			handlebg.setStyle('left',34);
		} else {
			onLabel.set('opacity',0);
			handlebg.setStyle('left',0);
		}
	}
});


/* example use to enable/disable products with an ajax callback:

new IPhoneCheckboxes({
    changeEvent: function(mystatus, el) {
        // full access to original element
        if (el.hasClass("prodEnable")) {
            var newstatus = (mystatus) ? "live" : "disabled";
            new Request({
                url: "admin.php",
                method: "get",
                onComplete: function() {
                    // do something, for example, fade out parent of checkbox element
                    var fadeTo = (newstatus == "disabled") ? .4 : 1;
                    el.getParent().getParent().getParent().fade(fadeTo);
                }
            }).send("a=productStatus&id=" + el.get("data-id") + "&i_status=" + newstatus);
        }
    }
});

*/ 
/*
	initial javascript start of application
*/
window.addEvent('domready', function() {
	//if (!Browser.Engine.trident) { dbug.enable(); }
//dbug.log('mm.runtime : ');	
//dbug.log(mm.runtime);
//dbug.log('mm.lang : ');
//dbug.log(mm.lang);
	mm.main.init();
});
 