/**
 * Matthew Eagar <meagar@gmail.com>
 */
(function($) {

	/**
	 * Snaps an element to it's parent container
	 */
	$.fn.snap_to_parent = function() {
		/*options = jQuery.extend(
			{ width  : 500
			, height : 500
			}, options);*/
	
		$(this).each(function(i, element) {

			var x = parseInt($(element).css("left"));

			if (x <=  0) {
				$(element).css("left", 0);
			} else {
				var w = parseInt($(element).width());
				var pw = parseInt($(element).parent().width());
				if (x + w > pw)
					$(element).css("left", pw - w);
			}

			var y = parseInt($(element).css("top"));
			if (y <= 0) {
				$(element).css("top", 0);
			} else {
				var h = parseInt($(element).height());
				var ph = parseInt($(element).parent().height());
				if (y + h > ph)
					$(element).css("top", ph - h);
			}
		});
	}

})(jQuery);

jQuery.utils = {

	/**
	 * Add commas to a number to denote thousands
	 * ie 12345678.912345=> 12,345,678.912345
	 * TODO = comma-seperate stuff after decimal??
	 * @return string
	 */
	add_commas : function(num) {
		var parts = num.toString().split('.');
		i = parts[0];

		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(i))
			i = i.replace(rgx, '$1,$2');

		return i + (parts.length > 1 ? ('.' + parts[1]) : '')
	},

	timestamp : function() {
		return parseInt((new Date().getTime()) / 1000);
	},

	/**
	 * Format a number as a currency value
	 * @param mixed value A number to format as a currency
	 * @return string The value formatted as a currency : $123.456.78
	 */
	format_currency : function(value) {
		value = (value.toFixed(2)).toString();
		return '$' + jQuery.utils.add_commas(value);
	},

	is_numeric : function(n) {
		return !isNaN(parseFloat(n)) && isFinite(n);
	}
	
}; // jQuery.util;

// Function for dealing with highslide windows (from within highslide windows)
jQuery.utils.hs = {

	/**
	 * Return the parent's Highslide instance, or null
	 */
	instance : function() {
		if (parent != undefined
		&&  parent.window != undefined
		&&  parent.window.hs != undefined
		&&  parent.window.hs.getExpander() != undefined)
			return parent.window.hs;
		return null;
	},
	/**
	 * Close the highslide window from within the highslide window
	 */
	close : function(returnValue) {
		instance = jQuery.utils.hs.instance();
		if (!instance) return false;

		instance.returnValue = returnValue;
		instance.getExpander().close();
		return false;
	} ,
	/**
	 * Reflow the highslide window from within the highslide window
	 */
	reflow : function() {
		instance = jQuery.utils.hs.instance();
		if (!instance) return false;

		instance.getExpander().reflow();
	}

}; // jQuery.utils.hs

