$(document).ready(init);
$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
while(x<c.length){var m=r.exec(c.substr(x));
  if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
  }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
  o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});
function init() {
	$('#browseBtn, #previewImage').bind('click', function(e){
		e.preventDefault();			
		window.open(AppConfig['rootUrl']+"/frame/nieuwsbrief/chooseImage", "_blank", "location=0,status=0,scrollbars=1,width=800,height=600");
	});
	
	$('#aanbod_alles').bind('click', function() {
		if ($(this).is(':checked')) {
			$("input[type='checkbox']").attr('checked', 'checked');
		} else {
			$("input[type='checkbox']").removeAttr('checked');
		}
	});

	/**
	 * Niewsbrief create, stap 2, afbeelding kiezen
	 */
	$('#radio-noimg').click(function(){
		$('#choose-box').slideUp('fast');
	});
	$('#radio-choose').click(function(){
		$('#choose-box').slideDown('fast');
	});

	/**
	 * Aanmelden / afmelden
	 */
	$('#contNieuwsbrief').find('.toggle').bind('click', function(){
		$('form.toggleable').slideToggle(400);
		return false;
	})

	/**
	 * VALIDATE aanmelden
	 */
	if ( $("#nieuwsbriefAanmeldenForm").length > 0 ) {
		$("#nieuwsbriefAanmeldenForm").validate({
			errorElement: "div",
			errorPlacement: function(error, element) {
				error.insertBefore( element.parent( 'p' ) );
			},
			errorContainer: $("#formError"),
			rules: {
				uwnaam: "required",
				uwemail: {
					required: true,
					email: true
				}
			},
			messages: {
				uwnaam: "Graag even uw naam invullen:",
				uwemail: "Graag een correct emailadres invullen:"
			}
		});
	}
	if ( $("#nieuwsbriefAfmelden").length > 0 ) {
		$("#nieuwsbriefAfmeldenForm").validate({
			errorElement: "div",
			errorPlacement: function(error, element) {
				error.insertBefore( element.parent( 'p' ) );
			},
			errorContainer: $("#formError"),
			rules: {
				uwemail: {
					required: true,
					email: true
				}
			},
			messages: {
				uwemail: "Graag een correct emailadres invullen:"
			}
		});
	}

	/**
	 * TEKST
	 */
	if ( $('#tekstAddEditor').length > 0 ) {	
		$('#tekstAddEditor').dialog({
			autoOpen: false,
			bgiframe: true, 
			width: '960px', 
			height: '600', 
			draggable: false, 
			resizable: false, 
			modal: true, 
			position: ['center','top'],
			close: function(ev, ui) {
				//Bij het sluiten van de dialog een reload zodat de nieuwe items in de lijst staan
				window.location = AppConfig['rootUrl']+'/beheer/nieuwsbrief/create/new/stap-2/';
			}
	    });
		$('#tekstAddEditor').dialog('option', 'buttons', {
			'Opslaan': function() {
				$.ajax({
					type: 'post',
					data: 'interesse='+$.URLEncode( $('#interesse').val() )+'&idNieuwsbrief='+$.URLEncode( $('#idNieuwsbrief').val() )+'&titel='+$.URLEncode( $('#titelNb').val())+'&tekst='+$.URLEncode( $('#tekstNb').val())+'&leesVerder='+$.URLEncode( $('#leesverderNb').val())+'&afbeelding='+$.URLEncode( $('#thumbnailPath').val())+'&modId='+$.URLEncode( $('#modIdFrom').val()),
					url: AppConfig['rootUrl']+'/beheer/nieuwsbrief/insertItemByNb',
					contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
					success: function(data) {
						//alert(data);
						$('#tekstAddEditor').dialog("close");
					}
				});
			}
		});
		
		$('#tekstAdd').click(function () {
			$('#tekstAddEditor').dialog("open");
			$('#tekstAddEditor textarea').tinymce({
				script_url : AppConfig['rootUrl']+'/public/plugins/tinymce/3.4.4/tiny_mce.js',
				theme : "advanced",
				language : "nl",
				width: "400",
				height: "75",

				plugins : "safari,contextmenu,visualchars,xhtmlxtras",

				theme_advanced_buttons1 : "bold,italic,underline,|,cut,copy,paste,pastetext,pasteword,|,undo,redo,cleanup,|,charmap,bullist,numlist,|,link,unlink,code",
				theme_advanced_buttons2 : "",
				theme_advanced_buttons3 : "",
				theme_advanced_buttons4 : "",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : true,
				theme_advanced_resizing_min_width : 400,
				theme_advanced_resizing_max_width : 400,
				
				paste_auto_cleanup_on_paste : true,
				paste_strip_class_attributes: "all",
				paste_remove_spans: true,
				paste_text_use_dialog: true,

				force_br_newlines : true,
				force_p_newlines : false,
		        forced_root_block : '' // Needed for 3.x

			});
		});
	}

	$('.delItem').click(function() {	
		$.ajax({
			type: 'GET',
			data: 'idNieuwsbrief='+$('#idNieuwsbrief').val()+'&id='+$(this).attr('id'),
			url: AppConfig['rootUrl']+'/beheer/nieuwsbrief/delNbWoningKoppeling',
			success: function(data) {
				//alert(data);
				location.reload();
			}
		});
	});

	$('.modItem').click(function() {
		$.ajax({
			type: 'GET',
			data: 'id='+$(this).attr('id'),
			url: AppConfig['rootUrl']+'/beheer/nieuwsbrief/getTekstInfo',
			success: function(data) {
				/**
				 * Splitten op ||||
				 * 
				 * [0] = idItem
				 * [1] = titel
				 * [2] = tekst
				 * [4] = afbeelding id
				 */
				var aData = data.split('||||');
				
				$('#tekstAddEditor #modIdFrom').val(aData[0]);
				$('#tekstAddEditor #titelNb').val(aData[1]);
				$('#tekstAddEditor #tekstNb').val(aData[2]);
				$('#tekstAddEditor #leesverderNb').val(aData[8]);
				
				$('#tekstAddEditor #interesseLijst').html(aData[12]);
				
				if ( aData[4].length > 2 ) {
					$('#tekstAddEditor #thumbnailPath').val(aData[4]);
					$('#choose-thumbnail').attr('src', aData[4]).slideDown();
					$('#radio-choose').trigger('click');
				}
				
				$('#tekstAddEditor').css('display', 'block');
				$('#tekstAddEditor').dialog('open');	

				$('#tekstAddEditor textarea').tinymce({
					script_url : AppConfig['rootUrl']+'/public/plugins/tinymce/3.4.4/tiny_mce.js',
					theme : "advanced",
					language : "nl",
					width: "400",
					height: "75",

					plugins : "safari,contextmenu,visualchars,xhtmlxtras",

					theme_advanced_buttons1 : "bold,italic,underline,|,cut,copy,paste,pastetext,pasteword,|,undo,redo,cleanup,|,charmap,bullist,numlist,|,link,unlink,code",
					theme_advanced_buttons2 : "",
					theme_advanced_buttons3 : "",
					theme_advanced_buttons4 : "",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_statusbar_location : "bottom",
					theme_advanced_resizing : true,
					theme_advanced_resizing_min_width : 400,
					theme_advanced_resizing_max_width : 400,
					
					paste_auto_cleanup_on_paste : true,
					paste_strip_class_attributes: "all",
					paste_remove_spans: true,
					paste_text_use_dialog: true,

					force_br_newlines : true,
					force_p_newlines : false,
			        forced_root_block : '' // Needed for 3.x

				});
			}
		});
	});

	if(jQuery().dataTable)
		dataTableSorter();
}

function moveNb(dir, id, huidig, parent) {
	$.ajax({
		url: AppConfig['rootUrl']+'/beheer/nieuwsbrief/moveNb?dir='+dir+'&id='+id+'&huidig='+huidig+'&parent='+parent,
		success: function(data) {
			location.reload();
		}
	});   
}

function dataTableSorter() {
	//multiple sort
	$.fn.dataTableExt.oSort['string-case-asc']  = function(x,y) {
		return ((x < y) ? -1 : ((x > y) ?  1 : 0));
	};
	$.fn.dataTableExt.oSort['string-case-desc'] = function(x,y) {
		return ((x < y) ?  1 : ((x > y) ? -1 : 0));
	};

	if( $('table.tablesorterOntvangers').length > 0 ) {
		$('table.tablesorterOntvangers').dataTable({
			"sPaginationType": "full_numbers",
			"aaSorting": [ [2,'asc'] ],
			"iDisplayLength": '50',
			"bAutoWidth": false,			
			"oLanguage": {
				"sUrl": AppConfig['rootUrl']+"/public/modules/nieuwsbrief/js/datatables.1.6.2/js/nl_NL.txt"
			},
			"aoColumns": [
				{ "sWidth": "200px" }, //name
				{ "sWidth": "200px" }, //email
				{ "sWidth": "70px" } //tools
			]
		});
	}
}
