$(document).ready(function() {

    // Replace non-word characters with hyphens in slug as you type title
    $('form#addLink input#title').keyup(function() {

       var title = $('form#addLink input#title').val();
       var slug = title.replace(/[^A-Za-z0-9]/g, "-");

       $('form#addLink input#slug').val(slug);
    });

    // Confirm delete on removing link
    $('form#removeLink, form#removeCat').submit(function() {
       var answer = confirm("Are you sure you want to do this? \n** THIS CANNOT BE UNDONE! **");
       if(!answer)
       {
           return false;
       }
    });
});

var SPINNER = {

	/**
	* Replaces the supplied jQuery object with a spinner image
	*/
	replaceWithSpinner: function (obj)
	{
		var spinnerHtml = '<div class="spinner"><img src="/images/ajax-loader.gif" width="16" height="16" alt="Loading" /></div>';
		obj.replaceWith(spinnerHtml);
	}
}

/**
* Generic JavaScript helpers
*/
var RLM = {

	/**
	* Get the number of elements in an array/object
	*/
	objSize: function(obj) {
		var size = 0, key;
		for (key in obj) {
			if(obj.hasOwnProperty(key)) size++;
		}
		return size;
	},

	/**
	* Get date that is specified # of days in the future
	*
	* @param Date startObj Date object representing start date
	* @param int daysInFuture Number of days in the future to use to calculate the new date
	*/
	futureDate: function(startObj, daysInFuture) {
		var date = new Date(startObj);
		date.setDate(date.getDate() + daysInFuture + 1);
		return date;
	},

	/**
	* Format currency
	*/
	formatCurrency: function(num)
	{
		num = isNaN(num) || num === '' || num === null ? 0.00 : num;
		return parseFloat(num) > 0 ? '$' + parseFloat(num).toFixed(2) : '($' + parseFloat(Math.abs(num)).toFixed(2) + ')';
	},

	/**
	* Checks if object is an array
	*
	* @returns True if array, false, otherwise
	*/
	isArray: function(obj)
	{
		return typeof(obj) == 'object' && (obj instanceof Array);
	},

	ucwords: function (str)
	{
	    // http://kevin.vanzonneveld.net
	    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	    // +   improved by: Waldo Malqui Silva
	    // +   bugfixed by: Onno Marsman
	    // +   improved by: Robin
	    // +      input by: James (http://www.james-bell.co.uk/)
	    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // *     example 1: ucwords('kevin van  zonneveld');
	    // *     returns 1: 'Kevin Van  Zonneveld'
	    // *     example 2: ucwords('HELLO WORLD');
	    // *     returns 2: 'HELLO WORLD'

	    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
	        return $1.toUpperCase();
	    });
	},

	/**
	* Returns true if provided variable is null, false otherwise
	*/
	isNull: function ( variable )
	{
		if ( typeof variable == 'undefined' )
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}

var MSG = {

	showGenericJsMsg: function (cssClass, message, timeout)
	{
		// set class
		$('#genericMessageInner').addClass(cssClass);
		// set header
		$('#genericMessage h1').html(RLM.ucwords(cssClass));
		// set message
		$('#genericMessageContent').html(message);
		// position message so it's visible
		//var top = $(window).scrollTop();
		//$('#genericMessage').css('top', top);
		// slide in
		$('#genericMessage').slideDown();

		// slide out after "timeout" seconds
		var timeout = parseInt(timeout) * 1000;
		setTimeout('MSG.hideGenericJsMsg()', timeout);
	},

	hideGenericJsMsg: function ()
	{
		$('#genericMessage').slideUp();
	}
}

var ERRORS = {

    /**
     * Displays an error message.
     *
     * @param XMLHttpRequestObject XmlObj The full response from the server
     * @param bool showMessage If true, the server response will be logged to the console for debugging.
     */
	handleError: function( XmlObj, showMessage )
	{
		if(RLM.isNull(showMessage))
		{
			alert("There was an unkown error\nStatus code: " + XmlObj.status);
		}
		else if (!RLM.isNull(showMessage) && showMessage == true)
		{
			alert("There was an unknown error\nSee console for response");
			console.log(XmlObj.responseText);
		}
	}
}
