$(document).ready(function()
{
	$.ajaxSetup({cache:false});

	$("#nieuwsbriefaanmeldform").validate({
		meta: "validate",
		submitHandler: function(){
			$('#nieuwsbriefaanmeldform').ajaxSubmit({
				beforeSubmit: function(){
					AjaxLoader(true);
				},
				success: function(html){
					CloseAjaxLoader(true);
                                        //dialog("test");
					$('#nieuwsbriefdiv').html(html);
				}
			});
		}
	});

	$('#lidzoeken').ajaxForm({
		beforeSubmit: function(){
			AjaxLoader(true);
		},
		success: function(html){
			CloseAjaxLoader(true);
			//$.prompt(html);
			$('#zoekdiv').html(html);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			$.prompt(XMLHttpRequest['responseText'], {width:500});
		}
	});
	
	$("#groepselect").multiSelect({
		selectAllText: 'Alle groepen',
		noneSelected : 'Selecteer groep(en)',
		oneOrMoreSelected: '% groepen geselecteerd'
	});
	
	
	$('.tablesorter').tablesorter();

	var path = 'fckeditor/';
	
	$.fck.config = {
		path: path,
		height: 600,
		width: 680
	};

	// initialize
	$('textarea.fck').fck({
		toolbar: 'Default'
	});

	$('#editnieuwsbrief').ajaxForm({
		dataType: 'json',
		beforeSubmit: function(){
			AjaxLoader(true);
		},
		success: function(json){
			CloseAjaxLoader(true);
			if(json.success){
				window.location.href = 'backoffice/nieuwsbrief/overzicht_brieven/';
			}
		}
	});
	// ---------------------------------------------------------------------------------- ledenlijst groepen
	$('#add').click(function() {
		return !$('#alle_leden option:selected').remove().appendTo('#leden_ingroep');
	});
	$('#remove').click(function() {
		return !$('#leden_ingroep option:selected').remove().appendTo('#alle_leden');
	});
	$('form').submit(function() {
		$('#leden_ingroep option').each(function(i) {
			$(this).attr("selected", "selected");
		});
		$('#alle_leden option').each(function(i) {
			$(this).attr("selected", "selected");
		});
	});

		
	
	// ---------------------------------------------------------------------------------- ledenlijst groepen

	/* autocomplete */
	/*
	$("#lidzoeken").autocomplete('backoffice/nieuwsbrief/leden/autocomplete', {
		max: 12,
		autoFill: true,
		scrollHeight: 220,
		minChars: 0,
		width: 310,
		matchContains: true
	});
	*/
});

function EditUser(root, id){
	$.ajaxSetup({cache:false});
	AjaxLoader(true);
}

function DeleteUser(root, id){
	
	$.ajaxSetup({cache:false});
	AjaxLoader(true);
	$.ajax({
		cache: false,
		method: "get",
		url: root + "backoffice/nieuwsbrief/leden/deleteuser/" + id,
		dataType: 'json',
		success: function(json){
			ShowMessage(json);
			if(json.success){
				$('#row_' + id).hide();
			} else {
				alert('test');
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown);
		}
	});
	CloseAjaxLoader(true);
}

function PreviewLetter(url){
	$.ajaxSetup({cache:false});
	$('#editnieuwsbrief').ajaxSubmit({
		dataType: 'json',
		success: function(json){
			if(json.success){
				var link = url + 'backoffice/nieuwsbrief/preview/' + json.id;
				//alert(link);
				$('#letterid').val(json.id);
				$('#previewletter').load(link);
				$('#brief_nieuw').slideUp('slow', function(){
					$('#previewletter').slideDown('slow');
					$('#previewbutton').show();
				});
			}
		}
	});
}

function ClosePreview(){
	$('#previewbutton').hide();
	$('#previewletter').slideUp('slow', function(){
		$('#brief_nieuw').slideDown('slow');
		$('#previewletter').html('');
	});
}

function DeleteNieuwsbrief(root, id){
	$.ajaxSetup({cache:false});
	$.ajax({
		cache: false,
		method: "get",
		url: root + "backoffice/nieuwsbrief/deletenieuwsbrief/" + id,
		dataType: 'json',
		success: function(json){
			ShowMessage(json);
			if(json.success){
				$('#row_' + id).hide();
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown);
		}
	});
}

function changesendtype(type, id){
	if(type == 'test'){
		$('#sendontvangersdiv').hide();
		$('#sendnieuwdiv').hide();
		$('#sendtestdiv').show();
	} else if (type == 'nieuw') {
		$('#sendtestdiv').hide();
		$('#sendontvangersdiv').hide();
		SendNieuwLeden(id);
	} else {
		$('#sendtestdiv').hide();
		$('#sendnieuwdiv').hide();
		$('#sendontvangersdiv').show();
	}
}

function SendNieuwLeden(id){
	$.ajax({
		cache: false,
		method: "get",
		url: "backoffice/nieuwsbrief/GetNewMembers/" + id,
		success: function(html){
			$('#sendnieuwdiv').html(html);
			$("#recievers").multiSelect({
				selectAllText: 'Alle nieuwe leden',
				noneSelected : 'Selecteer leden',
				oneOrMoreSelected: '% leden geselecteerd'
			});
			$('#sendnieuwdiv').slideDown('slow');
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown);
		}
	});
}

function SendLetter(){
	$.ajaxSetup({cache:false});
	var optie = $('.optie:checked').val();
	if(optie == 'test'){
		$('#verzendform1').ajaxSubmit({
			beforeSubmit: function(){
				AjaxLoader(true);
			},
			success: function(html){
				CloseAjaxLoader(true);
				$('#verzenddiv').hide();
				$('#testdiv').html(html);
			}
		});
	} else if(optie == 'live' || optie == 'live_new'){
		SendLiveLetters();
	}	
}

function SendLiveLetters(){

	$.ajaxSetup({cache:false});
	$('#verzendform1').ajaxSubmit({
		beforeSubmit: function(){
			AjaxLoader(true);
		},
		success: function(html){
			
			if(html == 'klaar'){
				SendLettersRun();
			} else {
				$('#verzenddiv').hide();
				$('#testdiv').html(html);
				CloseAjaxLoader(true);
			}
		}
	});
}

function SendLettersRun(){
	$('#verzenddiv').hide();
	$('#testdivhead').html('Op dit moment wordt de nieuwsbrief verzonden.<br /><br />');
	SendToEmail(0);
}

function SendToEmail(aantal){
	var id = $('#letterid').val();
	$.ajax({
		cache: false,
		method: "get",
		url: "backoffice/nieuwsbrief/send_letter_now/" + id + "/" + aantal,
		dataType: 'json',
		success: function(json){
			if(json.success){
				if(json.klaar){
					$('#testdiv').html('De nieuwsbrief is naar '+json.aantal+' ontvangers gestuurd.');
					CloseAjaxLoader(true);
				} else {
					$('#testdiv').html('De nieuwsbrief is naar '+json.aantal+' ontvangers gestuurd.');
					SendToEmail(json.aantal);
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			showError(XMLHttpRequest['responseText']);
		}
	});
}

function SendFailEmail(id, teller){
	var aantal = (teller) ? teller : 0;
	if (!teller) {
		$('#testdivhead').html('Op dit moment wordt de nieuwsbrief verzonden.<br /><br />');
		AjaxLoader(true);
	}
	$.ajax({
		cache: false,
		method: "get",
		url: "backoffice/nieuwsbrief/send_letter_now/" + id + "/" + aantal,
		dataType: 'json',
		success: function(json){
			if(json.success){
				if(json.klaar){
					$('#waring_'+id).hide();
					$('#waring_'+id).remove();
					$('#testdiv').html('De nieuwsbrief is naar '+json.aantal+' ontvangers gestuurd.');
					CloseAjaxLoader(true);
				} else {
					$('#testdiv').html('De nieuwsbrief is naar '+json.aantal+' ontvangers gestuurd.');
					SendFailEmail(json.aantal, id);
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			showError(XMLHttpRequest['responseText']);
		}
	});
}

function ValidateEmails(run){
	var type = (run) ? run : 1;
	AjaxLoader(true);
	$.ajax({
		cache: false,
		method: "get",
		url: "backoffice/nieuwsbrief/leden/valideren/"+type,
		//dataType: 'json',
		success: function(html){
			CloseAjaxLoader(true);
			if ( type == 1 ) {
				$('#vuldiv').html(html);
				ValidateEmails(2);
			} else {
				$('#vuldiv').append(html);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			showError(XMLHttpRequest['responseText']);
		}
	});
}

function SetDefaultMail(id){
	var tekst;
	var image;
	var alt;
	if($('#default_'+id).attr('alt') == 'is_niet_default'){
		tekst = 'Weet je zeker dat je deze nieuwsbrief in wilt stellen als "Default"? Hij zal dan verzonden worden naar nieuwe leden wanneer zij zich aanmelden.';
		image = GetModuleImageUrl() + 'icons/standaard.png';
		alt = 'is_default';
	} else {
		tekst = 'Weet je zeker dat je "Default nieuwsbrief" van deze nieuwsbrief af wilt halen? Hij zal dan niet meer verzonden worden naar nieuwe leden wanneer zij zich aanmelden.';
		image = GetModuleImageUrl() + 'icons/niet_standaard.png';
		alt = 'is_niet_default';
	}
	$('#dialog').dialog('option', 'title', 'Bevestig wijziging');
	$('#dialog').dialog('option', 'height', 'auto');
	$('#dialog').dialog('option', 'width', 300);
	$('#dialog').dialog('option', 'modal', true);
	$('#dialog').dialog('option', 'buttons', {
		"Ok": function() {
			$(this).dialog("close");
			$.ajax({
				cache: false,
				method: "get",
				url: "backoffice/nieuwsbrief/setdefault/"+id+'/'+alt,
				success: function(html){
					$('#default_'+id).attr('src', image);
					$('#default_'+id).attr('alt', alt);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					showError(XMLHttpRequest['responseText']);
				}
			});
		},
		'Annuleren': function(){
			$(this).dialog("close");
		}
	});
	$('#dialog').html(tekst);
	$('#dialog').dialog('open');
}
