/***
 * Extensions for ajax queuing and anchor wiring
 ***/
 	sVil.extend("wireLinks", function(div) {		// Wire links to custom handler
 			if (!div) target = "a";
 			else target = div + " a";
 			$(target).bind("click", sVil.ajaxClickHandler);
 		});
/***
 * Links to most local files load only the main content into the my_content div using ajax/jQuery
 *	 Follows external links or those with class="follow"
 ***/
	sVil.extend("ajaxClickHandler", function() {	
		if ((location.host != this.host) || (this.className == "popup") || (this.className == "follow")) return true;
		sVil.ajaxQueue({
			originator: this,
			url: this.href,
			cache: false,
			success: function(htm){
			    $("#my_content").html(htm);
			 		sVil.wireLinks("#my_content");			//  Wire links before wiring e-mails
				$("#my_content span.contactron").html(sVil.createRonContact ());
				$("#my_content span.contactarmin").html(sVil.createArminContact ());
				$("#my_content a.popup").each(function (i) { sVil.bindPopup(this); });
			},
			error: function(xml, msg, thrown, originator) {
				alert(msg + " on loading " + originator);
				originator.blur();
			}
		});

		return false;
	});
 /***
  * Queue ajax requests so that we single thread. Take (possible) performance hit for browser robustness
  ***/
   	sVil.extend("ajaxQueue", (function(jQuery) {	// Create closure for queue handling
  			var queue = [];
  			var busy = false;
  			
  			function addToQ (ajaxObj) {
  				queue.push(ajaxObj);
  				if (busy) return;
  				executeNext()
  			}
  			function executeNext() {
   				if (queue.length==0 || busy) return;
  				busy = true;
  				var activeObj = queue.shift();
   				jQuery.ajax({
  					originator : activeObj.originator ? activeObj.originator : null,
  					activeSuccess : activeObj.success,
  					activeError : activeObj.error ? activeObj.error : null,
  					url : activeObj.url,
  					cache : activeObj.cache,
  					success : function (htm) {
  						this.activeSuccess(htm);
  						busy = false;
  						executeNext();
  					},
  					error : function (XMLHttpRequest, textStatus, errorThrown) {
  						busy = false;
 						if (this.activeError) this.activeError(XMLHttpRequest, textStatus, errorThrown, this.originator);
  						executeNext();
 					}  					
  				}); 					
  			}
  			return addToQ;
 		})(jQuery));
/***
 * Wraps ajaxQueue for simple load requests ala jQuery().load()
 ***/	
	sVil.extend("ajaxLoad", function(selector, url, callback) {
		if (arguments.length < 3)
			sVil.ajaxQueue({
					url : url,
					cache : false,
					success : function (htm) { $(selector).html(htm); }
				});
		else
			sVil.ajaxQueue({
					url : url,
					cache : false,
					success : function (htm) { callback($(selector).html(htm)); }
				});
		
	});
