/*
	User Interface
	--------------------------------------------------
	--------------------------------------------------
*/

	/* ++++ Dropdown Menu (.JSDropdownMenu) ++++ */

		$(document).ready(function(){	
			$('.JSDropdownMenu > a').click(function(e) {
			
				/*
				// Remove active menus
				$('.UIDropdownMenu.active').remove();
				$('.JSDropdownMenu.active').removeClass('active');
			
				// Get dropdown menu
				var $button = $(this).parent();
				var $menu = $(this).siblings('.UIDropdownMenu');
				var pos = $.extend({}, $button.offset(), {width: this.offsetWidth, height: this.offsetHeight});
				
				// Clone dropdown menu and put it at the bottom
				var $newmenu = $menu.clone().appendTo('body').addClass('active');
				$newmenu.show();
				$newmenu.css({top: pos.top + pos.height, left: pos.left + 1});
				
				// Add button style
				$button.addClass('active');
				
				// Reposition on window resize
				$(window).resize(function(){
					var newpos =  $.extend({}, $button.offset(), {width: this.offsetWidth, height: this.offsetHeight});
					$newmenu.css({top: newpos.top + newpos.height, left: newpos.left + 1});
				});
				
				return false;
				*/
			
				var $origThis = $(this);
				var $this = $origThis.parent();
			
				// 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');
				});
				
				// Prevents JSDropdownMenu from hiding when clicked
				$this.click(function(e){
					e.stopPropagation();
				});

				// is this the login dropdown?
				if ($origThis.hasClass('js-login')) {
					$('#txtAlias').focus();
				}
				
				return false;
				
			});

		});


	/* ++++ Album gallery slider (.JSImageSlider) ++++ */
	
		$(document).ready(function(){
		
			// 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);
			});
		});
	
	
	/* ++++ Sidebar Ad Scroll ++++ */
		/* Temp. disabled
		$(document).ready(function(){
			var el = $('#sidebar-ad');
			var elpos_original = el.offset().top;
			$(window).scroll(function(){
			    // var elpos = el.offset().top;
			    var windowpos = $(window).scrollTop();
			    var finaldestination = windowpos;
			    if(windowpos<elpos_original) {
			        finaldestination = elpos_original;
			        el.stop().css({'top':0});
			    } else {
			        el.stop().animate({'top':finaldestination-elpos_original+4},300);
			    }
			});
		});
*/


/*
	Dynamic
	--------------------------------------------------
	--------------------------------------------------
*/

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

		$(document).ready(function(){	
			$('.JSDropdownInbox > a').click(function() {
				var $this = $(this);
				var $menu = $this.siblings('.JSContent');
				var hasMessages = $this.is('.JSHasMessages');
				var messageList = $menu.children('.JSMessageList');
				if (hasMessages && 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 = '';
					
			    messageList.find('ul').append('<li><a href="/default.aspx?section=msg&page=message&id='+messages[i].Id+'"><img class="UIUserImage" src="http://'+messages[i].Image+'" alt="" /><span class="UIDropdownMenu-Inbox-ItemHeader"><span class="UIUserAlias">'+messages[i].Alias+'</span> <span class="UITimeAgo">'+messages[i].TimeAgo+'</span></span><span class="UIDropdownMenu-Inbox-ItemText">'+messages[i].Message+'</span></a></li>');
		    }
			if(messages.length==0)
			    messageList.hide();
			//$('#JSDropdownMenuMessageCount').html('<strong>'+messages.length+'</strong> melding'+(messages.length>1?'er':''));
		}





/*
	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(){
			$(".UIField-InlineLabel label").inFieldLabels({ fadeOpacity:0.3, fadeDuration:300 });
		});



	/*
		++++++++++++++++++
		CSS Browser Selector v0.3.4 (http://rafael.adm.br/css_browser_selector)
		++++++++++++++++++
	*/
	
		function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',o='opera',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);
		

/*
    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;
}
