/*
 * jQuery watcher plugin
 * Example: jQuery.estilo.tools.watcher.watch(window.location, "href", function(){ alert("Address have been changed"); });
 *
 * Copyright (c) 2009 Arnolds Verins
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

(function(jQuery) {
	function EstiloWatcher(){
		this.intV = null;
		this.targets_to_watch = new Array();
	};
	
	jQuery.extend(EstiloWatcher.prototype, {
		watch: function(target, attribute, callback) {
			try{
				var scope = this;
				var exists = false;
				for(var i=0; i<this.targets_to_watch.length; i++){
					if(target == this.targets_to_watch[i].target && this.targets_to_watch[i].attribute == attribute){
						exists = true;
						this.targets_to_watch[i].oldValue = null;
						break;
					}
				}
				if(!exists){
					var obj = new Object();
					obj.target = target;
					obj.callback = callback;
					obj.oldValue = null;
					obj.attribute = attribute;
					this.targets_to_watch.push(obj);
				}
				if(this.intV == null){
					this.intV = setInterval(function(){
						scope._docheck()
					}, 50);
				}
			}catch(ex){
				alert("Error in Estilo.watch: "+ex);	
			}
		},
		unwatch: function(target, attribute){
			try{
				var exists = false;
				for(var i=0; i<this.targets_to_watch.length; i++){
					if(target == this.targets_to_watch[i] && this.targets_to_watch[i].attribute == attribute){
						this.targets_to_watch.splice(i, 1);
					}
				}
			}catch(ex){
				alert("Error in Estilo.unwatch: "+ex);	
			}
		},	
		_docheck: function() {
			try{
				for(var i=0; i<this.targets_to_watch.length; i++){
					var obj = this.targets_to_watch[i];
					if(obj != undefined && obj.target != undefined && this._attribute_exists(obj.target, obj.attribute)){
						try{
							if(obj.target[obj.attribute] != obj.oldValue){
								obj.callback(obj.oldValue, obj.target[obj.attribute]);	
							}
							obj.oldValue = obj.target[obj.attribute];
							this.targets_to_watch[i] = obj;
						}catch(ex){}
					}
				}
			}catch(ex){
				// Probably crash because the object does'nt exist
				//alert("Error in Estilo._docheck: "+ex);	
			}
		},
		_attribute_exists: function(target, attribute){
			for(var name in target)
				if(name == attribute) return true;	
			return false;
		}
	});
	
	jQuery(document).ready(function() {
		if(jQuery.estilo == undefined)
			jQuery.estilo = new Object();	
		if(jQuery.estilo.tools == undefined)
			jQuery.estilo.tools = new Object();	
			
		jQuery.estilo.tools.watcher = new EstiloWatcher(); // singleton instance
	});
})(jQuery);
