/* Default functions */
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function submit( form_id ){
	$('#'+form_id).submit();
}

/* Editor options / functions */
var editor_options = {
	// General options
	mode : "exact",
	theme : "advanced",
	plugins : "safari,imagemanager,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
	language : "nl",
	entity_encoding : "none",
	
	// Theme options
	theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,cut,copy,paste,|,bullist,numlist,|,insertimage,|,undo,redo,|,link,unlink,|,blockquote,charmap,emotions",
	theme_advanced_buttons2 : "",
	theme_advanced_buttons3 : "",
	theme_advanced_buttons4 : "",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "none",
	theme_advanced_resizing : true,
	object_resizing : false,
	theme_advanced_styles : "Style 1=style1;Style 2=style2;Style 3=style3",

	// Example content CSS (should be your site CSS)
	content_css : virt_path+"stylesheets/content.css",

	imagemanager_rootpath: '../../../../images/profielimages/'+profielpagina,
	imagemanager_remember_last_path : false,
	imagemanager_insert_template : '<a rel="lightbox" href="{$url}"><img src="{$url}" width="{$custom.mywidth}" height="{$custom.myheight}" border="0" style="margin: 5px; float:left;"; /></a>',

	// word paste options 
	cleanup_callback : "customCleanup",
    paste_create_paragraphs : false,
    paste_create_linebreaks : false,
    paste_use_dialog : false,
    paste_auto_cleanup_on_paste : true,
    paste_convert_middot_lists : true,
    paste_unindented_list_class : "unindentedList",
    paste_remove_styles : true,
    paste_convert_headers_to_strong : true,
    paste_insert_word_content_callback : "removeP"
};

function customCleanup(type, ihtml) {
	switch (type) {
		case "get_from_editor":
		case "submit_content":
			ihtml = ihtml.replace(/<a[^>]*href[^>]*><\/a>/ig, "");
			ihtml = ihtml.replace(/<p><\/p>/ig, "");
			ihtml = ihtml.replace(/<\/?span[^>]*>/gi, "");
			ihtml = ihtml.replace(/<\/?!--[^>]*>/gi, "");
			ihtml = ihtml.replace(/ style=\"margin: 0cm 0cm 0pt\"/ig, "");
			ihtml = ihtml.replace(/ class=\"MsoNormal\"/ig, "");
			ihtml = ihtml.replace(/ style=\"font-size: x-small\"/ig, "");
		break;
	}
	return ihtml;
}

/* Berichten / Blog functions */
var current_bericht_id;

function delete_bericht( bericht_id ){
	if( confirm( "Weet je zeker dat je dit bericht wilt verwijderen?" ) == true ){
		window.location.href = virt_path+"berichten/delete/id/"+bericht_id;
	}
	return false;
};

function lock_bericht( bericht_id, lock ){
	if( confirm( "Weet je zeker dat je dit bericht wilt "+(lock == 'locked'?'de':'')+"blokkeren?" ) == true ){
		window.location.href = virt_path+"berichten/lock/id/"+bericht_id;
	}
	return false;
};

function lock_doel( doel_id, lock ){
	if( confirm( "Weet je zeker dat je dit doel wilt "+(lock == '0'?'de':'')+"blokkeren?" ) == true ){
		window.location.href = virt_path+"admin/lockdoel/id/"+doel_id;
	}
	return false;
};

function close_bericht(){
	$(".bericht").show();
	$(".bericht_edit").children().remove();
	current_bericht_id = 0;
};

function toon_bericht( bericht_id )
{
	$("#bericht_verkort_"+bericht_id).toggle();
	$("#bericht_"+bericht_id).toggle();
	link =$("#bericht_link_"+bericht_id);
	link.text( link.text() == "lees verder »" ? "« verkort" : "lees verder »" );
}

function delete_foto( foto_id ){
	if( confirm( "Weet je zeker dat je deze foto wilt verwijderen?" ) == true ){
		window.location.href = virt_path+"fotoalbum/verwijderen/id/"+foto_id;
	}
	return false;
};

//post-submit callback 
function showResponse(responseText, statusText){
	if( responseText == "update" )
	{
		$(current_bericht_id+" .bericht_content").load( virt_path+'berichten/view/id/'+current_bericht_id.replace("#bericht_",""), function(){
			$(current_bericht_id).toggle();
			$(current_bericht_id+"_edit").children().remove();
			current_bericht_id = 0;
			/* Activate Lightbox */
		    $('a[rel="lightbox"]').lightbox({
			    fitToScreen: true
		    });			
		});
	} else if( responseText == "insert" ) {
		window.location.href = virt_path+profielpagina;
	} else {
		$(current_bericht_id+"_edit").html(responseText);
		$('.tinymce').tinyMCE(editor_options);
		$('.bericht_form').ajaxForm({success:showResponse});
	}
} 

/* Beheer functions */
function lock_actie( actie_id, lock ){
	if( confirm( "Weet je zeker dat je deze actiepagina wilt "+(lock == 'locked'?'de':'')+"blokkeren?" ) == true ){
		window.location.href = virt_path+"admin/lock/id/"+actie_id;
	}
	return false;
};

/* Tooltip functions */
this.tooltip = function(){	
	var xOffset = 10;
	var yOffset = 20;		
	$("a.tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$("a.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});		
};

$(document).ready(function(){
	$('.tinymce').tinyMCE(editor_options);
	
	/* Bind op change doelen op homepagina */
	$("#doelen").change(function () {
		window.location.href = virt_path+'site/home/doel/'+$("#doelen option:selected").val()
	});
	
	/* Functies voor bewerken/aanmaken berichtenblog */
	$(".bericht_bewerken").click(function () {
		var id = "#"+$(this).parent().parent().attr('id');
		var type_bericht = $(this).parent().parent().attr('type').toLowerCase();
		if( current_bericht_id == id ) return false; 
		current_bericht_id = id;

		$(".bericht").show();
		$(".bericht_edit").children().remove();
		
		$(id+"_edit").load( virt_path+'berichten/edit/type_bericht/'+type_bericht+'/id/'+id.replace("#bericht_",""), function(){
			$('.tinymce').tinyMCE(editor_options);
			$('.bericht_form').ajaxForm({
				beforeSubmit: function(a) {
				
					var editorid = $('.tinymce').attr('id');
					for (var i=0; i<a.length; i++)
						 if (a[i].name == 'bericht') a[i].value = tinyMCE.get( editorid ).getContent();
			   }, 
			   success:showResponse});
			$(id).toggle();
			$(id+"_edit").show();
		});
	});	
	
	/* Bind op change sorteren op listpagina */
	$("#list_sorteren").change(function () {
		doel = "";
		order = "";
		if( $("#list_sorteren option:selected").val() != "" ) order = "/order/"+$("#list_sorteren option:selected").val();
		if( $("#list_doelen option:selected").val() != "" ) doel = "/doel/"+$("#list_doelen option:selected").val();
		window.location.href = virt_path+'admin/index'+doel+order;
	});
	
	/* Bind op change doelen op listpagina */
	$("#list_doelen").change(function () {
		doel = "";
		order = "";
		if( $("#list_sorteren option:selected").val() != "" ) order = "/order/"+$("#list_sorteren option:selected").val();
		if( $("#list_doelen option:selected").val() != "" ) doel = "/doel/"+$("#list_doelen option:selected").val();
		window.location.href = virt_path+'admin/index'+doel+order;
	});
	
	/* tooltip activeren */
	tooltip();

	/* Activate Lightbox */
	$('a[rel="lightbox"]').lightbox({
		fitToScreen: true
	});
	
	MakeEditable('textarea');
	MakeEditable('text');
	
	/* Activiteitenkalender mouseover */
	$(".activiteit").bind("mouseover", function(){
		var classname = $(this).attr('class').replace('activiteit',"");
		$(this).removeClass(classname);
		$(this).addClass(classname+"_over");
	});
	
	/* Activiteitenkalender mouseout */
	$(".activiteit").bind("mouseout", function(){
		var classname = $(this).attr('class').replace('activiteit',"");
		$(this).removeClass(classname);
		$(this).addClass(classname.replace("_over",""));
	}); 
	
	/* Berichteneditbox */
	$(".labelfy").labelify({labelledClass:"readonly"});
	
	/* Berichteneditbox (hart) max 150 karakters */
	$("#hart").bind("keyup blur" , function(e){
		var max = 150;
		var length = $("#hart").val().length;
		if(length > max) {
			$("#hart").val($("#hart").val().substr(0,max));
			alert('Dit bericht mag maximaal '+max+' tekens bevatten.');
		}
	});	
	
	
	$("input[name=public_getuigenis]").change( function(e)
	{
		$.get(virt_path+profielpagina+'/save', { id: "profiel_public_getuigenis", value: $("#public_getuigenis input:checked").val() } );
	});
	
	/* uploads voor fotoalbum */
	$("#uploadify").uploadify({
		'uploader'      : virt_path+'scripts/uploadify.swf',
		'script'        : virt_path+'upload',
		'scriptData'	: {'hash': hash},
		'cancelImg'     : virt_path+'images/icon_close_on.gif',
		'queueID'       : 'fileQueue',
		'auto'          : true,
		'multi'         : true,
		'fileDesc'		: 'Alleen afbeeldingen (*.jpg of *.gif)',
		'fileExt'		: '*.jpg;*.gif;',
		'buttonText'	: 'Toevoegen',
		'queueSizeLimit': 6,
		'simUploadLimit': 2,
		'onComplete'	: UploadSucces
	});
	
	
	function UploadSucces(event,queueID,fileObj,response,data )
	{
		//console.log( "%s", unescape(response) );
		$('#fileUploaded').append('<div class="fotoalbum_result"><div style="width:120px;height:120px;background:bottom center no-repeat #FFF;background-image: url('+virt_path+'download/getimage/fotoalbum/'+response+'/size/120);"><img src="'+virt_path+'images/transparent.gif" height=120 border=0></div><div class="edit" id="foto_'+response+'_titel">'+ fileObj['name'].replace( fileObj['type'], "" ) +'</div></div>');
		MakeEditable( 'text' );
		return true;
	}
	
	function MakeEditable( type )
	{
		/* AJAX voor bewerken van textarea / text */
		$( ( type == 'text' ? '.edit' : '.editarea' ) ).editable(virt_path+'site/save', {
			data: function(value, settings) {
		    	var retval = value.replace(/<br[\s\/]?>/gi, '\r');
		    	return retval;
		  	},
		  	height	  :( type == 'text' ? '18px' : 'auto' ),
		  	width	  :( type == 'text' ? '110px' : 'auto' ),
			cssclass  : 'cssform js', 
		    type      : type,
		    cancel    : '<a onmouseout=\'MM_swapImgRestore()\' onmouseover=\'MM_swapImage("sluiten","","'+virt_path+'images/icon_close_on.gif",1)\'><img src=\''+virt_path+'images/icon_close_off.gif\' alt=\'Editor afsluiten\' title=\'Editor afsluiten\' name=\'sluiten\' border=\'0\' id=\'sluiten\' /></a>',
		    submit    : '<a href=\'javascript:submit();\' onmouseout=\'MM_swapImgRestore()\' onmouseover=\'MM_swapImage("opslaan","","'+virt_path+'images/icon_save_on.gif",1)\'><img src=\''+virt_path+'images/icon_save_off.gif\' alt=\'Bericht opslaan\' title=\'Bericht opslaan\' name=\'opslaan\' border=\'0\' id=\'opslaan\' /></a>',
		    tooltip   : 'Klik hier om deze tekst aan te passen',
		    placeholder : 'Klik hier om deze tekst aan te passen'
		});
		
	}
	
});
