/**
 */


	activity.mailing = Class.create(activity, {
		initialize:function($super, container, controller){
			$super(container, controller);
			this.instID = 'activity.mailing.' + parseInt(Math.random()*1000000);
			this.uploadTryCounter = 0;
			this.id = 0;
			this.name ='';
			this.description = '';
			this.message1 = '';
			this.message2 = '';
			this.message3 = '';
			this.message4 = '';
			this.message5 = '';
			this.title1 = '';
			this.title2 = '';
			this.title3 = '';
			this.title4 = '';
			this.title5 = '';

			this.url1 = '';
			this.url2 = '';
			this.url3 = '';
			this.url4 = '';
			this.url5 = '';
			
			this.imageAlign1 = '';
			this.imageAlign2 = '';
			this.imageAlign3 = '';
			this.imageAlign4 = '';
			this.imageAlign5 = '';
			
			this.senderName = '';
			this.senderEmail = '';
			this.subject = '';
			this.userData = '';
			this.myCommand = 'persclubMailing';
			
			// texts 
			this.previewTemplate = 'include/showTemplate.php?mailingID=';

			this.uploadWarning = "Om bestanden te koppelen dient u de nieuwsbrief eerst op te slaan";
			this.viewMailingText = "Nieuwsbrief bekijken";
			this.nameOfMailingText = "Naam van de nieuwsbrief* : ";
			this.descriptionOfMailingText = 'Optionele beschrijving van deze nieuwsbrief:<br/>';
			this.dateSelectText = '<b>Selecteer een datum waarop de nieuwsbrief verzonden moet worden:</b><br/>';
			this.dtToSendText = "<br/>Deze nieuwsbrief wordt verzonden op: <b>";
			this.dtToSentText = "<br/>Deze nieuwsbrief is verzonden op: <b>"; 
			this.selectListWarning = "Kies minimaal 1 lijst waar de nieuwsbrief naar verzonden zal worden:<br/>";
			this.sendMailConfirmText = 'Weet u zeker dat u de nieuwsbrief wilt versturen?';
			this.mailSentConfirmationText = "<blink>De nieuwsbrief is verzonden !</blink>";
			
			// get metadata
			var RPCObj = new rpc;
			RPCObj.debug = true;
			RPCObj.attachWaiter(function(){shader('', 'Even geduld a.u.b., bezig met ophalen van gegevens.')}, this);
			RPCObj.attachUnWaiter(unShader, this);
			RPCObj.createCall(this.myCommand, this.getUserMetaData.bind(this), this);
			RPCObj.call('getUserMetaData');
			
		},
		
		getUserMetaData : function(req){
			this.userData = req.responseJSON;
			if (!this.senderName) this.senderName = this.userData.naam;
			if (!this.senderEmail) this.senderEmail = this.userData.email;
			if ($(this.instID + '_senderName')) $(this.instID + '_senderName').value = this.senderName;
			if ($(this.instID + '_senderEmail')) $(this.instID + '_senderEmail').value = this.senderEmail;
			
			if (this.userData.datasetID == 0 || ( this.userData.accessToPersonification == 0 || this.userData.accessToPersonification == '' )  || this.userData.dsOK == 0){
				this.disablePersonification = true;
			}else{
				window.datasetID = this.userData.datasetID;
			}
			unWaiter();
			this.draw();
		},
		
		openActivity : function(mailingID){
			this.id = mailingID;
			var RPCObj = new rpc;
			RPCObj.debug = true;
//			RPCObj.attachWaiter(this.waiter, this);
//			RPCObj.attachUnWaiter(unWaiter, this);
			RPCObj.createCall(this.myCommand, this.setMailingValues.bind(this), this);	
			RPCObj.call('getMailing', 'mailingID=' + mailingID);
		},
		
		setMailingValues : function(req){
			var obj = req.responseJSON;
			for (index in obj){
				this[index] = obj[index];
			}
		//	this.draw();
		},
		
		draw : function(){
			unWaiter();
			unWaiter();
			this.container.update('');
			
			//add drawers:
			this.container.insert('<form name="'+this.instID + '_form" id="' +this.instID + '_form" action="/index.php" method="post" target="'+this.instID+'uploadIFrame" enctype="multipart/form-data">');
			var form = $(this.instID + '_form');
			
			var aContainer = this.addDrawer(form, 'Instellingen');
			this.drawSettings(aContainer);
			
			var aContainer = this.addDrawer(this.container, 'Email-lijst');
			this.getLists(aContainer, 'perclubBasket');
			this.getLists(aContainer, 'perclubPrivateBasket');
			
			var aContainer = this.addDrawer(this.container, 'Sjabloon');
			this.getTemplates(aContainer);

			// bericht 1
//			var form = new Element('form', {name:this.instID + '_form', id:this.instID + '_form', method:'post', action:'/index.php', target:this.instID+'uploadIFrame', enctype:'multipart/form-data'})
//			this.container.insert(form);
			
			var aContainer = this.addDrawer(form, 'Bericht deel 1', (function(){this.startTinyEditor('message1')}).bind(this) );
			this.getMessageProperties(aContainer, 1 );
			aContainer.insert('<textarea id="message1">' + recursivehtml_entity_decode(this.message1) + '</textarea>');

			// bericht 2
			var aContainer = this.addDrawer(form, 'Bericht deel 2', (function(){this.startTinyEditor('message2')}).bind(this) );
			this.getMessageProperties(aContainer, 2);
			aContainer.insert('<textarea id="message2">' + recursivehtml_entity_decode(this.message2) + '</textarea>');

			// bericht 3
			var aContainer = this.addDrawer(form, 'Bericht deel 3', (function(){this.startTinyEditor('message3')}).bind(this) );
			this.getMessageProperties(aContainer, 3);
			aContainer.insert('<textarea id="message3">' + recursivehtml_entity_decode(this.message3) + '</textarea>');

			// bericht 4
			var aContainer = this.addDrawer(form, 'Bericht deel 4', (function(){this.startTinyEditor('message4')}).bind(this) );
			this.getMessageProperties(aContainer, 4 );
			aContainer.insert('<textarea id="message4">' + recursivehtml_entity_decode(this.message4) + '</textarea>');

			// bericht 5
			var aContainer = this.addDrawer(form, 'Bericht deel 5', (function(){this.startTinyEditor('message5')}).bind(this) );
			this.getMessageProperties(aContainer, 5);
			aContainer.insert('<textarea id="message5">' + recursivehtml_entity_decode(this.message5) + '</textarea>');

			
			var aContainer = this.addDrawer(this.container, 'Attachments');
			this.writeFileUploader(aContainer);

			var aContainer = this.addDrawer(this.container, 'Verzending');
			this.setMessageTiming(aContainer);
			
			this.container.insert("</form>");

			this.statusBar = new Element('div', {id:this.instID + "_status", className:'activityStatus'})
			this.container.insert(this.statusBar);

			var ieContainer = new Element('div', {className:'ieContainer'});
			this.container.insert(ieContainer);

			var storeBttn = new Element('input', {type:'button', className:'type-button', value:'Hoofdmenu', id:this.instID + '_cancel', style:'float:left;'});
			ieContainer.insert(storeBttn);
			storeBttn.observe('click', this.goBack.bind(this))

			var sendBttn = new Element('input', {type:'button',className:'type-button', id:this.instID + '_send', style:'float:right;', value:'Versturen'});
			sendBttn.disabled = true;
			ieContainer.insert(sendBttn);
			sendBttn.observe('click', this.sendMailing.bindAsEventListener(this));

			var sendTestBttn = new Element('input', {type:'button',className:'type-button',id:this.instID + '_sendTest', style:'float:right;', value:"Testbericht versturen"});
			sendTestBttn.disabled = true;
			ieContainer.insert(sendTestBttn);
			sendTestBttn.observe('click', this.sendTestMail.bind(this));

			var previewBttn = new Element('input', {type:'button',className:'type-button', id:this.instID + '_preview', style:'float:right;', value:this.viewMailingText} );
			previewBttn.disabled = true;
			ieContainer.insert(previewBttn);
			previewBttn.observe('click', (function(){
				window.open(this.previewTemplate + this.id);
			}).bind(this))

			var storeBttn = new Element('input', {type:'button',className:'type-button', id:this.instID + '_store',style:'float:right;', value:"Opslaan"});
			ieContainer.insert(storeBttn);
			storeBttn.observe('click', this.saveActivity.bind(this))
			this.container.insert('<iframe name="'+this.instID+'uploadIFrame" id="'+this.instID+'uploadIFrame" width="0" frameborder="0" height="0"></iframe>');


			return ieContainer;
		},
		
		writeFileUploader:function(container){
			if ($('attachmentUploader')) $('attachmentUploader').remove();
			var div = new Element('div', {className:'uploader', id:'attachmentUploader'});
			container.insert(div);
			if (!this.id){
				var iframe = new Element('span').update(this.uploadWarning);
			}else{
				var iframe = new Element('iframe', {height:'75px', frameborder:'0',  border:'0', width:'100%', scrolling:'auto', src:'include/mailing_attachments.php?id=' + this.id});
				iframe.setStyle("border:1px black solid;");
			}
			div.insert(iframe);
		},
		
		getMessageProperties : function(container, index){
			var aValue = this['title' + index];
			if (!aValue || aValue == 'undefined') aValue = '';

			var tmpContainer = new Element('div', {className:'messageProperties'});
			container.insert(tmpContainer);

			var row = new Element('div', {className:'messagePropertiesRow'})
			tmpContainer.insert(row);
			var title = new Element('div', {className:'fieldTitle'}).update('Titel deel ' +index+':');
			row.insert(title);
			var input = new Element('input', {type:'text', id:this.instID + '_mailingTitle'+index, className:'activityInput', value:aValue});
			row.insert(input);

			var row = new Element('div', {className:'messagePropertiesRow'})
			tmpContainer.insert(row);

//			var form = new Element('form', {name:this.instID + '_form'+index, id:this.instID + '_form'+index, method:'post', action:'/index.php', target:'blank', enctype:'multipart/form-data', target:'uploadIFrame'});
//			row.insert(form);
			var title = new Element('div', {className:'fieldTitle'}).update('Afbeelding deel ' +index+':');
			row.insert(title);
			
			var input = new Element('input', {type:'file', id:this.instID + '_hidden'+index, 'name':this.instID + '_hidden'+index, className:'activityInput'});
			row.insert(input);
			
			var defaultHTML = '<div class="extraText">Let op: JPG-Afbeeldingen van maximaal 300 x 300 pixels in formaat en niet groter dan 512Kb.</div>';
			if (this['hasImageOnIndex' + index] == 'true'){
				row.insert('<div class="extraText" id="extraText'+index+'">U heeft reeds <a target="_blank" href="http://' + window.location.hostname +'/images/users/mailing_images/'+this.id+'/'+index+'.jpg">deze afbeelding</a> geupload. <a href="http://' + window.location.hostname +'/include/removeImage.php?mailingID='+this.id+'&index='+index+'" target="'+this.instID+'uploadIFrame" onclick="$(\'extraText'+index +'\').update(\'\')" >[afbeelding verwijderen]</a>');
				row.insert('<br/>Door een andere afbeelding te uploaden zult u de bestaande afbeelding overschrijven. <br/>Let op: JPG-Afbeeldingen van maximaal 300 x 300 pixels in formaat en niet groter dan 512Kb.</div>')
			}else{
				row.insert(defaultHTML)
			}
			input.observe('change', (function(e){
				var elem = e.element();
				var filename = elem.getValue();
				filename = filename.toLowerCase();
				var ext = filename.substring( filename.length-4, filename.length);
				if (ext != '.jpg' && ext != 'jpeg'){
					alert("Alleen bestanden van het type JPG zijn toegestaan");
					elem.value = '';
				}
			}).bindAsEventListener(this) )


			var row = new Element('div', {className:'messagePropertiesRow'})
			tmpContainer.insert(row);
			var title = new Element('div', {className:'fieldTitle'}).update('Plaatsing afbeelding deel ' +index+':');
			row.insert(title);
			var select = new Element('select', {id:this.instID + '_imageAlign'+index, className:'activityInput'});
			row.insert(select);
			
			var option = new Element('option', {value:'right'}).update("");
			select.insert(option);
			if (this['imageAlign'+index] == '') option.selected = true;

			var option = new Element('option', {value:'left'}).update("Links uitgelijnd");
			select.insert(option);
			if (this['imageAlign'+index] == 'left') option.selected = true;

			var option = new Element('option', {value:'right'}).update("Rechts uitgelijnd");
			select.insert(option);
			if (this['imageAlign'+index] == 'right') option.selected = true;
			
		},
		
		drawSettings : function(container){
			var div = new Element('div', {style:'padding:5px;'});
			container.insert(div);
			
			var input = new Element('input', {type:'text', id:this.instID + '_mailingName', className:'activityInput', value:this.name});
			div.insert(new Element('span', {className:'activityTitle'}).update(this.nameOfMailingText));
			div.insert(input);
			input.observe('change', this.updateTitle1.bindAsEventListener(this))
			div.insert('<br/>');

			
			var select = new Element('select', {id:this.instID + '_showTitle', className:'activityInput'});
			div.insert(new Element('span', {className:'activityTitle'}).update("Toon naam als titel in bericht: "));
			div.insert(select);
			
			var option = new Element('option', {value:'1'}).update("Ja");
			select.insert(option);
			if (this['showTitle'] == '1') option.selected = true;

			var option = new Element('option', {value:'0'}).update("Nee");
			select.insert(option);
			if (this['showTitle'] == ''||this['showTitle'] == '0') option.selected = true;

			div.insert('<br/>');
			
			var text = new Element('textarea', {id:this.instID + "_description", className:'activityInput'}).update(unescape(this.description));
			div.insert(new Element('span', {className:'activityTitle'}).update(this.descriptionOfMailingText));
			div.insert(text);
			
			div.insert('<br/>');

			var input = new Element('input', {type:'text', id:this.instID + '_senderName', className:'activityInput', value:this.senderName});
			div.insert(new Element('span', {className:'activityTitle'}).update("Afzender naam : "));
			div.insert(input);

			div.insert('<br/>');
			
			var input = new Element('input', {type:'text', id:this.instID + '_senderEmail', className:'activityInput', value:this.senderEmail});
			div.insert(new Element('span', {className:'activityTitle'}).update("Afzender adres : "));
			div.insert(input);
			div.insert('<div class="extraText"><span style="color:red;">Let op</span>: Indien u een Testbericht wil sturen, dan vult u hier het mailadres in van diegene waar het naar toe moet.</div>');
			div.insert('<br/>');

			var input = new Element('input', {type:'text', id:this.instID + '_subject', className:'activityInput', value:this.subject});
			div.insert(new Element('span', {className:'activityTitle'}).update("Email onderwerp : "));
			div.insert(input);
			
			div.insert('<br/>');
			
			
			var input = new Element('input', {type:'file', id:this.instID + '_titleFile', 'name':this.instID + '_titleFile', className:'activityInput'});
			div.insert(new Element('span', {className:'activityTitle'}).update("Afbeelding titel : "));
			div.insert(input);
		
			
			var defaultHTML = '<div class="extraText">Let op: JPG-Afbeeldingen van maximaal 300 x 300 pixels in formaat en niet groter dan 512Kb.</div>';
			if (this['hasImageOnTitle'] == 'true'){
				div.insert('<div class="extraText" id="extraText">U heeft reeds <a target="_blank" href="http://' + window.location.hostname +'/images/users/mailing_title_images/'+this.id+'.jpg">deze afbeelding</a> geupload. <a href="http://' + window.location.hostname +'/include/removeTitleImage.php?mailingID='+this.id+'" target="'+this.instID+'uploadIFrame" onclick="$(\'extraText\').update(\'\')" >[afbeelding verwijderen]</a>');
				div.insert('<br/>Door een andere afbeelding te uploaden zult u de bestaande afbeelding overschrijven. <br/>Let op: JPG-Afbeeldingen van maximaal 300 x 300 pixels in formaat en niet groter dan 512Kb.</div>')
			}else{
				div.insert(defaultHTML)
			}
			input.observe('change', (function(e){
				var elem = e.element();
				var filename = elem.getValue();
				filename = filename.toLowerCase();
				var ext = filename.substring( filename.length-4, filename.length);
				if (ext != '.jpg' && ext != 'jpeg'){
					alert("Alleen bestanden van het type JPG zijn toegestaan");
					elem.value = '';
				}
			}).bindAsEventListener(this) )

			div.insert('<br/>');
			
			var select = new Element('select', {id:this.instID + '_titleImageAlign', className:'activityInput'});
			div.insert(new Element('span', {className:'activityTitle'}).update("Plaatsing titel-afbeelding : "));
			div.insert(select);
			
			var option = new Element('option', {value:'right'}).update("");
			select.insert(option);
			if (this['titleImageAlign'] == '') option.selected = true;

			var option = new Element('option', {value:'left'}).update("Links uitgelijnd");
			select.insert(option);
			if (this['titleImageAlign'] == 'left') option.selected = true;

			var option = new Element('option', {value:'right'}).update("Rechts uitgelijnd");
			select.insert(option);
			if (this['titleImageAlign'] == 'right') option.selected = true;			
			
		},
		
		setMessageTiming:function(container){
			var div = new Element('div', {id:this.instID + "_calContainer"});
			container.insert(div);
			div.insert(this.dateSelectText);
			if (this.dtToSent){
				var dtArr = this.dtToSent.split(' ');
				var timeArr = dtArr[1].toString().split(":");
				dtArr = dtArr[0].split('-');
				var aDate =  new Date();
				aDate.setFullYear(dtArr[0]);
				aDate.setMonth((dtArr[1] - 1));
				aDate.setDate(dtArr[2]);
				aDate.setHours(timeArr[0]);
				aDate.setMinutes(timeArr[1]);
			}else{
				aDate = new Date();
			}
            setTimeout( (function(){
            	Calendar.setup(
                    {
                        flat: this.instID + "_calContainer",
                        flatCallback : this.dateChanged.bind(this),
                        showsTime : true,
                        date : aDate,
					    timeFormat : '24'                        
                    });
            	}).bind(this), 50);

			div.insert('<div id="' + this.instID + '_dateMsgContainer"></div>')
			if (this.dtToSent){
				if (aDate > (new Date())){
					var div = new Element('div').update(this.dtToSendText + aDate.toString() + "</b><br/>");
				}else{
					var div = new Element('div').update(this.dtToSentText + aDate.toString() + "</b><br/>");
				}
				$(this.instID + '_dateMsgContainer').update(div);
			}
		},
			
		dateChanged : function(dateObj){
			this.sendDate = dateObj;
			var div = new Element('div').update(this.dtToSentText + dateObj.date.toString() + "</b><br/>");

			$(this.instID + '_dateMsgContainer').update(div);
			var button = new Element('input', {type:'button', value:'reset datum'});
			div.insert(button)
			button.observe('click', this.resetDate.bind(this));
		},
		
		resetDate : function(){
			this.sendDate = '';
			$(this.instID + '_dateMsgContainer').update('');
		},
		
		getLists : function(container, command){
			var callBack = (function(req){this.drawLists(req, container, command)}).bind(this)
			var RPCObj = new rpc;
			RPCObj.debug = true;
			RPCObj.attachWaiter(this.waiter, this);
			RPCObj.attachUnWaiter(unWaiter, this);
			RPCObj.createCall(command, callBack, this);
			RPCObj.call('getBasketList');
		},
		
		drawLists : function(req, container, command){
			var div = new Element('div', {style:'padding:5px;'});
			div.insert(this.selectListWarning)
			if (!req.responseJSON || !req.responseJSON.data){
				return;
			}
			var lists = req.responseJSON.data;
			lists.each(
				(function(list){
					var checkbox = new Element('input', {type:'checkbox', id:'selectedList' + list.id, className:'activityListSelect',value:list.id});
					checkbox.command = command;
					if (list.items){
						var listCount = list.items.length;
					}else{
						var listCount = 0;
					}
					if (!listCount) listCount  = " geen ";
					
					if (command == 'perclubPrivateBasket'){
						var label = new Element('label', {'for':'selectedList' + list.id}).update(list.name + "(" + listCount + " items, priv&euml;-lijst)");
					}else{
						var label = new Element('label', {'for':'selectedList' + list.id}).update(list.name + "(" + listCount + " items)");
					}
					container.insert(checkbox);
					container.insert(label);
					container.insert("<br/>");
					if (this.basket_id && this.basket_id.indexOf(parseInt(list.id)) > -1) checkbox.checked = true;
					if (this.private_basket_id && this.private_basket_id.indexOf(parseInt(list.id)) > -1) checkbox.checked = true;
				}).bind(this)
			)
			if (this.id ) this.validateBeforeSend();
		},

		getTemplates : function(container){
			var callBack = (function(req){this.drawTemplates(req, container)}).bind(this)
			var RPCObj = new rpc;
			RPCObj.debug = true;
			RPCObj.attachWaiter(this.waiter, this);
			RPCObj.attachUnWaiter(unWaiter, this);
			RPCObj.createCall(this.myCommand, callBack, this);
			RPCObj.call('getTemplates');
		},

		drawTemplates : function(req, container){
			var div = new Element('div', {style:'padding:5px;'});
			container.insert(div);
			div.insert("Kies een sjabloon<br/>")
			if (!req.responseJSON) return;
			var lists = req.responseJSON;
			lists.each(
				(function(list){
					var checkbox = new Element('input', {'name':'selectedTemplate',type:'radio', id:'selectedTemplate' + list.id, className:'templateSelect',value:list.id});
					var label = new Element('label', {'for':'selectedList' + list.id}).update(list.name);
					var preview = new Element('a', {href:'include/showTemplate.php?templateID=' + list.id, target:"_blank"}).update('[bekijken]');
					label.insert(preview);	
					container.insert(checkbox);
					container.insert(label);
					container.insert("<br/>");
					if (list.id == this.template_id) checkbox.checked = true;
				}).bind(this)
			)
			if (this.id ) this.validateBeforeSend();
		},
		
		showTemplate : function(event){
			var win = window.open("", "win", "width=600,height=500"); // a window object
			win.document.open("text/html", "replace");
			win.document.write(unescape(event.element().header) + unescape(event.element().footer));
		},
		
		saveActivity: function(){
			if (this.validateSave()){
				// save mailing
				this.statusBar.update("<blink style=\"font-weight:bold;\">Even geduld A.U.B, bezig met opslaan.</blink>");
				this.saveMailing();
			}else{
				this.statusBar.update("Niet alle velden zijn correct ingevuld.")
			}
		},
		
		validateBeforeSend : function(){
			return this.validateSave(true);
		},
		
		validateSave : function(checkForSend){
			if (!checkForSend) checkForSend=false;
			// check if all values are OK to save
			var ok = true;
			var okForSend = true;
			this.resetDrawerStatus();
			
			// check mailing-settings:
			if ( !$(this.instID + '_mailingName') || !$(this.instID + '_mailingName').getValue()){
				ok = false;
				okForSend = false;
				if ($(this.instID + '_mailingName')) $(this.instID + '_mailingName').setStyle('background-color:#ff9898;')
				this.setDrawerStatus('Instellingen', 'fatal');
			}else{
				this.setDrawerStatus('Instellingen', 'ok');
				if ($(this.instID + '_mailingName')) {
					$(this.instID + '_mailingName').setStyle('background-color:#98ff9f;');
					this.name = ($(this.instID + '_mailingName').getValue());
				}
			}
			
			// check sendername:
			if ( !$(this.instID + '_senderName') || !$(this.instID + '_senderName').getValue()){
				ok = false;
				okForSend = false;
				if ($(this.instID + '_senderName')) $(this.instID + '_senderName').setStyle('background-color:#ff9898;')
				this.setDrawerStatus('Instellingen', 'fatal');
			}else{
				this.setDrawerStatus('Instellingen', 'ok');
				if ($(this.instID + '_senderName')) {
					$(this.instID + '_senderName').setStyle('background-color:#98ff9f;');
					this.senderName = $(this.instID + '_senderName').getValue();
				}
			}

			// check senderEmail:
			if ( !$(this.instID + '_senderEmail') || !$(this.instID + '_senderEmail').getValue()){
				ok = false;
				okForSend = false;
				if ($(this.instID + '_senderEmail')) $(this.instID + '_senderEmail').setStyle('background-color:#ff9898;')
				this.setDrawerStatus('Instellingen', 'fatal');
			}else{
				this.setDrawerStatus('Instellingen', 'ok');
				if ($(this.instID + '_senderEmail')) {
					$(this.instID + '_senderEmail').setStyle('background-color:#98ff9f;');
					this.senderEmail = $(this.instID + '_senderEmail').getValue();
				}
			}

			// check subject:
			if ( !$(this.instID + '_subject') || !$(this.instID + '_subject').getValue()){
				ok = false;
				okForSend = false;
				if ($(this.instID + '_subject')) $(this.instID + '_subject').setStyle('background-color:#ff9898;')
				this.setDrawerStatus('Instellingen', 'fatal');
			}else{
				this.setDrawerStatus('Instellingen', 'ok');
				if ($(this.instID + '_subject')) {
					$(this.instID + '_subject').setStyle('background-color:#98ff9f;');
					this.subject = $(this.instID + '_subject').getValue();
				}
			}

			// check list-selection:
			var selectedLists = []; 
			$$('.activityListSelect').each(
				function(input){
					if (input.checked) selectedLists.push(input.value);
				}
			)
			
			if (selectedLists.length < 1){
				this.setDrawerStatus('Email-lijst', 'error');
				okForSend = false;
			}else{
				this.setDrawerStatus('Email-lijst', 'ok');
			}

			// check template:
			var selectedTemplates = $$('.templateSelect').findAll(
					function(input){
						if (input.checked) {
							return input;
						}
					}
				)

			if (selectedTemplates.length < 1){
				okForSend = false;
				this.setDrawerStatus('Sjabloon', 'error');
			}else{
				this.setDrawerStatus('Sjabloon', 'ok');
			}
			// check messages
			for (var i=1;i<6;i++){
				var ed = tinyMCE.get('message'+i);
				if (ed){
					tinyMCE.execCommand('mceCleanup');
					try{
						this['message'+i] = ed.getContent();
					}catch(e){
						var ed = '';
					}
				}
				
				if (i==1){
					// check if at least message 1 has a value:
					if (this.message1.length < 1){
						okForSend = false;
						this.setDrawerStatus('Bericht deel 1', 'error');
					}else{
						this.setDrawerStatus('Bericht deel 1', 'ok');
					}
				}else{
					this.setDrawerStatus('Bericht deel '+i, 'ok');
				}
				this['imageAlign' +i] = $(this.instID + '_imageAlign' + i).getValue();
				this['title' +i] = $(this.instID + '_mailingTitle' + i).getValue();
			}
			this['titleImageAlign'] = $(this.instID + '_titleImageAlign').getValue();
			this['showTitle'] = $(this.instID + '_showTitle').getValue();

			var ed = tinyMCE.get(this.instID + '_description');
			if (ed){
				try{
					this.description = ed.getContent();
				}catch(e){
					var ed = '';
				}
			}else{
				this.description = $(this.instID + '_description').getValue();
			}
			this.setDrawerStatus('Verzending', 'ok');
			if (okForSend){
				$(this.instID + '_send').disabled = false;
				$(this.instID + '_sendTest').disabled = false;
				$(this.instID + '_preview').disabled = false;
				if ($(this.instID + '_landingPreview')) $(this.instID + '_landingPreview').disabled = false;
			}else{
				$(this.instID + '_send').disabled = true;
				$(this.instID + '_sendTest').disabled = true;
				$(this.instID + '_preview').disabled = true;
				if ($(this.instID + '_landingPreview')) $(this.instID + '_landingPreview').disabled = true;
			}
			
			if (checkForSend) return okForSend;
			return ok;
		},
		
		saveMailing : function(callBack){
			this.statusBar.update("Bezig met opslaan...");
			if (!callBack) callBack = this.handleSave.bind(this);
			var RPCObj = new rpc;
			RPCObj.debug = true;
			RPCObj.createCall(this.myCommand, '', this);
			RPCObj.setMethod('saveMailing');

			RPCObj.attachWaiter(function(){shader('', "Even geduld a.u.b, bezig met opslaan")}, this);
			RPCObj.attachUnWaiter(unShader, this);

			RPCObj.addArgument('mailingID', this.id);
			RPCObj.addArgument('name', encodeURIComponent(this.name));
			RPCObj.addArgument('titleImageAlign', this.titleImageAlign);
			RPCObj.addArgument('showTitle', this.showTitle);
			RPCObj.addArgument('senderName', this.senderName);
			RPCObj.addArgument('senderEmail', this.senderEmail);
			RPCObj.addArgument('subject', encodeURIComponent(this.subject));
			RPCObj.addArgument('description', '<![CDATA[' + encodeURIComponent(this.description) + " ]]>");
			
			for (var i=1;i<6;i++){
				RPCObj.addArgument('title'+i, encodeURIComponent(this['title'+i]));
				var ed = tinyMCE.get('message'+i);
				if (ed){
					RPCObj.addArgument('message' + i, '<![CDATA[' + encodeURIComponent(this['message'+i])+ " ]]>");
				}
				RPCObj.addArgument('imageAlign'+i, this['imageAlign'+i]);
			}
			
			if (this.sendDate) {
				var minutes = this.sendDate.date.getMinutes();
				if (minutes < 10){
					var minutes = '0' + minutes.toString();  
				}
				var date = this.sendDate.date.getFullYear() + "-" + (this.sendDate.date.getMonth()+1) + "-" + this.sendDate.date.getDate() + " " + this.sendDate.date.getHours() + ":" + minutes + ":00";
				RPCObj.addArgument('dtToSent', '<![CDATA[' + (date)+ " ]]>");
			}
			// add selected lists:
			var selectedLists = [];
			var selectedPrivateLists = []; 
			$$('.activityListSelect').each(
				function(input){
					if (input.checked){
						if (input.command == 'perclubPrivateBasket'){
							selectedPrivateLists.push(input.value);
						}else{
							selectedLists.push(input.value);
						}
					}
				}
			)
			if (selectedLists[0]) {
//				selectedLists = selectedLists[0].getValue();
				RPCObj.addArgument('basket_id', selectedLists.join(','));
			}else{
				RPCObj.addArgument('basket_id', '');
			}
			if (selectedPrivateLists[0]) {
//				selectedLists = selectedLists[0].getValue();
				RPCObj.addArgument('private_basket_id', selectedPrivateLists.join(','));
			}else{
				RPCObj.addArgument('private_basket_id', '');
			}
			
			// add selected template:
			var selectedTemplates = $$('.templateSelect').findAll(
				function(input){
					if (input.checked) return input;
				}
			)
			if (selectedTemplates[0]) {
				selectedTemplates = selectedTemplates[0].getValue();
				RPCObj.addArgument('template_id', selectedTemplates);
			}

			RPCObj.setCallback(callBack);
			RPCObj.call();			

		},
		
		startTinyEditor : function(elemID){
			if (this.disablePersonification ){
	            this.tiny = tinyMCE.init({
	                mode : "exact",
	                elements : elemID,
	                theme : "advanced",
	                plugins : "safari,iespell",
	                theme_advanced_buttons1 : "bold,italic,underline,separator,advimage,code,separator,bullist,numlist,undo,redo,link,unlink,iespell",
	                theme_advanced_buttons2 : "",
	                theme_advanced_buttons3 : "",
	                theme_advanced_toolbar_location : "bottom",
	                theme_advanced_toolbar_align : "left",
	                theme_advanced_path_location : "none",
	                extended_valid_elements : "label[class|data]",
	                language : "nl",
	                docs_language : "nl",
	                language : "en",
	                gecko_spellcheck : true,
	                verify_css_classes : true, 
	                encoding : "xml", 
	                width:"100%",
	                height:"250px"
	            });
			}else{
	            this.tiny = tinyMCE.init({
	                mode : "exact",
	                elements : elemID,
	                theme : "advanced",
	                plugins : "persclub,safari,iespell",
	                theme_advanced_buttons1 : "persclub,bold,italic,underline,separator,advimage,code,separator,bullist,numlist,undo,redo,link,unlink,iespell",
	                theme_advanced_buttons2 : "",
	                theme_advanced_buttons3 : "",
	                theme_advanced_toolbar_location : "bottom",
	                theme_advanced_toolbar_align : "left",
	                theme_advanced_path_location : "none",
	                extended_valid_elements : "label[class|data]",
	                language : "nl",
	                docs_language : "nl",
	                language : "en",
	                gecko_spellcheck : true,
	                verify_css_classes : true, 
	                encoding : "xml", 
	                width:"100%",
	                height:"250px"
	            });
			}
			if ($(this.instID + '_mailingURL1') && $(this.instID + '_mailingURL1').getValue() !=''){
				this.hideTiny(); 
			}
		},
		
		hideTiny : function(){
			/* Hide Tiny also removes the template selection */
			
			$$('.templateSelect').each( 
					function(e){
						e.checked = false
						e.disabled = true;
					} 
			)
			
			if ($$('.mceEditor')[0]){
				$$('.mceEditor')[0].hide();
			}else{
				setTimeout(
					(function(){this.hideTiny()}).bind(this),250
				)
			}
		},
		
		sendTestMail : function(){
			this.statusBar.update("Voorbereiden verzenden testmail.");
			if (this.validateBeforeSend()){
				this.saveMailing(this._sendTestMail.bind(this));
			}
		},
		
		_sendTestMail : function(){
			var RPCObj = new rpc;
			RPCObj.debug = true;
			RPCObj.attachWaiter(this.waiter, this);
			RPCObj.attachUnWaiter(unWaiter, this);
			RPCObj.createCall(this.myCommand, this.handleTestMail.bind(this), this);
			RPCObj.call('sendTestMail', 'mailingID=' + this.id);
		},
		
		handleTestMail : function(req){
			this.statusBar.update("<blink>Er zijn 2 test-emails (een text-email en een HTML-email) verzonden naar " + this.senderEmail + ".</blink>");
		},
		
		sendMailing : function(){
			if (this.validateBeforeSend()){
				if (confirm(this.sendMailConfirmText)){
					if (this.disablePersonification){
						// no personification; just store and send the stuff;
						this.saveMailing(
							(function(){
								shader('', "Even geduld a.u.b., de mailing wordt verzonden.");
								this._sendMailing();
							}).bind(this) )
								
					}else{
						// there is personification
						shader('', "Even geduld a.u.b. de gegevens worden voorbereid (dit kan even duren).");
						this.updateDataSet();
					}
				}
			}
		},
		
		updateDataSet : function(){
			var RPCObj = new rpc;
			RPCObj.debug = true;
			RPCObj.attachWaiter(this.waiter, this);
			RPCObj.attachUnWaiter(unWaiter, this);
			RPCObj.createCall(this.myCommand, this.getUpdateStatus.bind(this), this);
			RPCObj.call('updateDataSet', 'mailingID=' + this.id);
		},
		
		getUpdateStatus : function(req){
			if (req.responseJSON.updating == 0){
				unShader();
				this.saveMailing(
					(function(){
						shader('', "Even geduld a.u.b., de mailing wordt verzonden.");
						this._sendMailing();
					}).bind(this) )
					return;
			}else if (req.responseJSON.updating == 2){
				// ERROR
				unShader();
				this.statusBar.update("Er is een error opgetreden, mailing kan op dit moment niet verzonden worden.");
				shader('', " Er is een fout opgetreden bij het versturen van gegevens, de mailing kan niet verzonden worden. De mailing is wel opgeslagen. <br/>Neem contact op met de helpdesk en geef hierbij de volgende gegevens door:<br/>Dataset-update-error, DsID:" +  req.responseJSON.dsID + ", mailingID:" + this.id);
				return;
			}else{
				var RPCObj = new rpc;
				RPCObj.debug = true;
				RPCObj.attachWaiter(this.waiter, this);
				RPCObj.attachUnWaiter(unWaiter, this);
				RPCObj.createCall(this.myCommand, this.getUpdateStatus.bind(this), this);
				RPCObj.addArgument('mailingID', this.id);
				RPCObj.addArgument('dsID', req.responseJSON.dsID);
				RPCObj.call('getUpdateStatus');
			}
		},
		
		_sendMailing : function(){
			var RPCObj = new rpc;
			RPCObj.debug = true;
			RPCObj.attachWaiter(this.waiter, this);
			RPCObj.attachUnWaiter(unWaiter, this);
			RPCObj.createCall(this.myCommand, this.handleSendMailing.bind(this), this);
			RPCObj.call('sendMailing', 'mailingID=' + this.id);
		},
		
		handleSendMailing : function(req){
			unShader();
			if (req.responseJSON.message == 'true'){
				this.statusBar.update(this.mailSentConfirmationText);
			}else{
				this.statusBar.update("<blink>Er is een fout opgetreden : [" + req.responseJSON.message + "].</blink>");
			}
		},
		
		handleSave : function(req){
			if (req.responseJSON.message){
				shader("", "Er is een fout opgetreden bij het verwerken van de mailing, de mailing is opgeslagen maar kan niet verzonden worden. <br/>Neem contact op met de helpdesk <br/>(errormelding: " + req.responseJSON.message + ")");
				return;
			}

			if (this.id == 0){
				this.id = req.responseJSON.mailingID;
			}
			this.id = req.responseJSON.mailingID;
			var hasFiles = false;
			for (var i=1;i<6;i++){
				if ( $(this.instID + '_hidden'+i).getValue()){
					hasFiles = true;	
				}
			}
			if ( $(this.instID + '_titleFile').getValue()){
				hasFiles = true;	
			}
			if (hasFiles){
				this.statusBar.update("Bezig met uploaden bestanden .... ");
				this.handleUploads();
			}else{
				this.statusBar.update("Opgeslagen!");
			}
		},
		
		handleUploads : function(){
			var form = $(this.instID + '_form');
			
			var hidden = new Element('input', {type:'hidden', name:'rpc', value:'1'});
			form.insert(hidden);

			var hidden = new Element('input', {type:'hidden', name:'action', value:this.myCommand});
			form.insert(hidden);

			var hidden = new Element('input', {type:'hidden', name:'xmlReq', value:'<command><call><method>storeImages</method><arg>mailingID='+this.id+'</arg></call></command>'});
			form.insert(hidden);
			
			form.submit();
			this.checkUploadStatus();
		},
		
		checkUploadStatus : function(e){
			if (Prototype.Browser.IE){
				// catch crappy browsers:
				var iFrameDOM = window.frames[this.instID+'uploadIFrame'].document;//.getElementsByTagName('message').length;
			}else{
				var iFrameDOM = $(this.instID+'uploadIFrame').contentDocument;
			}
			if (this.uploadTryCounter >= 600){
				alert("Er is een storing opgetreden bij het uploaden van uw afbeeldingen, probeer het a.u.b. nog een keer of neem contact op met de webmaster.");
				return;
			}
			if ( ( !iFrameDOM ||  iFrameDOM.getElementsByTagName('message').length == 0) && (this.uploadTryCounter < 600) ){ //  hardcoded timeout of 120 seconds!
				this.uploadTryCounter++;
				setTimeout(this.checkUploadStatus.bind(this), 1000);
				return;
			}
			this.uploadTryCounter= 0;
			this.statusBar.update("Opgeslagen!");
		}
				
		
	})
