(function($){
	$.fn.extend({
		LazyLoad: function(opt) {
			if (opt === "load") {
				var obj = this.ParseClass(),
				url = getURL(obj),
				_this = this;
				if (!url && window.console && console.error) {
					console.error("No URL provided for LazyLoad", ele);
				}
				_this.trigger("throb");
				$.get(url, function(data) {
					_this.trigger("unthrob");
					//inject the current HTML into the bottom of the page for use later
					$('<div></div>').css("display","none").append(_this.children()).appendTo(document.body);
					
					_this.html(data);
					// Do all the HTML updates
					_this.find("span.placeholder").each(function() {
						var $this = $(this);
						try {
							var data=eval("("+$this.html()+")");
						} catch(e) {
							if (window.console && console.error) {
								console.error("Error in the JSON string!", this);
							}
							return;
						}
						if (!data || !data.containerSelector) {
							return;
						}
						var cont = $(data.containerSelector);
						if (cont.length == 0) {
							return;
						}
						
						$this.replaceWith(cont);
						if (data.updateEles) {
							for(var i=0, eleObj; eleObj = data.updateEles[i]; i++) {
								var ele = $(eleObj.selector);
								if (typeof(eleObj.html) !== "undefined") {
									ele.html(eleObj.html);
								}
								if (typeof(eleObj.options) !== "undefined") {
									var opts = [];
									for(var j=0, opt; opt=eleObj.options[j]; j++) {
										opts.push('<option value="' + opt.value + '">' + opt.html + '</option>');
									}
									ele.html(opts.join(""));
								}
								if (typeof(eleObj.value) !== "undefined") {
									ele.val(eleObj.value);
								}
								if (typeof(eleObj.checked) !== "undefined") {
									ele.attr("checked", eleObj.checked);
								}
							}
						}
					});
					// Initialize datatables
					$.dataTable.init();
					// Initialize tabs
					$.tabs.init();
					// Initialize datepickers
					$.datepicker.init();
					// Initialize lazyloader (Recursive lazyloading? Love it!)
					$.LazyLoad.init();
				});
				return;
			}
			var $this = this.not(function() {
				return $.data(this, "lazyloadinit");
			}).data("lazyloadinit", true).each(function() {
				var $this = $(this),
				obj = $this.ParseClass();
				if (!obj.preLoaded) {
					$this.LazyLoad('load');
				}
				var ele = $(obj.lazyLoadURL);
				if (ele.length > 0) {
					ele.change(function() {
						$this.LazyLoad('load');
					});
				}
			});
			return this;
		}
	});
	//helper functions
	var getURL = function(obj) {
		if (!obj || !obj.lazyLoadURL) {
			return false;
		}
		var ele = $(obj.lazyLoadURL);
		if (ele.length > 0) {
			return ele.val() || getURL(ele.ParseClass());
		}
		return obj.lazyLoadURL;
	};
	$.LazyLoad = {
		init: function(sel) {
			$(sel || "div.lazyload").LazyLoad();
		}
	};
	$(function() {
		$.LazyLoad.init();
	});
})(jQuery);
