/*
Module: PageLoader
Downloads and injects HTML into specified selector. Also downloads all appropriate scripts and css files.

Requires: jQuery, using.js

Author:
Alexandr Smirnov (alex@regio.ee)
*/

function LoadPage(where, url, selector, callback) {
	callback = callback || function(){};

	// Default to a GET request
	var type = "GET";
	
	var self = jQuery(where);
	
	var onReady = []; // array of functions to be executed on template loaded
	
	function done() {
		for(var i=0; i<onReady.length; i++) {
			using.injectScript(onReady[i].body, onReady[i].n);
		};
		callback();
	}
	
	// Request the remote document
	var ajax = jQuery.ajax({
		url: url+(_AVOID_CACHE ? (((url.indexOf("?") >= 0) ? "&" : "?")+"_="+Math.random()) : ""),
		type: type,
		dataType: "html",
		complete: function(res, status){
			if ( status == "success" || status == "notmodified" ) {
				var contents = res.responseText;
				var script = contents.match(RegExp(/<script(.|\s)*?\/script>/ig));
				var css = contents.match(RegExp(/<link[^>]*?rel=[\'\"]{0,1}stylesheet[^>]*?>/ig));
				
				// inject the contents of the document in, removing the scripts
				// to avoid any 'Permission Denied' errors in IE
				contents = contents.replace(/<script(.|\s)*?\/script>/ig, "");
				contents = contents.replace(/<link[^>]*?rel=[\'\"]{0,1}stylesheet[^>]*?>/ig, "");
				
				// See if a selector was specified
				if(selector) {
					// Create a dummy div to hold the results
					self.html(jQuery("<div/>").append(contents).find(selector)/*.children()*/);
				} else {
					// If not, just inject the full result
					self.html(contents);
				};
				
				// inject all css'es
				$(css).each(function() {
					var s = (''+this);
					s = s.replace(/\.\.\//g, ''); // HACK: because the are in "templates" subfolder
					$('head').append($(s));
				});
				
				var use = [];
				$(script).each(function() {
					var src = (''+this).match(/<script.*?src\=[\"\']{0,1}(.*?)[\"\']{0,1}>/);
					if (src && src.length > 1) {
						// collect external scripts and feed them to "using.js" later
						var nameOnly = ('/'+src[1]).match(/(.*)[\/\\]([^\/\\]+)\.\w+$/);
						use.push(nameOnly[2]);
					} else {
						// get inline scripts
						var body = (''+this).match(/<script[^>]*>([\S\s]*?)<\/script>/i);
						if(body && body.length > 1) {
							onReady.push({ body: body[1], n: "inline for "+where+" from "+url });
						}
					}
				});
				
				// if there are any external scripts, then execute callback only when all of them loads
				if(use.length > 0) {
					using(use, function() { done() });
				} else {
					done();
				}
			}
		}
	});
	
	return ajax;
}
