window.changer = window.changer || {};
changer.communityportal = changer.communityportal || {};

/* Login extensions */
changer.communityportal.loginHandler = function() {
	$('#username, #password').focus(function() {
		this.value = this.value == this.defaultValue ? '' : this.value;
		$(this).removeClass('empty');
		if(this.id == 'password') {
			this.type = 'password';
			$(this).toggleClass('password', this.value != this.defaultValue);
		}
	}).blur(function() {
		this.value = this.value == '' ? this.defaultValue : this.value;
		$(this).toggleClass('empty', this.value == this.defaultValue);
		if(this.id == 'password') {
			this.type = this.value == this.defaultValue ? 'text' : 'password';
		}
	});
};

/* Ajax handler news ?? */
changer.communityportal.ajaxHandlerNews = function() {
	// This is the basic posting mechanism for news?
	$('.content-new .share').live('click', function() {
		var oSelf = $(this);
		var oParent = oSelf.closest('.comment');
		var oData = {};
				
		oData['community'] =  $('#id_community', oParent).val();
		oData['title'] = $('#id_title', oParent).val();
		oData['description'] = $('#id_description', oParent).val();
		oData['for_publication'] = $('#id_for_publication', oParent).val();
		oData['classification'] = this.id;		
		
		changer.communityportal.showLoader();
		$.post("/posts/new/post/", oData, function() {
			changer.communityportal.streamNav.loadCurrent();
		})
		.complete(function() { changer.communityportal.removeLoader(); });
	});
};


/* Stream Navigation (Right profile column) */
changer.communityportal.streamNav = changer.communityportal.streamNav || {

	init: function() {
		this.handleClick();
		this.loadCurrent();
	},

	showArrow: function(iIndex) {
		aArrows = $('.stream-select .arrows');	
		aArrows.removeClass('arrow-white').eq(iIndex).addClass('arrow-white');
	},
	
	moveArrow: function(oCurrent) {
		var oArrow = oCurrent.siblings('.arrow');
		var iMargin = 0;
		
		oCurrent.prevAll().each(function() {
			iMargin += $(this).outerWidth();
		});
		
		iMargin += (oCurrent.width() - oArrow.width()) / 2;
		oCurrent.siblings('.arrow').animate({marginLeft: iMargin + 'px'});
		
	},

	loadCurrent: function(bAppend, fCallBack) {
		var oThis = this;
		var oCurrent = ($('.stream-select li.active').length || $('.stream-select li').eq(0).addClass('active')) && $('.stream-select li.active').eq(0);
		var oTarget = $('.stream-boxes');
		var sHref = $('a:first', oCurrent).attr('href');
		if(!sHref) {
			// Somehow loadCurrent is called when there are no stream links
			return;
		}
		if(bAppend) {
			if(sHref != oTarget.attr('loaded-url')) {
				// Can't append to items of another url
				return;
			}
			var iExistingItems = oTarget.find('aside.content-block:not(.content-block-header)').length;
			if(iExistingItems > 0) {
				sHref = sHref.replace(/\/?$/, '/' + iExistingItems + '/');
				oTarget = $('<div />').appendTo(oTarget);
				changer.communityportal.showLoader(oTarget);
			}
		}
		else {
			changer.communityportal.showLoader();
			oTarget.attr('loaded-url', sHref);
		}
		window.console&&console.log('loading:', sHref);
		oTarget.load(sHref, function() {
			var streams = $(this).find('.stream');
			streams.appendTo($(this).empty());
			oThis.moveArrow(oCurrent);
			oCurrent.addClass('active').siblings().removeClass('active');
			if(fCallBack) {
				fCallBack();
			}
			changer.communityportal.removeLoader();
			$(window).unbind('scroll.loadCurrent');
			if(!streams.length) {
				return;
			}
			$(window).bind('scroll.loadCurrent', function() {
				var top = $(window).scrollTop();
				var height = $('#wrapper').height() - $(window).height();
				if(top > height) {
					$(window).unbind('scroll.loadCurrent');
					changer.communityportal.streamNav.loadCurrent(true);
				}
			});
		}, false);
	},

	handleClick: function() {
		var self = this;
		$('.stream-select li').live('click', function(e) {
			e.preventDefault();
			$(this).addClass('active').siblings().removeClass('active');
			self.loadCurrent();
		});
	}
};


/* Add comment */
changer.communityportal.addCommentHandler = function () {
	var submit = function(input) {
		var oSelf = $(input);
		var oParent = oSelf.closest('.comment');
		var oData = {};
		oData['post_id'] = $('.post-id-field', oParent).val();
		oData['content_type'] = $('.content-type-field', oParent).val();
		oData['body'] = oSelf.val();
		changer.communityportal.showLoader(oParent);
		$.post("/posts/comment/", oData, function() {
			oSelf.blur();
			oSelf.val('');
			oSelf.attr('disabled', 'disabled');
			changer.communityportal.streamNav.loadCurrent();
		});
	}
	$('.comment-field').live('keydown', function(event) {
		if (event.keyCode == '13') {
			submit(this);
		}
	});
	$('.comment-button').live('click', function(event) {
		submit($(this).siblings('.comment-field'));
	});
};


/* Remove comment */
changer.communityportal.removeCommentHandler = function () {
	$('div.comment a.delete').live('click', function(e) {
		e.preventDefault();
		changer.communityportal.showLoader();
		$.get(this.href, {}, function() {
			changer.communityportal.streamNav.loadCurrent();
		})
		.complete(function() { changer.communityportal.removeLoader(); });
	});
};


/* Show comments */
changer.communityportal.showCommentsHandler = function () {
	// Set defaults
	$('.comment-container .body').hide();
	$('.comment-container .body:lt(3)').show();
	
	// Handle click
	$('.comment-container > .show a').live('click', function() {
		$(this).remove();
		$('#comments-' + this.id + ' > .comment-container > .body').slideDown('slow');
	});
};


/* CSRF Compatibility */
$('html').ajaxSend(function(event, xhr, settings) {
	function getCookie(name) {
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = $.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
	if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
		// Only send the token to relative URLs i.e. locally.
		xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
	}
});


/* Show friend profile */
changer.communityportal.friendProfileHandler = function() {
	$('.show-friends.loader').live('click', function(e) {
		e.preventDefault();
		var oFooter = $(this).parents('.content-block').find('.content-footer-extra');
		oFooter.find('.remote-content').remove();
		oFooter.hide();
		oFooter.load(this.href + ' .remote-content', function() {
			oFooter.slideDown('slow');
		});
	});
};


/* Messaging */
changer.communityportal.doHighlightMessages = function() {
	changer.communityportal.doScrollUp('fast');

	oMsgContainer = $('div#messages-container > ul.messages');

	$('li', oMsgContainer).each(function() {
		var li = $(this);
		var opts = {'background-color': '#feae00','color': '#ffffff','border-color': '#000000'};
		var orig = {'background-color': li.css('background-color'),'color': li.css('color'),'border-color': li.css('border-color')};
		li.animate(opts, 'slow');
		li.animate(orig, 'slow');
	});

	setTimeout(function(){
		oMsgContainer.slideUp('fast');
	}, 4000);
};


/* Show loader */
changer.communityportal.showLoader = function(oLoadingParent) {
	oLoadingParent = oLoadingParent || $('.right-content');
	if(!$('.loading').length) {
		oLoadingParent.addClass('loadingBackground').prepend('<div class="loading" />');
	}
};

/* Hide loader */
changer.communityportal.removeLoader = function() {
	$('.loadingBackground').removeClass('loadingBackground');
	$('.loading').remove();
};


/* Scroll up */
changer.communityportal.doScrollUp = function(speed) {
	var speed = speed == undefined ? 'slow' : speed;
	$( 'html, body' ).animate( { scrollTop: 0 }, speed);
};


/* Schools accordion */
changer.communityportal.jAccordionHandler = function() {

	$('.acc-container').hide();
	
	$('.acc-trigger').click(function() {
		$('.acc-container').hide();
		
		var $trigger = $(this);
		var $container = $trigger.closest('.acc-header').next();
		
		$trigger.toggleClass('active');
		$container.slideDown(200) && $trigger.hasClass('active') || $container.slideUp(150);
		
		return false;
	});

};


/* Lightbox */
changer.communityportal.lightBoxHandler = function() {
	$('a[rel*="lightbox"]').live('mouseover', function() {
		var oNodes = $(this).parents('ul:first');
		oNodes = oNodes.length ? oNodes.find('a') : $(this);
		oNodes.lightBox();
	});
};


/* Publication handler */
changer.communityportal.publicationHandler = function() {
	$('.post-publication').live('click', function(e) {
		e.preventDefault();
		var self = $(this);
		$.get(this.href, {}, function(data) {
			changer.communityportal.streamNav.loadCurrent();
			changer.communityportal.findAndHighlightMessages(data);
			
		})
		
	});
};

/* Edit profile handler */
changer.communityportal.editProfileHandler = function() {
	$('.edit-profile.loader').live('click', function(e) {
		e.preventDefault();
		var url = this.href;
		var oSelf = $(this);
		var oParent = oSelf.closest('.content-block');
		var oFooter = $('.content-footer-extra', oParent);
		
		oFooter.load(url + ' .form-box', function(data) {
			oFooter.slideDown('slow');
			$(function() {
				changer.communityportal.findAndHighlightMessages(data);
				changer.communityportal.datePickerHandler();
			});	
		});
	});	
};


changer.communityportal.datePickerHandler = function() {
	$('.datepicker').datepicker({
		changeMonth: true,
		changeYear: true,
		yearRange: '1930:',
		dateFormat: 'dd-mm-yy'
	});
}


changer.communityportal.previewPhotosHandler = function() {
	// Populates a preview pane with a thumbnail of the uploaded 
	// image.
	
	oPreviewPane = $(".preview-pane");
	changer.communityportal.showLoader($('.preview-pane'));
	oPreviewPane.load('/load/previews/', function() {
		changer.communityportal.removeLoader();
	});
};


changer.communityportal.handleAjaxPost = function() {
	// Handle ajax post events
    
	$(".ajax-form").live("submit", function(e) {
		e.preventDefault();
		var $post = $(this);
		var url = $post.attr('action');
		console.log($post);
		console.log(url);

		$.post(url, $post.serialize())
			.success(function(data) {
				// window.console&&window.console.log("Success data: " + data);
				var $container = $post.closest('.form-box');
				var $formdata = $('.widget-content .form-box', data);
				// window.console&&window.console.log($formdata);
				$container.html($formdata);
				changer.communityportal.findAndHighlightMessages(data);
                changer.communityportal.datePickerHandler();
			});
			
	});
};

changer.communityportal.findAndHighlightMessages = function(data) {
	var $msgContainer = $('div#messages-container');
	var $msgdata = $('.messages', data);
	console.log($msgdata);
	$msgContainer.html($msgdata);
	changer.communityportal.doHighlightMessages();
};

$(document).ready(function() {	
	changer.communityportal.streamNav.init();
	changer.communityportal.ajaxHandlerNews();
	changer.communityportal.loginHandler();
	changer.communityportal.editProfileHandler();
	changer.communityportal.friendProfileHandler();
	changer.communityportal.addCommentHandler();
	changer.communityportal.removeCommentHandler();
	changer.communityportal.showCommentsHandler();
	changer.communityportal.jAccordionHandler();
	changer.communityportal.lightBoxHandler();
	changer.communityportal.publicationHandler();
	changer.communityportal.datePickerHandler();
	changer.communityportal.handleAjaxPost();

	changer.communityportal.doHighlightMessages();
});


/* Carousel */
// Reason for deletion: Not used anymore in new lay-out
//changer.communityportal.cCarouselHandler = function() {
//	new changer.communityportal.cCarrousel('ul#groups-navigation > li', 'div.ccarousel-prev', 'div.ccarousel-next');
//};
//changer.communityportal.cCarrousel = function(szsItems, szsButtonPrev, szsButtonNext) {
//	this.items = $(szsItems);
//	this.buttonPrev = $(szsButtonPrev);
//	this.buttonNext = $(szsButtonNext);
//	this.init();
//};
//changer.communityportal.cCarrousel.prototype = {
//	maxVisible: 6,
//	firstVisible: 0,
//	set: function() {
//		var selected = $('.selected', this.items.parent());
//		if(selected.length) {
//			this.firstVisible = this.items.index(selected);
//		}
//	},
//	draw: function() {
//		var oSelected = this.items.slice(this.firstVisible, this.firstVisible + 1);
//		var oVisible = this.items.slice(this.firstVisible + 1, this.firstVisible + 1 + this.maxVisible);
//		var oHidden = this.items.slice(0, this.firstVisible);
//		oHidden.push(this.items.slice(this.firstVisible + this.maxVisible, this.items.length));
//
//		$('img', oHidden).animate({width: 0}, function() {$(this).parents('li:first').hide();});
//		if($('.selected', this.items.parent()).length) {
//			$('img', oSelected.show()).animate({width: 50, height: 50});
//		}
//		else {
//			$('img', oSelected.show()).animate({width: 35, height: 35});
//		}
//		$('img', oVisible.show()).animate({width: 35, height: 35});
//	},
//	init: function() {
//		var oThis = this;
//		this.buttonPrev.click(function() {
//			if(oThis.firstVisible > 0) {
//				oThis.firstVisible--;
//			}
//			oThis.draw();
//		});
//		this.buttonNext.click(function() {
//			if(oThis.firstVisible < oThis.items.length - 1) {
//				oThis.firstVisible++;
//			}
//			oThis.draw();
//		});
//		this.set();
//		this.draw();
//	}
//};

/* LOAD PROFILES */
// Reason for deletion: Partly replaced by stream nav. 'ajax' class hack

// //This bit lets you navigate through personal and community profiles without reloading entire page
// //Set class ajax on elements containing anchors that should respond
// changer.communityportal.ajaxHandler.loadProfiles = function() {
// 	$('.ajax a').bind('click', function(e) {
// 		e.preventDefault();
// 		$('#profile-container').load(this.href + ' #profile-content', changer.communityportal.doScrollUp());	
// 	});
// };


/* SEND ALBUM */
// Reason for deletion: Harcoded + testing = unfinished and not working.

// changer.communityportal.genericFunctions.sendAlbum = function(community, title, body, fnCallback) {
// 	$.post("/posts/new/album/", {community: community, title: title, description: body}, function(data) {
// 		alert(data);
// 		fnCallback('/posts/new/album/37/');
// 	});
// };


/* ALBUM/PHOTO UPLOAD */
// Reason for deletion: Old way of uploading an album

// changer.communityportal.ajaxHandler.photo = function(oSelf) {
// 	alert(oSelf);
// 	var oParent = oSelf.closest('.dialog');
// 	var oCommunity = $('#id_community', oParent);
// 	var oTitle = $('#id_title', oParent);
// 	var oBody = $('#id_description', oParent);
// 	var community = oCommunity.val();
// 	var title = oTitle.val();
// 	var body = oBody.val();
// 	
// 	fnAfterPost = function(data) {
// 		oSelf.dialog('close');
// 		//oSelf.load(data + ' .dialog-wrapper');
// 	};
// 	changer.communityportal.genericFunctions.sendAlbum(community, title, body, fnAfterPost);
// };


/* PHOTOS UPLOAD */
// Reason for deletion: Photo's go via uploadify and the normal forms now 
// instead of a custom photo/album form.

// changer.communityportal.photos = changer.communityportal.photos || {};
// changer.communityportal.photos.init = function() {
// 	$('.add-photos').live('click', function(e) {
// 		e.preventDefault();
// 		var oButton = $(this);
// 		if(!oButton.data('dialog')) {
// 			oButton.data('dialog', oButton.parents('aside:first').find('div.dialog'));
// 		}
// 		oButton.data('dialog').dialog({ 
// 			buttons: { 
// 				"Annuleer": function() {
// 					$(this).dialog('close');
// 				},
// 				"Verder": function() { 
// 					changer.communityportal.ajaxHandler.photo($(this));
// 				}
// 			}
// 		});
// 	});
// };


/* NEW FORM SELECT*/

// changer.communityportal.newFormSelect = changer.communityportal.newFormSelect || {};

// changer.communityportal.newFormSelect.init = function() {
// 	changer.communityportal.newFormSelect.setDefaults();
// 	changer.communityportal.newFormSelect.handleClick();
// };
// 
// changer.communityportal.newFormSelect.setDefaults = function() {
// 	console.log("newFormSelector");
// 	$('div.content .boxes > div').hide();
// 	console.log($('div.content .boxes'));
// 	$('div.content > .boxes > div:first').show();
// };
// 
// changer.communityportal.newFormSelect.handleClick = function() {
// 	console.log("handleclick");
// 	$('div.content > .tabs a').bind('click', function() {
// 		oSelf = $(this);
// 		oContainer = oSelf.closest('div.content');
// 		aLinks = $('.tabs a', oContainer);
// 		aBoxes = $('.boxes > div', oContainer);
// 		console.log(aLinks);
// 		
// 		aLinks.each(function(){ $(this).removeClass('active'); });
// 		oSelf.addClass('active');
// 		iCurrentIndex = aLinks.index(oSelf);
// 		
// 		aBoxes.each(function(){ $(this).hide(); });
// 		oBox = aBoxes.eq(iCurrentIndex);
// 		oBox.show();
// 	});
// 	
// };

/* FORM SELECT */
// Reason for deletion: The simple uploadify function we have now 
// doesn't play nice with toggling the display of a tab, when each tab has
// its own uploadify. We're now going to implement the forms server-side.


// changer.communityportal.formSelect = changer.communityportal.formSelect || {};

// 
// 
// // This bit might become redundant, its for selecting which post-type to post
// changer.communityportal.formSelect.init = function() {
// 	changer.communityportal.formSelect.setDefaults();
// 	changer.communityportal.formSelect.handleClick();
// 	changer.communityportal.formSelect.handleExternalClick();
// };
// 
// changer.communityportal.formSelect.setDefaults = function() {
// 	$('div.content > .form-boxes > div').hide();
// 	$('div.content > .form-boxes > div:first').show();
// };
// 
// changer.communityportal.formSelect.handleClick = function() {
// 	$('div.content > .form-select a').bind('click', function() {
// 		oSelf = $(this);
// 		oContainer = oSelf.closest('div.content');
// 		aLinks = $('.form-select a', oContainer);
// 		aBoxes = $('.form-boxes > div', oContainer);
// 		
// 		aLinks.each(function(){ $(this).removeClass('active'); });
// 		oSelf.addClass('active');
// 		iCurrentIndex = aLinks.index(oSelf);
// 		
// 		aBoxes.each(function(){ $(this).hide(); });
// 		oBox = aBoxes.eq(iCurrentIndex);
// 		oBox.show();
// 	});
// 	
// };
// // moves bekijk alle vrienden up to the right friends tab
// changer.communityportal.formSelect.handleExternalClick = function() {
// 	$('.form-selector').live('click', function(e) {
// 		var id = this.id;
// 		e.preventDefault();
// 		$('.icon.' + id + '> a').click();
// 		changer.communityportal.doScrollUp();
// 	});
// };


// /* UPLOADIFY */
// Reason for deletion: For our purposes and the time we have this is 
// much easier and clearer in the template.

// $(document).ready(function() {
// 	$('.multi-file-upload').each(function() {
// 		changer.communityportal.uploadifyInit.apply($(this));
// 	});
// });

// changer.communityportal.uploadifyInit = function() {
// 	var uploadify_url = this.attr('uploadify-url');
// 	var uploadify_path = '/layout/js/uploadify/';
// 	var upload_path = this.attr('upload-path');
// 	var upload_complete_url = this.attr('upload-complete-url');
// 	var oObject = this;
// 	var uploader = $('input', this);
// 	uploader.attr('id', 'uploader-' + parseInt(Math.random() * 10000));
// 	var allComplete = function(event, data) {
// 		uploader.load(upload_complete_url, {
// 			'filesUploaded': data.filesUploaded,
// 			'errorCount': data.errors,
// 			'allBytesLoaded': data.allBytesLoaded,
// 			'speed': data.speed
// 		});
// 		// Raise custom event
// 		//uploader.trigger('allUploadsComplete', data);
// 	};
// 	console.log("uploadify called with the following params " + upload_path + "uploadify path " + uploadify_path + "uloadify_url " + uploadify_url)
// 	$('input', this).uploadify({
// 		'uploader'  : uploadify_path + 'uploadify.swf',
// 		'script'    : uploadify_url,
// 		'cancelImg' : uploadify_path + 'cancel.png',
// 		'auto'      : true,
// 		'folder'    : upload_path,
// 		'multi'     : true,
// 		'onAllComplete' : allComplete
// 	});
// };


/* STIPPELLIJN LOAD */
// Reason for deletion: Added a loading.gif instead.

/* init loader */
// oSelf.val('');
// oSelf.attr('disabled', 'disabled');
// 
// var loader = setInterval(function() {
// 	oSelf.val(oSelf.val() + '.');
// }, 100);

/* alt init loader */
// var loader = setInterval(function() {
// 	var h = oTarget.find('h2');
// 	h.html(h.html() + '.');
// }, 100);

/* callback */
// clearInterval(loader);
// oSelf.val('');
// oSelf.removeAttr('disabled');

