
$.fn.getRand = function(){
	var rand = Math.floor(Math.random()*10000000001);
	//console.log(rand);
	return rand;
}
$.fn.getIdContent = function(){

	var pathname = window.location.pathname;
			
	var extract = pathname.split('/');
	
	var idContent = extract[4];
	
	return idContent;

}

$.fn.getIdMember = function(){

	var pathname = window.location.pathname;
			
	var extract = pathname.split('/');
	var idMember = extract[4];
	
	return idMember;

}

$.fn.removeImage = function(){
	
	$('.blogEntryUploads a').click(function(event){
		
		event.preventDefault();	
					
		var image = $(this).attr('id');
		$.get('/xhr/index/case/deleteBlogImage/image/'+image,{},function(data){
		});
		
		$(this).parent().fadeOut('normal');
	})
}
$.fn.removeGroupImage = function(){
	$('.groupUploads a').click(function(event){
		
		event.preventDefault();	
					
		var image = $(this).attr('id');
		$.get('/xhr/index/case/deleteGroupImage/image/'+image,{},function(data){
		});
		
		$(this).parent().fadeOut('normal');
	})
}
$.fn.getIdBlogEntry = function(){

	var pathname = window.location.pathname;
			
	var extract = pathname.split('/');
	var idBlogEntry = extract[4];
	
	return idBlogEntry;

}

$.fn.getTopImages = function(){

	var i = 0;

	$('#topImageFader img').each(function(n){
		
		i++;
		
	});
	
	return i;

}

// select en deselect van recipients
$.fn.selectRecipients = function(){
	
	$('#composeRecipients :checkbox').click(function(event){
		
		// retrieve foreach checkbox the corresponding membername
		var rawRecipient = $(this).val().split('|');
		
		var recipient = rawRecipient[0];
		var idRecipient = rawRecipient[1];
		
		// get the current string of recipients
		var currentRecipient = $(':input[name=recipients]').val();
		var currentIdRecipient = $(':input[name=idrecipients]').val();
		
		// when member is clicked, add her to the recipients string
		if($(this).is(':checked')){
		
			var recipients = currentRecipient+recipient+'; ';
			var idRecipients = currentIdRecipient+idRecipient+'; ';
		
		// else remove her from the recipients string
		} else {
		
			var recipients = currentRecipient.replace(recipient+'; ','');
			var idRecipients = currentIdRecipient.replace(idRecipient+'; ','');
			
		}
		
		// show the recipients string in the recipients field
		$(':input[name=recipients]').val(recipients);
		$(':input[name=idrecipients]').val(idRecipients);
		
	});
}
function validateMessage(formData, jqForm, options) { 
    
   	var queryString = $.param(formData);
    //alert(recipientsRequired);
    for (var i=0; i < formData.length; i++){ 
       
    	if(formData[i].value == ''
            && formData[i].name != 'image'
            && formData[i].name != 'embed'
            && formData[i].name.indexOf('share')===-1
            ){
    		var error="";
       		if(formData[i].name=="title"){error="Please enter a title.";}
       		else if (formData[i].name=="name"){error="Please enter your name.";}
       		else if (formData[i].name=="subject"){error="Please add a subject.";}
       		else if (formData[i].name=="idrecipients"){error="Please add recipients.";}
       		else if (formData[i].name=="introduction"){error="Please add an introduction.";}
       		else if (formData[i].name=="textbody" && window.action=="startGroup"){error="Please add the full text of your group information.";}
       		else if (formData[i].name=="textbody" && (window.action=="addGroupArticle" || window.action=="editGroupEntry")){error="Please add the full text of your article.";}
       		else if (formData[i].name=="textbody" && (window.action=="addBlogEntry" || window.action=="addSharebit" || window.action=="editBlogEntry")){error="Please add the full text of your blog.";}
       		else if (formData[i].name=="tags" && (window.action=="addBlogEntry" || window.action=="addSharebit" || window.action=="addGroupArticle")){error="Please enter tags/keywords about your blog that help place your blog throughout the community.";}
       		else {error = formData[i].name+' required';}
       		var invalid = true;
       		$("#compose"+(i)).html(error);
       		$("#compose"+(i)).show();
       		//alert('errors:'+(i)+error);
       	} else if (formData[i].name=="embed"){
            var error = "";
            if(formData[i].value.substr(0,4)=='http' || formData[i].value.substr(0,3)=='www'){
                invalid = true;
                var error = "This embed code is invalid. Please try again.";
                //alert('errors:'+(i)+error);
                $("#compose"+(i)).html(error);
                $("#compose"+(i)).show();
            }else{
                $("#compose"+(i)).hide();
            }
        } else {
       		$("#compose"+(i)).hide();
       	}
	}
	
	if(invalid){
		return false;
	} else {
		return true;
    }
}

function validateShareBitMessage(formData, jqForm, options) {

   	var queryString = $.param(formData);
    var notLoggedin = false;
    
    for (var i=0; i < formData.length; i++){
        if(formData[i].name=='name'){
            notLoggedin = true;
        }
        var embedNum = (notLoggedin) ? 10 : 9 ;
        var tagsNum = (notLoggedin) ? 11 : 10 ;
    	if(formData[i].value == ''
            && (formData[i].name=="title"
                  || formData[i].name=="tags"
                  || formData[i].name=='name'
//                || formData[i].name=='share_url'
                )

        ){
    		var error="";
       		if(formData[i].name=="title"){error="Please enter a title.";}
       		else if (formData[i].name=="name"){error="Please enter your name.";}
       		else if (formData[i].name=="share_url"){error="Please enter a link.";}
            else if (formData[i].name=="tags"){error="Please enter tags/keywords about your Share Bit that help place your Share Bit throughout the community.";}
       		else {error = formData[i].name+' required';}
       		var invalid = true;

            var j = (formData[i].name=="tags") ? tagsNum : i ;

            $("#compose"+(j)).html(error);
       		$("#compose"+(j)).show();
       	} else if (formData[i].name=="embed"){
            var error = "";
            if(formData[i].value.substr(0,4)=='http' || formData[i].value.substr(0,3)=='www'){
                invalid = true;
                var error = "This embed code is invalid. Please try again.";
                $("#compose"+(embedNum)).html(error);
                $("#compose"+(embedNum)).show();
            }else{
                $("#compose"+(embedNum)).hide();
            }
        } else {
       		if(i!=tagsNum && i!=embedNum)$("#compose"+(i)).hide();
            if(formData[i].name=="tags")$("#compose"+(tagsNum)).hide();
       	}
	}

	if(invalid){
		return false;
	} else {
		return true;
    }
}
 
// na opslaan van entry wordt deze method getoond
function outputMessage(responseText, statusText)  { 
	$("#overlay").html(responseText);	
		$(".closeOverlay").click(function(event){
			$("#overlay").expose({api: true}).close();
			if(window.newpath){
				document.location.href=window.newpath;
			}else{
				document.location.href=document.location.href;
			}
			return false;
		}); 
		
		$(".imagecancel").click(function(event){
			$("#overlay").expose({api: true}).close();
			return false;
		}); 
		
	
	 	$("#overlay").oneTime(3000, function() {
	 		$(".closeOverlay").click(function(event){
				$("#overlay").expose({api: true}).close();
				if(window.newpath){
					document.location.href=window.newpath;
				}else{
					document.location.href=document.location.href;
				}
				return false;
			}); 
			
			$(".imagecancel").click(function(event){
				$("#overlay").expose({api: true}).close();
				return false;
			}); 
			if(window.action != "unsubscribeGroup" && window.action != "connectBlog"){
				$('#overlay').expose({api: true}).close();
				//location.reload();
				
				if(window.newpath){
					document.location.href=window.newpath;
				}else{
					document.location.href=document.location.href;
				}
			}
		});
	
}
$(function() { 
 
	// perform exposing for the clicked element 
    $('#overlay').expose({
       	
   		api: true,
       	loadSpeed:500,
		closeSpeed:500,
		opacity:0.5,
		onBeforeLoad: function(){
            //alert('dxgdxfhdxf');
            if(window.action == "addSharebit"){
                var textOptions = {
                    beforeSubmit:  validateShareBitMessage,  	// pre-submit callback
                    success:       outputMessage 		// post-submit callback
                };
            }else if(window.action != "connectBlog"){
                var textOptions = {
                    beforeSubmit:  validateMessage,  	// pre-submit callback
                    success:       outputMessage 		// post-submit callback
                };
            }else{
                var textOptions = {
                    success:       outputMessage 		// post-submit callback
                };
            }
    		$('#overlay').html("loading content...");
            if(window.path==''){
                var closeHTML='<div style="width: 50px; float: right;"><a style="float: left;" href="#" class="closeOverlay">close</a> <a style="float: right;" href="#" class="closeOverlay"><img style="border: 0px none;" src="/images/design/close.png"></a></div><br style="clear:both;" /><br />';
                $('#overlay').html(closeHTML+'<center>'+window.overlayData+'</center>');
                $('#overlay').find(".closeOverlay").click(function(event){
                                $("#overlay").expose({api: true}).close();
                                return false;
                    });
                $('#overlay').css('width','420px');
            }else{
                $('#overlay').css('width','600px');
                $.get(window.path+'/rand/'+$(this).getRand(),{},function(data){
                    $('#overlay').html(data);
                    $('#overlay').find('#xhr').submit(function(event) {
                            event.preventDefault();
                            $(this).ajaxSubmit(textOptions);
                            return false;
                    });
                    $('#overlay').find(".closeOverlay").click(function(event){
                                $("#overlay").expose({api: true}).close();
                                return false;
                    });

                    $('#overlay').find(".imagecancel").click(function(event){
                        $("#overlay").expose({api: true}).close();
                        return false;
                    });

                });
            }
            
            
		},
		
		onLoad: function(){
			$("#overlay").centerInClient();
			
			$("#overlay").fadeIn('slow');
			
			$(document).ready(function() { 
				
				$('.error').hide();
				$('#pane1').jScrollPane();
			    
			    $(this).removeImage();
			    $(this).removeGroupImage();
				
				var textOptions = {
			        beforeSubmit:  validateMessage,  	// pre-submit callback 
			        success:       outputMessage 		// post-submit callback
			    };
			    
			    $(this).selectRecipients();
			    
			    // voor het toevoegen van een blog entry zijn image options vereist
			    if(window.action == "addBlogEntry" 
			    	|| window.action == "editBlogEntry" 
			    	|| window.action == "addGroupArticle" 
			    	|| window.action == "editGroupEntry"
                    || window.action == "addSharebit"
			    ){
			    	if(window.action == "addGroupArticle"){
			    		var xhrCase = "addGroupArticle";
			    	}
			    	else{
			    		var xhrCase = "addEntry";
			    	}
			    	var blogOptions = {
			    		url: '/xhr/index/case/'+xhrCase+'/content/image',
			    		success: showImage
			    	};
			    	
			    	$('input[type=file]').change(function(){
                        if($(this).val().toLowerCase().indexOf('jpg')===-1 && $(this).val().toLowerCase().indexOf('jpeg')===-1 && $(this).val().toLowerCase().indexOf('gif')===-1 && $(this).val().toLowerCase().indexOf('png')===-1){
                            alert('error: unsupported filetype');
                            $(this).val('');
                        }else{
                            $('#images').append("<div id='imgLoading'>Loading..</div>");
                            $('#xhr').ajaxSubmit(blogOptions);
                        }
			    		return false;
			    		
			    	});
                    //$('#iTextareaFullText').wysiwyg();
                   

                    // Initialize the editor.
                    // Callback function can be passed and executed after full instance creation.
                    $('#iTextareaFullText, #textarea[name="textbody"]').ckeditor();
			    
			    }
                ////handle URL shareing
                if(window.action == "addSharebit"){
                    $('input[name="share_url"]').blur(function(){
                       loadSharebitURLData($(this).val()); 
                    });
                    if($('input[name="share_url"]').val()!=''){
                        loadSharebitURLData($('input[name="share_url"]').val());
                    }
                }
			    
			  
			});
			
			// pre-submit callback 
			
			
			// voor het tonen van geuploade images
			function showImage(image,statusText){
				$('#imgLoading').remove();
                if(image.indexOf('error')!==-1){
                    alert(image);
                }else{
                    $('#images').append('<div class="blogEntryUploads"><img id='+image+' src="/images/content/origineel/'+image+'" /><a id="'+image+'" href="#"><b>x</b> delete</a></div>');
                    $('#images img:last').hide();
                    $('#images img:last').fadeIn('normal');

                    // set de behavior voor het removen van een image
                    $(this).removeImage();
                }
				// clear het upload form
				$('input[type=file]').val('');
				
			}
			
			
		    
			$(".closeOverlay").click(function(event){
				$("#overlay").expose({api: true}).close();
				return false;
			}); 
			
			$(".imagecancel").click(function(event){
				$("#overlay").expose({api: true}).close();
				return false;
			}); 
		},
		
		// before close hide the overlay
       	onBeforeClose: function() { 
        	$("#overlay").hide();
            location.reload();
        }
	});
	

	$("#iAEmbedItem, #removeBlogEntry, #removeShareBit, #removeGroupEntry, #deleteGroup, #attendEvent, #sendAfriend, #sendRecommendation, img.reportViolation, img.reportViolationEntry, img.editComment, #addBlogEntry, #addBlogEntryAnonymous, #iAConnectBlog, #addSharebit, #editSharebit, #editBlogEntry, #editGroupEntry, #startGroup, #joinGroup, a[title='personal'], [title='invitation'], [title='invitationOverview'], [title='disconnect'], #termsConditions, #addGroupArticle, #unsubscribeGroup, a[id='unsetGroupMember'], a[id='assignFounder'], #unAttendEvent, #editGroupMain, [rel='overlayVideo']").click(function(event){

		// eerst wordt bekeken om welke actie het gaat met oog op het vullen van de overlay
		// voor dit vullen wordt het path gedefinieerd
		if($(this).attr('id') == "attendEvent"){
			
			window.action = "attendEvent";
			
			var idContent = $(this).getIdContent();
			window.path = '/xhr/index/case/attend/id/'+idContent;
			
		} else if($(this).attr('id') == "unAttendEvent"){
			
			window.action = "unAttendEvent";
			
			var idContent = $(this).getIdContent();
			window.path = '/xhr/index/case/unAttend/id/'+idContent;
		
		} else if($(this).attr('id') == "sendAfriend"){
			
			window.action = "sendMessage";
			
			var idContent = $(this).getIdContent();
			window.path = '/xhr/index/case/manage/section/compose/type/'+$(this).attr("rel")+'/idContent/'+idContent;
		
		} else if($(this).attr('class') == "reportViolation"){
			
			window.action = "reportViolation";
			window.path = '/xhr/index/case/reportViolation/id/'+$(this).attr("rel");
		
		} else if($(this).attr('class') == "reportViolationEntry"){

			window.action = "reportViolation";
			window.path = '/xhr/index/case/reportViolationEntry/id/'+$(this).attr("rel");

		} else if($(this).attr('id') == 'startGroup'){
			
			window.action = "startGroup";
			window.path = '/xhr/index/case/startGroup';
			window.newpath = '/groups/index';
				
		} else if($(this).attr('id') == 'deleteGroup'){
			window.action = "deleteGroup";
			window.path = '/xhr/index/case/deleteGroup/id/'+$(this).attr("rel");
			window.newpath = '/groups/index';
				
		} else if($(this).attr('id') == 'editGroupMain'){
			
			window.action = "editGroupMain";
			window.path = '/xhr/index/case/editGroupMain/id/'+$(this).attr("rel");
				
		} else if($(this).attr('id') == 'joinGroup'){
			
			window.action = "joinGroup";
			window.path = '/xhr/index/case/joinGroup/id/'+$(this).attr("rel");
				
		} else if($(this).attr('id') == 'unsetGroupMember'){
			
			window.action = "unsubscribeGroup";
			window.path = '/xhr/index/case/unsubscribeGroup/id/'+$(this).getIdContent()+'/idMember/'+$(this).attr("rel");
				
		}else if($(this).attr('id') == 'assignFounder'){
			
			window.action = "assignFounder";
			window.path = '/xhr/index/case/assignFounder/idGroups/'+$(this).getIdContent()+'/idMember/'+$(this).attr("rel");
				
		}else if($(this).attr('id') == 'unsubscribeGroup'){
			window.action = "unsubscribeGroup";
			window.path = '/xhr/index/case/unsubscribeGroup/id/'+$(this).attr("rel");
				
		} else if($(this).attr('id') == 'addBlogEntry'){
			
			window.action = "addBlogEntry";
			window.path = '/xhr/index/case/entry/content/blog';
			window.newpath = '/presentation/blog/';
		} else if($(this).attr('id') == 'iAConnectBlog'){

			window.action = "connectBlog";
			window.path = '/blogs/connectExternal';
			window.newpath = '/blogs/';
		} else if($(this).attr('id') == 'addBlogEntryAnonymous'){

			window.action = "addBlogEntry";
			window.path = '/blogs/postAnonymousBlog';
			window.newpath = '/blogs/index/mylatestadded/true';
		} else if($(this).attr('id') == 'addSharebit'){

			window.action = "addSharebit";
			window.path = '/sharebits/postSharebit';
			window.newpath = '/sharebits/index/mylatestadded/true';
		} else if($(this).attr('id') == 'editSharebit'){

			window.action = "addSharebit";
            var idBlogEntry = $(this).getIdBlogEntry();
			window.path = '/sharebits/postSharebit/id/'+idBlogEntry;
			//window.newpath = '/item/index/id/'+idBlogEntry;
		} else if ($(this).attr('id') == "editBlogEntry"){
		
			window.action = "editBlogEntry";
			var idBlogEntry = $(this).getIdBlogEntry();
			window.path = '/xhr/index/case/entry/content/blog/id/'+idBlogEntry;
		
		} else if ($(this).attr('id') == "editGroupEntry"){
		
			window.action = "editGroupEntry";
			var idBlogEntry = $(this).getIdBlogEntry();
			window.path = '/xhr/index/case/entry/content/group/id/'+idBlogEntry;
		
		} else if($(this).attr('title') == "personal" || $(this).attr('title') == "invitation"){
		
			window.action = "sendMessage";
			
			// the receiver is visible in the url so we strip it from there trough this function
			var recipient = $(this).getIdMember();
			
			// the type of message is retrieved from the title attribute
			var type = $(this).attr('title');
			
			window.path = '/xhr/index/case/manage/section/compose/type/'+$(this).attr("title")+'/recipient/'+recipient;
		
		} else if($(this).attr('title') == "invitationOverview"){
		
			window.action = "sendMessage";
			
			// the receiver is visible in the url so we strip it from there trough this function
			var recipient = $(this).attr("rel");
			
			// the type of message is retrieved from the title attribute
			//var type = "invitation";
			
			window.path = '/xhr/index/case/manage/section/compose/type/invitation/recipient/'+recipient;
		
		} else if($(this).attr('id') == 'termsConditions'){
			
			window.action = "termsConditions";
			window.path = '/xhr/index/case/termsConditions';

		} else if($(this).attr('id') == 'sendRecommendation'){
		
			var recommended = $(this).getIdMember();
		
			window.action = "sendRecommendation";
			window.path = '/xhr/index/case/sendRecommendation/recommended/'+recommended;	
		
		} else if($(this).attr('id') == 'addGroupArticle'){
			window.action = "addGroupArticle";
			window.path = '/xhr/index/case/grouparticle/idgroups/'+$(this).attr('rel');
		} else if($(this).attr('id') == 'manageVisitor' || $(this).attr('id') == 'visitorClick'){			
			window.action = "manageVisitor";
			window.path = '/xhr/index/case/manageVisitor';
		} else if ($(this).attr('id') == 'headerVisitor') {									
			window.action = "manageVisitor";
			window.path = '/xhr/index/case/manageVisitor';
		} else if ($(this).attr('rel') == 'overlayVideo') {
			window.action = "overlayVideo";
            window.overlayData = $(this).next().html();
            
			window.path = '';
		} else if($(this).attr('title') == 'disconnect'){
			var recipient = $(this).getIdMember();
			window.action = "disconnect";
			window.path = '/xhr/index/case/disconnect/recipient/'+recipient;
		} else if($(this).attr('id') == 'removeBlogEntry' || $(this).attr('id') == 'removeGroupEntry' || $(this).attr('id') == 'removeShareBit'){
			window.action = "removeBlogEntry";
			var idBlogEntry = $(this).getIdBlogEntry();
			window.path = '/xhr/index/case/removeEntry/id/'+idBlogEntry;
			if($(this).attr('id') == 'removeBlogEntry'){
				window.newpath = '/presentation/blog/';
			}else if($(this).attr('id') == 'removeGroupEntry'){
				window.newpath = '/groups/publicPage/group/'+$(this).attr('rel');
			}else{
				window.newpath = '/sharebits';
			}
        } else if($(this).attr('id') == "iAEmbedItem"){
			window.action = "iAEmbedItem";
			var idBlogEntry = $(this).getIdBlogEntry();
			window.path = '/xhr/index/case/embed/id/'+idBlogEntry;
        } else if($(this).attr('id') == "iAAddExternalBlog"){
			window.action = "iAAddExternalBlog";
			//var idBlogEntry = $(this).getIdBlogEntry();
			window.path = '/xhr/index/case/externalBlog';
		} else {
			window.action = "editComment";
			window.path = '/xhr/index/case/editComment/id/'+$(this).attr("rel");
		}
				
		$('#overlay').expose({api: true}).load();
		return false;
		
	});
	// following section commented to allow visitors to view public articles/columns
//	$('area[rel=events]').each(function(index) {
//		$(this).css('opacity', 0.3);
//		$(this).click(function(event){
//			window.action = "manageVisitor";
//			window.path = '/xhr/index/case/manageVisitor';
//			$('#overlay').expose({api: true}).load();
//			event.preventDefault();
//		});
//	});
	$('#manageVisitor').parents('#navigation:first').css('background','none');
	$('#manageVisitor').parents('#navigation:first').css('border','none');
	$('div [rel=fpFooterVisitor]').click(function(event){
		//document.location.href="/partner/index";
		//event.preventDefault();
	});
	$('#topImageFader').innerfade({ 
		speed: 'slow', 
		timeout: 4000, 
		type: 'sequence', 
		containerheight: $('#topImageFader').attr('rel')
	});
	$('#bottomImageFader').innerfade({ 
		speed: 'slow', 
		timeout: 4000, 
		type: 'sequence'  
	});

    ///hack for ol and ul's
    $('#mainArticle > ol').each(function(i){
        $(this).before('<br style="clear:both;" />');
    });

    function addthisReady(evt) {
    $('.addthis_button_facebook_like > iframe').each(function(i){
        $(this).css('width','110px');
    });
    }

// Listen for the ready event
    if($('.addthis_toolbox').length>0){
        addthis.addEventListener('addthis.ready', addthisReady);
    }
	/*$("#removeBlogEntry").click(function(){
		
		var idBlogEntry = $(this).getIdBlogEntry();
		$.get('/xhr/index/case/removeEntry/id/'+idBlogEntry,{},function(data){
			 window.location.href = data;
		});
		
	});*/
	
});

