/**
 * Detect attribute changes with jQuery. 0.0.1a
 *
 * Idea and majority of code adopted from Darcy Clarke (darcyclarke.me)
 * and extended upon it to fit specific requirements.
 *
 * Author: Matthew Kingston <matthew@clickcreative.com.au>
 *         Copyright: 2011 © Click Creative Pty Ltd
 *
 * Usage:
 * <code>
 *     $(function($) {
 *         $(".demo").watch('width', function() {
 *             if(parseFloat($(this).width()) >= 150) {
 *                 $(this).css({'background': 'green'});
 *             }
 *         });
 *         
 *         $('.demo').delay(3000);
 *         $('.demo').queue(function() { $(this).css({'width':'400px'}); $(this).dequeue(); });
 *     });
 * </code>
 * 
 * http://darcyclarke.me/development/detect-attribute-changes-with-jquery/
 * http://darcyclarke.me/dev/watch/
 */
(function(window, $, undefined)
{
	
	$.watch = {
		
		/**
		 * The current version.
		 * @type String
		 */
		version: "0.0.1a",
		
		/**
		 * Storage for the interval timer
		 */
		interval: null
	}
	
	$.fn.watch = function(props, callback, timeout)
	{
		if(!timeout)
		{
			timeout = 10;
		}
		
		return this.each(function()
		{
			var el = $(this);
			var func = function()
			{
				__check.call(this, el)
			};
			
			var data = {
				props: props.split(","),
				func: callback,
				vals: []
			};
			
			$.each(data.props, function(i)
			{
				data.vals[i] = el.css(data.props[i]);
			});
			
			el.data(data);
			
			if((typeof(this.onpropertychange) == "object") || ($.browser.mozilla))
			{
				el.bind("DOMAttrModified", callback);
			}
			else
			{
				$.watch.interval = setInterval(func, timeout);
			}
		});
		
		function __check(el)
		{
			var data = el.data();
			var changed = false;
			var temp = "";
			
			for(var i = 0; i < data.props.length; i++)
			{
				temp = (!el.css(data.props[i]) ? el.attr(data.props[i]) : el.css(data.props[i]));
				
				if(data.vals[i] != temp)
				{
					data.vals[i] = temp;
					changed = true;
					break;
				}
			}
			
			if(changed && data.func)
			{
				data.func.call(el, data);
			}
		}
	}
	
	
	$.fn.unwatch = function()
	{
		var el = $(this);
		
		el.removeData('props');
		el.removeData('func');
		el.removeData('vals');
		
		if((typeof(this.onpropertychange) == "object") || ($.browser.mozilla))
		{
			el.unbind("DOMAttrModified");
		}
		else
		{
			clearInterval($.watch.interval);
		}
	}
	
	
})(window, jQuery);
