$(document).ready(function()
{
	$('.checkallgroup').checkall();
	$('.fieldswap').fieldswap();
	$('.nn-info-pop').nninfopop();
});
(function($){
	$.fn.nnimage = function(options, _function){
		var defaultoptions = {};
		var options = $.extend(defaultoptions, options);

		return $(this).each(function(){
			var image = new Image();
			image.src = options.src;
			if(options.title !== undefined){image.title = options.title;}
			if(options.alt !== undefined){image.alt = options.alt;}
			if(options.height !== undefined){image.height = options.height;}
			if(options.width !== undefined){image.width = options.width;}
			if(options.id !== undefined){image.id = options.id;}

			if(_function !== undefined)
			{
				image.onload = _function;
			}
			this.appendChild(image);
		});
	};
})(jQuery);

/**
* Ajax-ified pagination
*/
(function($){
	$.fn.nnpagination = function(options){
		return this.each(function(){
			$(this).click(function()
			{
				$('.ajax-pagination-content').html('<img src="\/static\/common\/images\/ajax\/loading-animation.gif" alt="" \/>');
				$('.pagination a').removeClass('current');
				$(this).addClass('current');

				var $sUrl = $(this).attr('href');
				if($sUrl.indexOf("/ajax") != 0)
				{
					$sUrl = '/ajax' + $sUrl;
				}
				$.post($sUrl, function(response)
				{
					$('.ajax-pagination-content').html(response);
				});
				return false;
			});
		});
	};
})(jQuery);


/*
* jQuery function: nninfopop
* Description: Shows a layer, commmonly containing additional information, onmouseover.
			   If clicked the layer will stay onmouseout and become draggable.
			   The layer automatically positions itself where thre's enough room (ie left/right & top/bottom).
			   It's always relative to the icon.
			   jqueryui core & draggable are loaded on the fly when needed.
* Dependencies: jquery.ui.core.js & jquery.ui.draggable.js (onclick functionality enables drag)
*/
(function($){
	$.fn.nninfopop = function(options){

		var defaultoptions = {};
		var options = $.extend(defaultoptions, options);


		return this.each(function(){
			var obj = $(this);
			obj.show();

			$(this).data('toggle', true);

			if($(this).attr('class').match('sticky'))
			{
				obj.click(function()
				{
					obj.data('toggle', !obj.data('toggle'));

					if($('body').data('ui.draggable-loaded') === undefined)
					{
						$('body').append('<script type="text/javascript" src="/static/common/js/jquery-ui/jquery.ui.core.js"></script>');
						$('body').append('<script type="text/javascript" src="/static/common/js/jquery-ui/jquery.ui.draggable.js"></script>');
						$('body').data('ui.draggable-loaded', true);
						obj.data('layer').draggable();
					}
					else
					{
						obj.data('layer').draggable();
					}
				});
			}

			obj.mouseover(function()
			{
				$('.nn-info-pop').data('toggle', true);
				$('.nn-info-pop-layer').hide();

				if($(this).data('layer') === undefined)
				{
					oInfo = $(this).next('div');
					oInfo.after('<div class="nn-info-pop-layer"><div class="nn-info-pop-layer-title">' + $(this).attr('title') + '<\/div><div class="nn-info-pop-layer-content">' + oInfo.html() + '<\/div><\/div>');
					oLayer = oInfo.next('.nn-info-pop-layer');
					oLayer.hide();
					$(this).attr('title', '');
					$(this).data('layer', oLayer);
				}

				aItemPosition = $(this).position();
				iViewPortWidth = $(window).width();
				iViewPortHeight = $(window).height();
				iVievPortPositionTop = aItemPosition.top - $(window).scrollTop();
				iVievPortPositionLeft = aItemPosition.left - $(window).scrollLeft();

				iItemHeight = $(this).height()/2;
				iLayerHeight = oLayer.height();
				iTop = (iVievPortPositionTop + iLayerHeight < iViewPortHeight) ? aItemPosition.top  : aItemPosition.top - iLayerHeight + iItemHeight;

				iItemWidth = $(this).width();
				iLayerWidth = oLayer.width();
				iLeft = (iVievPortPositionLeft + iLayerWidth + iItemWidth < iViewPortWidth) ? aItemPosition.left + iItemWidth : aItemPosition.left - iLayerWidth - 10;

				$(this).data('layer').css('top', iTop);
				$(this).data('layer').css('left', iLeft);
				$(this).data('layer').show();
			});

			obj.mouseout(function()
			{
				if($(this).data('layer') !== undefined && $(this).data('toggle'))
				{
					$(this).data('layer').hide();
				}
			});

			obj.focus(function(){$(this).trigger('mouseover');});
			obj.blur(function(){$(this).trigger('mouseout');});
		});
	};
})(jQuery);


/*
* jQuery function: fieldswap
* Description: Toggles the value in an input box.
*/
(function($){
	$.fn.fieldswap = function(options){
		var defaultoptions = {attr: 'title'};
		var options = $.extend(defaultoptions, options);
		
		return this.each(function(){
			
			var text = (options.value !== undefined) ?  options.value : $(this).attr(options.attr);			
			$(this).focus(function()
			{
				if(text == $(this).val())
				{
					$(this).val('');
				}
			});
			$(this).blur(function()
			{
				if($(this).val() == '')
				{
					$(this).val(text);
				}
			});

			$(this).closest('form').submit(function()
			{
				if(text == $(this).val())
				{
					$(this).val('');
				}
			});
		});
	};
})(jQuery);

/*
* jQuery function: checkall
* Description: Adds a check all box that will toggle the checkboxes within the parent element.
* Options:	text: The text that is displayed next to/the toggle box. Default is "Select/Deselect All"
*/
(function($){
	$.fn.checkall = function(options){
		var defaultoptions = {
			text: "Select/Deselect All"
		};
		var options = $.extend(defaultoptions, options);
		return this.each(function(){
			var obj = $(this);
			obj.append('<label><input type="checkbox" class="checkallselect" />&nbsp;'+options.text+'</label>');
			$(obj.find('.checkallselect')).click(function()
			{
				obj.find('input[@type=checkbox]').attr('checked', $(this).is(':checked'));
			});
		});
	};
})(jQuery);

/*
* jQuery function: confirmdelete
* Description: Adds a confirmation check on click.
* Options:	textBefore: The text that is displayed in front of the options. Default is "Are you sure?"
* 			confirmText: The text that is displayed as the confirm option. Default is "Yes"
* 			cancelText: The text that is displayed as the cancel option. Default is "No"
*/
(function($){
	$.fn.confirmdelete = function(options){
		var defaultoptions = {
			textBefore: "Are you sure?",
			confirmText: "Yes",
			cancelText: "No"
		};
		var options = $.extend(defaultoptions, options);
		return this.each(function(){
			var obj = $(this);
			obj.click(function(){
				obj.after('<span class="confirm-delete-box">&nbsp;&nbsp;'+options.textBefore+' <a href="'+obj.attr('href')+'">'+options.confirmText+'</a> - <a href="#" class="confirm-delete-no">'+options.cancelText+'</a></span>');
				$('.confirm-delete-no').click(function(){
					$(this).parent('span').remove();
				});
				return false;
			});
		});
	};
})(jQuery);

/*
* jQuery function: nnclock
* Description: Adds a clock that updates runtime.
* Options:	interval: How often the clock updates in milliseconds. Default is 998 to compensate for processing time.
*			separator: Separator between hour, minute & second. default is ':'
			startTime: Start time in milliseconds
*/
var nnClockInterval;
(function($){
	$.fn.nnclock = function(options){
		var defaultoptions = {
			interval: 992,
			separator: ':',
			startTime: -1
		};
		var options = $.extend(defaultoptions, options);

		nnClockInterval = options.interval;
		this.html('<span class="hour"></span>' + options.separator + '<span class="minute"></span>' + options.separator + '<span class="second"></span>');
		updateClock(options.startTime);
	};
})(jQuery);

/*######## Clock Support Functions ########*/

function updateClock(a_iStartTime)
{
	iStartTime = parseInt(a_iStartTime);
	var oNow = new Date();
	if(iStartTime != -1)
	{
		oNow.setTime(iStartTime);
		iStartTime = iStartTime + 1000;
	}

	$('.hour').text(appendZero(oNow.getHours()));
	$('.minute').text(appendZero(oNow.getMinutes()));
	$('.second').text(appendZero(oNow.getSeconds()));

	setTimeout("updateClock(iStartTime)", nnClockInterval);
}

function appendZero(a_iValue)
{
	value = (10 > a_iValue) ? '0' + a_iValue : a_iValue;
	return value;
}

/*######## Clock Support Functions End ########*/

/**
* nnsuggest
* $('input#tag').nnsuggest({protocol: 'inline', source: '.available-tags'});
*/
(function($){$.fn.nnsuggest = function(options){

	var defaultoptions = {};
	var options = $.extend(defaultoptions, options);

	return this.each(function(){

		$(this).after('<div class="nnsuggest-container"></div>');

		$(this).keydown(function(e)
		{
			var obj = $(this);
			if((/^38$|^40$$/.test(e.keyCode) && $('div.nnsuggest-container').is(':visible')))
			{
				e.preventDefault();
				switch(e.keyCode)
				{
					case 38: // up
						nnsuggestMarkPrev();
					break;
					case 40: // down
						nnsuggestMarkNext();
					break;
				}
			}
			else if((/^27$|^13$|^9$/.test(e.keyCode) && $('div.nnsuggest-container').is(':visible') && $('ul.nnsuggest-list').children('.selected').text() != ''))
			{
				e.preventDefault();
				switch(e.keyCode)
				{
					case 9: // tab
					case 13: // return
						nnsuggestGetCurrentSelection(obj);
					break;
					case 27: // escape
						$('div.nnsuggest-container').hide();
					break;
				}
			}
		});

		$(this).keyup(function(e)
		{
			var obj = $(this);
			if ((/^27$|^38$|^40$|^13$|^9$/.test(e.keyCode)))
			{
				return false;
			}
			else
			{
				var $aSearchStrings = obj.val().split(','); // get all strings as list
				var $sSearchString = trim($aSearchStrings.pop()); // get last string in list
				if($sSearchString.length > 0)
				{
					if(obj.data('aAvailableSuggestions') === undefined)
					{
						if(options.protocol == 'inline')
						{
							obj.data('aAvailableSuggestions', $(options.source).text().split(','));
						}
					}

					var $sResultList = '';
					for(var i in obj.data('aAvailableSuggestions'))
					{

					    if(obj.data('aAvailableSuggestions')[i].toLowerCase().search($sSearchString.toLowerCase()) > -1)
					    {
					    	$sResultList += '<li>' + obj.data('aAvailableSuggestions')[i] + '</li>';
					    }
					}

					if($sResultList.length > 0)
					{
						$('div.nnsuggest-container').html('<ul class="nnsuggest-list">' + $sResultList + '</ul>');
						$('div.nnsuggest-container').show();
						$('ul.nnsuggest-list li').bind('click', function ()
						{
							nnsuggestApply($(this), obj);
						});
					}
					else
					{
						$('div.nnsuggest-container').hide();
					}
				}
				else
				{
					$('div.nnsuggest-container').hide();
				}
			}
		});
	});
};
})(jQuery);

function nnsuggestGetSelected()
	{
		if(!$('div.nnsuggest-container').is(':visible'))
		{
			return false;
		}
		var $currentResult = $('ul.nnsuggest-list').children('li.selected');
		if (!$currentResult.length)
		{
			$currentResult = false;
		}
		return $currentResult;
	}

	function nnsuggestGetCurrentSelection(obj)
	{
		$oSelected = nnsuggestGetSelected();
		if($oSelected)
		{
			nnsuggestApply($oSelected, obj);
		}
	}

	function nnsuggestMarkNext()
	{
		$currentResult = nnsuggestGetSelected();
		if ($currentResult)
		{
			$currentResult.removeClass('selected').next().addClass('selected');
		}
		else
		{
			$('ul.nnsuggest-list').children('li:first-child').addClass('selected');
		}
	}

	function nnsuggestMarkPrev()
	{
		$currentResult = nnsuggestGetSelected();
		if ($currentResult)
		{
			$currentResult.removeClass('selected').prev().addClass('selected');
		}
		else
		{
			$('ul.nnsuggest-list').children('li:last-child').addClass('selected');
		}
	}

	function nnsuggestApply(selected, obj)
	{
		var $aTags = obj.val().split(',');
		$aTags.pop();
		$aTags.push(trim(selected.text()));
		obj.val($aTags);
		obj.focus();
		moveCaretTo(obj, obj.val().length);
		$('div.nnsuggest-container').hide();
	}

/*### nnsuggest end ###*/


function parsePictureID($a_sPictureID)
{
	var $sPictureID = -1;
	if($a_sPictureID !== undefined)
	{
		$sPictureID = $a_sPictureID.substr(4);
	}
	return $sPictureID;
}

/**
* Move the caret to any position with in the object (an input or a textarea)
*/
function moveCaretTo(a_oObject, a_iPosition)
{
	if(a_oObject.createTextRange) // IE
	{
		var oRange = a_oObject.createTextRange();
		oRange.move('character', a_iPosition);
		oRange.select();
	}
	else if(a_oObject.setSelectionRange)
	{
		a_oObject.focus();
		a_oObject.setSelectionRange(a_iPosition, a_iPosition);
	}
}

function isAjaxResponseOk($a_sResponse)
{
	if($a_sResponse == '')
	{
		return false;
	}
	return true;
}

function trim(str, chars) {
    if(str === undefined || str == '')
    {
    	return '';
    }
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}