$(document).ready(function(){

	/*	Set content height to match sidebar
	----------------------------------------------------------------------------------------------------
	----------------------------------------------------------------------------------------------------*/
	
		var sidebarHeight = $('#fw-content-sidebar').outerHeight();
		$('#fw-content-main').css('minHeight',sidebarHeight);



	/*	Fixed elements
	----------------------------------------------------------------------------------------------------
	----------------------------------------------------------------------------------------------------*/
	
		// Header
		function fixedheader() {
	
			var fixed = $('#fw-header');
			var content = $('#fw-body');
	
			if ( fixed.length ) {
				var fixedheight = $(fixed).outerHeight();
				var fixedtop = $(fixed).offset().top - parseFloat($(fixed).css('marginTop').replace(/auto/, 0));
		
				$(window).scroll(function(event){
					var y = $(this).scrollTop();
			
					if (y >= fixedtop) {
						$(fixed).addClass('fixed');
						$(content).css('marginTop', fixedheight);
					}
					else {
						$(fixed).removeClass('fixed');
						$(content).css('marginTop', 0);
					}
				});
			}
	
		}
		
		// Side Ad
		function fixedsidead() {
	
			var fixed = $('#fw-content-sidebar .ad-side');
			var header = $('#fw-header');
	
			if ( fixed.length ) {
				var fixedheight = $(fixed).outerHeight();
				var headerheight = $(header).outerHeight();
				var fixedtop = $(fixed).offset().top - headerheight - 10 - parseFloat($(fixed).css('marginTop').replace(/auto/, 0));
				var fixedbottom = $('#fw-footer').offset().top - parseFloat($('#fw-footer').css('marginTop').replace(/auto/, 0));
		
				$(window).scroll(function(event){
					var y = $(this).scrollTop();
			
					if (y >= fixedtop) {
						$(fixed).addClass('fixed');
					}
					else {
						$(fixed).removeClass('fixed');
					}
					if (y >= (fixedbottom - fixedheight - headerheight - 6)) {
		                $(fixed).addClass('end');
		            }
		            else {
		                $(fixed).removeClass('end');
		            }

	
				});
			}
	
		}
		
		// Init (only if browser window is > 1024)
		if (!($('html').hasClass("lt-1024"))) {
			setTimeout(function(){
				fixedheader();
				fixedsidead();
			},1000);
		}


	/*	Dropdowns
	----------------------------------------------------------------------------------------------------
	----------------------------------------------------------------------------------------------------*/

		$('.ui-dropdown > .ui-button').click(function(e){
			
			e.preventDefault();
			
			// Get items relevant to clicked item
			$clickedItem = $(this);
			$clickedParent = $clickedItem.parent();
			
			// Get active items
			$activeItems = $('.ui-dropdown.js-active');
			
			if(!$clickedParent.hasClass('js-active')) {
				$activeItems.removeClass('js-active');
				$clickedParent.addClass('js-active');
			} else {
				$clickedParent.removeClass('js-active');
			}

			// Set a field active right away?
			if ($clickedParent.find('.js-focus:first').length > 0)
				$clickedParent.find('.js-focus:first').focus();
			
			e.stopPropagation();
		});

		$(document).mouseup(function(e){
			if (!$(e.target).closest('.ui-dropdown').length > 0) {
				$('.ui-dropdown.js-active').removeClass('js-active');
			}
		});
		
		$('.ui-dropdown-menu').mouseup(function(e){
			e.stopPropagation();
		});


		/*	Checks for messages in inbox (.JSDropdownInbox) ----------------------- */	

			$(document).ready(function() {
				$('.JSDropdownInbox > a').click(function() {
					var $this = $(this).closest('a');
					var $menu = $this.siblings('.JSContent');
					// var hasMessages = $this.hasClass('JSHasMessages');
					var messageList = $menu.children('.JSMessageList');
					if (messageList.find('li').length == 0) {
						messageList.show();
						NIU.Biip.Controls.FrameWork.Header.GetNewMessages(function(response) { GetNewMessages_callback(response, messageList); });
					}
				});
			});

			function GetNewMessages_callback(res, messageList) {
				messageList.find('.MessageLoader').hide();
				messages = res.value;
				for (i = 0; i < messages.length; i++) {
					// flush messages containing a filepath only
					if (messages[i].Message.length > 0 && messages[i].Message.match(/^\/[^\s]+\.html?$/))
						messages[i].Message = '';

					// set a special CSS class for unread messages
					var cssClass = !messages[i].IsRead ? 'class="unread"' : '';

					messageList.find('ul').append('<li ' + cssClass + '><a href="/default.aspx?section=msg&page=message&id=' + messages[i].Id + '"><img class="x-user-image" src="http://' + messages[i].Image + '" alt="" /><span class="x-item-header"><span class="x-user-alias">' + messages[i].Alias + '</span> <span class="x-item-time">' + messages[i].TimeAgo + '</span></span><span class="x-item-text">' + messages[i].Message + '</span></a></li>');
				}
				if (messages.length == 0) {
					messageList.find('ul').append('<li class="empty">Du har ingen innboksmeldinger</li>');
				}
			}		


		/*	Legacy Dropdown (.JSDropdownMenu) ----------------------- */

			$('.JSDropdownMenu > a').click(function(e) {
				var $origThis = $(this);
				var $this = $origThis.parent();

				console.log('test');

				// Hides other active JSDropdownMenus
				$('.JSDropdownMenu.active').removeClass('active');

				// Toggles current JSDropdownMenu
				$this.toggleClass('active');

				// Hides JSDropdownMenu on click outside
				$('html').click(function() {
					$this.removeClass('active');
				});

				// Any fields wanting focus right away?
				console.log($this.find('.JSFocus:first'));
				if ($this.find('.JSFocus:first').length > 0) {
					console.log($this.find('.JSFocus:first'));
					$this.find('.JSFocus:first').focus();
				}

				// Prevents JSDropdownMenu from hiding when clicked
				$this.click(function(e) {
					e.stopPropagation();
				});

				return false;
			});



	/*	Album gallery slider (.JSImageSlider)
	----------------------------------------------------------------------------------------------------
	----------------------------------------------------------------------------------------------------*/

		function gallerySlider() {

			// Get our elements for faster access and set overlay width
			var div = $('.JSImageSlider'), divInner = $('.JSImageSlider > div'), divPadding = 2;

			// Get menu width
			var divWidth = div.width();

			// Remove scrollbars
			div.css({overflow: 'hidden'});

			// Find last image
			var lastImg = divInner.find('a:last-child');

			// Find current image
			var currImg = divInner.find('a.current');

			// When user move mouse over menu
			div.mousemove(function(e){

				// As images are loaded divInner width increases, so we recalculate it each time
				var divInnerWidth = lastImg[0].offsetLeft + lastImg.outerWidth() + divPadding;
				var left = (e.pageX - div.offset().left) * divInnerWidth / divWidth;
				div.scrollLeft(left);
			});
		
		}
	
		// Init
		gallerySlider();
	
	
	
	/*	Form Elements
	----------------------------------------------------------------------------------------------------
	----------------------------------------------------------------------------------------------------*/

		// Checkbox On-Off Switch
		function inputSwitch() {
			$('.input-switch').each(function() {					
				if ($(this).children('input[type=checkbox]').is(':checked')) {
					$(this).addClass('checked');
				}
			
				$(this).children('label').click(function() {
					if ($(this).siblings('input[type=checkbox]').is(':checked')) {
						$(this).parent().removeClass('checked');
					} else {
						$(this).parent().addClass('checked');
					}
				});
			});
		}
		
		// Init
		inputSwitch();
		

});


/*	Plugins
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------*/

	/*	In-Field Label v1.0 (http://fuelyourcoding.com/scripts/infield.html) ----------------------- */

		(function($){$.InFieldLabels=function(b,c,d){var f=this;f.$label=$(b);f.label=b;f.$field=$(c);f.field=c;f.$label.data("InFieldLabels",f);f.showing=true;f.init=function(){f.options=$.extend({},$.InFieldLabels.defaultOptions,d);if(f.$field.val()!=""){f.$label.hide();f.showing=false};f.$field.focus(function(){f.fadeOnFocus()}).blur(function(){f.checkForEmpty(true)}).bind('keydown.infieldlabel',function(e){f.hideOnChange(e)}).change(function(e){f.checkForEmpty()}).bind('onPropertyChange',function(){f.checkForEmpty()})};f.fadeOnFocus=function(){if(f.showing){f.setOpacity(f.options.fadeOpacity)}};f.setOpacity=function(a){f.$label.stop().animate({opacity:a},f.options.fadeDuration);f.showing=(a>0.0)};f.checkForEmpty=function(a){if(f.$field.val()==""){f.prepForShow();f.setOpacity(a?1.0:f.options.fadeOpacity)}else{f.setOpacity(0.0)}};f.prepForShow=function(e){if(!f.showing){f.$label.css({opacity:0.0}).show();f.$field.bind('keydown.infieldlabel',function(e){f.hideOnChange(e)})}};f.hideOnChange=function(e){if((e.keyCode==16)||(e.keyCode==9))return;if(f.showing){f.$label.hide();f.showing=false};f.$field.unbind('keydown.infieldlabel')};f.init()};$.InFieldLabels.defaultOptions={fadeOpacity:0.5,fadeDuration:300};$.fn.inFieldLabels=function(c){return this.each(function(){var a=$(this).attr('for');if(!a)return;var b=$("input#"+a+"[type='text'],"+"input#"+a+"[type='password'],"+"textarea#"+a);if(b.length==0)return;(new $.InFieldLabels(this,b[0],c))})}})(jQuery);
		$(document).ready(function(){
			$(".ui-infieldlabel label, .UIField-InlineLabel label").inFieldLabels({ fadeOpacity:0.3, fadeDuration:300 });
		});
		
	
	/*	Fancybox ----------------------- */

		function modalIframe(elem,width,height){
		    $.fancybox({
				'padding'		: 0,
				'autoScale'		: true,
				'transitionIn'	: 'none',
				'transitionOut'	: 'none',
				'height'		: height,
				'width'			: width,
				'title'			: elem.title,
				'href'			: elem.href,
				'type'			: 'iframe'
			});
			return false;
		}




/*	Flood Prevention
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------*/

	var FloodPrevention = {
		operations: [],

		// returns true if the check allows the user to perform the operation
		check: function(method, limitCount, limitMinutes, limitMessage) {
			// no operations added?
			if (this.operations.length == 0)
				return true;

			// operation not found?
			var operationRef = this.getOperation(method);
			if (operationRef == null)
				return true;

			// invocation limit exceeded?
			if (typeof (limitCount) == 'undefined' || limitCount == 1)
				return false;

			if (operationRef.invokeCount >= limitCount) {
				var validCheck = true;

				// no timelimit set
				if (typeof (limitMinutes) == 'undefined' || limitMinutes == 0) {
					validCheck = false;
				}
				// check timelimit
				else {
					var currentTime = new Date();
					var limitDate = currentTime.setTime(currentTime.getTime() - (limitMinutes * 60 * 1000));
					validCheck = operationRef.lastInvoked < limitDate;
				}

				// check was not valid, any message to display?
				if (!validCheck) {
					if (typeof (limitMessage) != 'undefined' && limitMessage.length > 0)
						alert(limitMessage);

					return false;
				}
			}

			return true;
		},

		// add successfully performed operation
		add: function(method) {
			var operationRef = this.getOperation(method);

			// new operation?
			if (operationRef == null) {
				operationRef = new Operation(method);
				this.operations.push(operationRef);
			}
			// existing operation
			else {
				operationRef.invokeCount++;
				operationRef.lastInvoked = new Date();
			}
		},

		// searches thru the list of performed operations, returns
		// the object if any match was found
		getOperation: function(method) {
			var operationRef = null;

			for (var i = 0; i < this.operations.length; i++) {
				var operation = this.operations[i];
				// got method match?
				if (operation.method == method) {
					operationRef = operation;
					break;
				}
			}

			return operationRef;
		}
	}

	function Operation(method) {
		this.method = method;
		this.lastInvoked = new Date();
		this.invokeCount = 1;
	}
