(function(){
	var ui = {
		/**
		 * @var object settings - The configuration of this library
		 */
		settings:{
			selectors : {
				groupSearch : {
					showForm : '.showform',
					hideForm : '.hideform',
					searchForm : '#search-form'
				},
				selectOnClick : '.selectOnClick',
				clearOnFocus : '.clearOnFocus',
				clearOnSubmit: '.clearOnSubmit'
			},
			translate : {
				clearOnSubmitDefault : ''
			},
			characterCounter:{
				'selector'	:	'.charCounter',
				'maxCharacters'	:	255
			}
		},

		userCookieData : null,


		/**
		 * Will be called as soon as this library is loaded
		 * into the main SE library
		 */
		init:function(){
			var me = this;
			$(document).ready(function() {
			//	me.clearOnFocus();
			//	me.closeStatusMessages();
				me.leftMenu();
				me.characterCounter();
				me.setInputClasses();
				me.bindOnSubmitForms();
				me.expandli();
				me.scrollToAnchor();
				me.setUserBox();
				tooltip();
				me.hideGroupSearchForm();
				me.selectOnClick();
				me.clearOnFocus();
				me.clearOnSubmit();
			});
		},

		leftMenu: function() {
			$("#navigation li a").bind('click', function(e) {
				if ($(this).parent().find("ul").is(':visible')) {
					$(this).parent().find("ul").hide();
				} else {
					$(this).parent().find("ul").show();
				}
			});
		},

		expandMenu: function() {

		},

		/**
		 * Read a cookie
		 */
		readUserCookie : function () {
			if (this.userCookieData === null){
				$.Jookie.Initialise("user", 0, false);
				var userObj = {};
				var list = ['uid', 'un', 'img', 'imgurl', 'o', 'msgs'];
				var listFull = ['userID', 'username', 'imageID', 'imageUrl', 'isOnline', 'nrMessages'];
				var i = 0, l = 0;
				for(i=0,l=list.length; i<l; i++){
					try{
						userObj[listFull[i]] = $.Jookie.Get("user", list[i]);
					} catch(e){
						userObj[listFull[i]] = null;
					}
				}
				this.userCookieData = userObj;
			}
			return this.userCookieData;
		},

		/**
		 * Determine the user box on top of the page
		 *
		 * @return this for chainability
		 */
		setUserBox:function(){

			var userObj = this.readUserCookie();

			$('#visitor').hide();
			$('#registered-user').hide();
			$('#firsttime-visitor').hide();

			if (userObj.username !== null && typeof userObj.username != 'undefined' && userObj.isOnline){
				//Hide default box
				//$('#visitor').hide();

				//Show logged in user box
				var boxID = 'registered-user';
				var box = $('#'+boxID);

				var i, l = 0;
				if (box !== null){
					//box.toggle();
					var html = box.html();
					if (html === null) {
						return;
					}
					var listFull = ['userID', 'username', 'imageID', 'imageUrl', 'isOnline', 'nrMessages'];

					for(i=0,l=listFull.length; i<l; i++){
						var repString = "\\#" + listFull[i];
						var myregexp = new RegExp(repString, "g");
						var txt = userObj[listFull[i]];
						html = html.replace(myregexp, txt);
					}
					box.html(html);

					box.toggle();

					// Code for Avatar
				}

			} else if (userObj.username !== null && typeof userObj.username != 'undefined') {
				$('#visitor').show();
			} else {
				$('#firsttime-visitor').show();
			}

			//IE 8 FIX
			$(".user-panel").css("position","static");
			$(".user-panel").css("top","0px");

			return this;
		},

		/**
		 * Bind a clear on focus function on given selectors
		 *
		 * @return this for chainability
		 */
		clearOnFocus:function(){
			//Every element that needs to clear on focus
			$(this.settings.selectors.clearOnFocus).bind('focus blur', function (e) {
				if (e.type == 'blur' && this.value == ''){
					this.value = this.defaultValue;
				}
				else if (e.type == 'focus' && this.value == this.defaultValue){
					this.value = '';
				}
			});
			return this;
		},

		/**
		 * Functionality to close a statusmessage
		 *
		 * @return this for chainability
		 */
		closeStatusMessages:function(){
			//Close status message
			var me = this;
			$(this.settings.selectors.closeStatusMessages).bind('click', function (e) {
				e.preventDefault();
				me._closeMessage.call(this);
				return false;
			});
			return this;
		},

		/**
		 * Hide a message pane
		 */
		_closeMessage:function(){
			var me = this;
			if ($(me).get(0).nodeName.toLowerCase() == "a"){
				me = $(me).parent();
			}
			$(me).fadeOut(1000);
		},

		/**
		 * Functionality to close a statusmessage automatically after a determined period of time
		 *
		 * @return this for chainability
		 */
		autoCloseStatusMessages:function(){
			var lib = this;
			//Auto close status message
			$(this.settings.selectors.autoCloseStatusMessages).each(function() {

				var me = this;
				window.setTimeout(function(){
					lib._closeMessage.call(me);
				},lib.settings.autoCloseTimer);
				//return false;
			});
			return this;
		},

		/**
		 * Show a statusmessage and hide it automatically after a determined period of time
		 *
		 * @return this for chainability
		 */
		autoShowHideStatusMessage : function(id) {
			var box = $('#'+id);
			if (box) {
				box.fadeIn(1000);

				var me = this;
				window.setTimeout(function(){
					me._closeMessage.call(box);
				},me.settings.autoCloseTimer + 1000);
			}
			return this;
		},

		/**
		 * Functionality to add classes to all the input boxes
		 *
		 * @return this for chainability
		 */
		setInputClasses : function(){
			if (jQuery.browser.msie){
				$("input").each(function() {
					var me = this;
					var type = me.type;
					type = type.charAt(0).toUpperCase() + type.substr(1);
					$(me).addClass('input'+type);
				});
			}
			return this;
		},

		/**
		 * Set the value of a hidden field to the id
		 * of the button that was clicked in the form
		 *
		 * @param Object obj The button that was clicked
		 * @param String hidden_id The id of the hidden field
		 *
		 * @return void
		 */
		setButtonClicked:function(obj, hidden_id){

			var re = new RegExp(/\[(.*)\]/);
			var name = obj.name;

			var matches = name.match(re);
			if (matches)
			{
				name = matches[1];
			}
			var obj2 = document.getElementById(hidden_id);

			// support for multiple forms on 1 page:
			var obs = document.getElementsByName(obj2.name);
			for(var i=0,l=obs.length;i<l;i++){
				if (obs[i].form == obj.form){
					obs[i].value = name;
				}
			}
		},

		/**
		 * Create a charactercounter on elements matched by selector
		 *
		 * @param elSelector
		 *
		 * @return void
		 */
		characterCounter:function(elSelector,maxCharacters){
			if (typeof elSelector == "undefined"){
				elSelector = this.settings.characterCounter.selector;
			}
			if (typeof maxCharacters == "undefined"){
				maxCharacters = this.settings.characterCounter.maxCharacters;
			}

			var me = this;
			$(elSelector).each(function(){

				var container = document.createElement("div");
				$(container).addClass("charsRemainingContainer");

				var charContainer = document.createElement("span");
				$(charContainer).addClass("charsRemaining");
				$(charContainer).attr("rel",maxCharacters);
				var msg = document.createElement("span");
				$(msg).html(me.settings.characterCounter.messageRemaining);

				// get current stringlength:
				var stringlength = $(this).val().length;
				var remaining = maxCharacters - stringlength;
				$(charContainer).html(remaining);

				$(container).append($(charContainer)).append($(msg));

				$(this).after($(container));

				$(this).bind("keyup",function(e){
					$(charContainer).html($(charContainer).attr("rel")*1 - $(this).val().length);
				});
			});
		},



		bindOnSubmitForms : function () {

			$('form').each(function(){
				var form = $(this);
				var buttonClicked = form.find("input[id$='buttonClicked']");

				var button = form.find("button[type='submit']:first");
				if (buttonClicked.length == 1 && button.length == 1) {
					button = button[0];
					form.bind('submit', function(){
						if (buttonClicked.val() == '') {
							SE.ui.setButtonClicked(button, buttonClicked.attr('id'));
						}
					});
				}
			});
		},

		expandli : function() {

			/* expand a to li in ul.wrap */

			$("ul.wrap li").click(function(){
				links = $(this).find("a.expand");
				if (links.length > 0) {
					window.location=$(links[0]).attr("href"); return false;
				}
			});

			/* expand a to div.wrap */

			$("div.wrap").click(function(){
				links = $(this).find("a.expand");
				if (links.length > 0) {
					window.location=$(links[0]).attr("href"); return false;
				}
			});

			/*  List item hover add class script  */

			$('ul.wrap li').hover(function() {
				$(this).addClass('hover');
				links = $(this).find("a.expand");
				if (links.length > 0) {
				 $(this).addClass('expanded');
					}
				 }, function() {
				 $(this).removeClass('hover');
				 $(this).removeClass('expanded');
				});


		},


		scrollToAnchor : function() {
			$(".scroll").click(function(event){
				//prevent the default action for the click event
				event.preventDefault();

				//get the full url - like mysitecom/index.htm#home
				var full_url = this.href;

				//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
				var parts = full_url.split("#");
				var trgt = parts[1];

				//get the top offset of the target anchor
				var target_offset = $("#"+trgt).offset();
				var target_top = target_offset.top;

				//goto that anchor by setting the body scroll top to anchor top
				$('html, body').animate({scrollTop:target_top}, 500);
			});
		},

		hideGroupSearchForm : function () {
			var me = this;
			$(me.settings.selectors.groupSearch.showForm).bind("click",function(e){
				$(me.settings.selectors.groupSearch.showForm).hide();
				$(me.settings.selectors.groupSearch.hideForm).show();
				$(me.settings.selectors.groupSearch.searchForm).slideDown('fast');
			});
			$(me.settings.selectors.groupSearch.hideForm).bind("click",function(e){
				$(me.settings.selectors.groupSearch.hideForm).hide();
				$(me.settings.selectors.groupSearch.showForm).show();
				$(me.settings.selectors.groupSearch.searchForm).slideUp('fast');
			});
		},

		/**
		 * Select the value of a textfield when clicking in it
		 *
		 * @return this for chainability
		 */
		selectOnClick : function () {
			var me = this;
			if ('' !== me.settings.selectors.selectOnClick) {
				$(me.settings.selectors.selectOnClick).focus(function(){
					$(this).select();
				});
			}
			return this;
		},

		/**
		 * Empty the form value if it is the standard text
		 *
		 * @return this for chainability
		 */
		clearOnSubmit : function () {
			var me = this;

			if ('' !== me.settings.selectors.clearOnSubmit) {
				var element = $(me.settings.selectors.clearOnSubmit);
				if (element.length > 0) {
					$(element.get(0).form).bind('submit', function(){
						if (me.settings.translate.clearOnSubmitDefault === element.val()) {
							element.val('');
						}
					});
				}
			}
			return this;
		},

		showPollOnHomepage: function(poll_id) {
			var voted = false;

			var cookie = document.cookie.split(';');
			for (o in cookie) {
				var s = cookie[o].split('=');
				if ($.trim(s[0]) == 'poll_' + poll_id && $.trim(s[1]) == 'voted') {
					voted = true;
				}
			}

			if (voted) {
				// indien cookie gezet:
				$("#poll_voting").hide();
				$("#poll_results").show();
			} else {
				// indien cookie niet gezet
				$("#poll_voting").show();
				$("#poll_results").hide();
			}
		},

		scrollBusy:{
			left:{},
			right:{}
		},

		scrollLeft : function (field) {
			var me = this;
			if (typeof field === 'string') {
				field = $(field);
			}

			if (typeof me.scrollBusy.left[field.attr('id')] === 'undefined') {
				me.scrollBusy.left[field.attr('id')] = false;
			}

			if (!me.scrollBusy.left[field.attr('id')]) {
				me.scrollBusy.left[field.attr('id')] = true;

				var parElement = $(field).parent();
				var parElement_width = this._getEntireElementWidth(parElement);
				var field_width = this._getEntireElementWidth(field);


				//alert(parseInt($(field).css("left").replace("px","")));
				//alert(-(field_width - parElement_width));

				var tenden = false;
				if (parseInt($(field).css("left").replace("px","")) < -(field_width - parElement_width)){
					tenden = true;
				}

				if (!tenden) {
					var firstElement = field.find('li').get(0);
					var width = this._getEntireElementWidth(firstElement);
					field.animate({
						left: '-=' + width
					},200, function() {
						me.scrollBusy.left[field.attr('id')] = false;
					});
				} else {
					me.scrollBusy.left[field.attr('id')] = false;
				}


				/*
				//var todayElement = $(field).find('li.today').get(0);
				var currentElement = $(field).find('li.current').get(0);
				var lastElement = $(field).find('li:last').get(0);

				var tenden = false;
				if (currentElement === lastElement) {
					tenden = true;
				}

				if (!tenden) {
					////$('.popup').hide();
					// scroll this to the left: (width + paddingLR + borderLR + marginLR)
					var firstElement = field.find('li').get(0);
					var width = this._getEntireElementWidth(firstElement);
					field.animate({
						left: '-=' + width
					},200, function() {
						//$(todayElement).removeClass('today');
						//$(todayElement).next().addClass('today');
						$(currentElement).removeClass('current');
						$(currentElement).next().addClass('current');
						me.scrollBusy.left[field.attr('id')] = false;
					});
				} else {
					me.scrollBusy.left[field.attr('id')] = false;
				}*/
			}
		},

		scrollRight : function (field) {
			var me = this;
			if (typeof field === 'string') {
				field = $(field);
			}

			if (typeof me.scrollBusy.right[field.attr('id')] === 'undefined') {
				me.scrollBusy.right[field.attr('id')] = false;
			}

			if (!me.scrollBusy.right[field.attr('id')]) {
				me.scrollBusy.right[field.attr('id')] = true;

				var tenden = false;
				if (parseInt($(field).css("left").replace("px","")) > 0) {
					tenden = true;
				}

				if (!tenden) {
					$('.popup').hide();
					// scroll this to the left: (width + paddingLR + borderLR + marginLR)
					var firstElement = field.find('li').get(0);
					var width = this._getEntireElementWidth(firstElement);
					field.animate({
						left: '+=' + width
					},200, function() {
						me.scrollBusy.right[field.attr('id')] = false;
					});
				} else {
					me.scrollBusy.right[field.attr('id')] = false;
				}



				/*
				//var todayElement = $(field).find('li.today').get(0);
				var currentElement = $(field).find('li.current').get(0);
				var firstElement = $(field).find('li:first').get(0);

				var tenden = false;
				if (currentElement === firstElement) {
					tenden = true;
				}

				if (!tenden) {
					$('.popup').hide();
					// scroll this to the left: (width + paddingLR + borderLR + marginLR)
					var firstElement = field.find('li').get(0);
					var width = this._getEntireElementWidth(firstElement);
					field.animate({
						left: '+=' + width
					},200, function() {
						//$(todayElement).removeClass('today');
						//$(todayElement).prev().addClass('today');
						$(currentElement).removeClass('current');
						$(currentElement).prev().addClass('current');

						me.scrollBusy.right[field.attr('id')] = false;
					});
				} else {
					me.scrollBusy.right[field.attr('id')] = false;
				}*/
			}
		},

		showDailyRecipePopup : function() {
			var posiX = -28;
			var posiY = 4;
			// these 2 variable determine popup's distance from the cursor

			var me = this;

			$(".otdRecipeDay").hover(function(e){

				me.hideAllPopups();
				//if(window.menuTimeout)
				window.clearTimeout(window.menuTimeout);

				var otdID = $(this).attr('id').replace('otdrecipe_','');
				var popupID = 'popup_otdrecipe_' + otdID;
				var posiToolTipParent = $(this).parent().offset();//Creates the object that will return the coordinates of the hovered link
				var posiToolTip = $(this).offset();//Creates the object that will return the coordinates of the hovered link

				if($(this).hasClass("today")){
					posiX_shift = 4;
				}else{
					posiX_shift = 0;
				}
				$('#' + popupID).css("top",(posiToolTipParent.top + posiX + posiX_shift + $(this).outerHeight(true)) + "px")//Positionnement sur les Y
				$('#' + popupID).css("left",(posiToolTip.left + $(this).outerWidth(true)/2 + posiY - $('#' + popupID).outerWidth(true)/2) + "px")//Positionnement sur les X
				//$('#' + popupID).fadeIn("fast");//The fade-in animation of the tool tip
				$('#' + popupID).show();
		    },
			function(){
				//Clear timer
				window.clearTimeout(window.menuTimeout);

				//Start timer voor hiden van menu
				window.menuTimeout = window.setTimeout(me.hideAllPopups,2000);
		    });
		},
		hideAllPopups : function (){
			$(".calendar-popup").hide();
		},
		_getEntireElementWidth : function (element) {

			/*

			use jquery outerwidth

			var totalWidth = 0;

			totalWidth += $(element).width();
			totalWidth += $(element).css('padding-left').replace('px','') * 1;
			totalWidth += $(element).css('padding-right').replace('px','') * 1;
			totalWidth += $(element).css('margin-left').replace('px','') * 1;
			totalWidth += $(element).css('margin-right').replace('px','') * 1;

			totalWidth += $(element).css('border-left-width').replace('px','') * 1;
			totalWidth += $(element).css('border-right-width').replace('px','') * 1;
			*/

			return $(element).outerWidth(true);
		},

		centerOTD : function (field) {

			if (typeof field === 'string') {
				field = $(field);
			}
			var par = $(field).parent();

			var field_width = this._getEntireElementWidth(field);
			var par_width = this._getEntireElementWidth(par);

			if(field_width != par_width){

				//var delta = Math.round((field_width - par_width)/2);
				$(field).css('left', '-' + 107*1.5 + 'px');
			}


			/*
			var containerCenterPosition = this._getCenterPosition(par);
			var todayCenterPosition = this._getCenterPosition(field.find('.today:first'));

			if (containerCenterPosition != todayCenterPosition) {
				var delta = (containerCenterPosition - todayCenterPosition);
				if (delta > 0) {
				} else {
					delta += 5;
				}
				field.css('left', field.css('left').replace('px','')*1 + delta + 'px');
			}*/
		},

		_getCenterPosition : function (element) {
			var centerPosition = element.offset().left + this._getEntireElementWidth(element)/2;
			return centerPosition;
		}
	};
	SE.extend("ui",ui);
})();