
// Create the sidecar and subordinate objects.
var sidecar = sidecar || {};
sidecar.preboot = sidecar.preboot || { urlroot: "http://www.getsidecar.com", asset_url: "https://getsidecar.s3.amazonaws.com" };
if (sidecar.preboot.asset_url == undefined) {
	sidecar.preboot.asset_url = "https://getsidecar.s3.amazonaws.com";
}

sidecar.boot = {
	// Timeout pointer.
	to: null,
	// Number of attempts to determine jquery loaded state.
	load_tries: 0,
	// Maximum number of tries.
	max_tries: 60,
	// Wait milliseconds.
	wait_time: 100,
	// Acceptable jquery librarys.
	ok_libs: new Array("1.5.1", "1.5", "1.4.5", "1.4.4", "1.4.3", "1.4.2", "1.4.1"),
	// Looping check to see if jquery has loaded. Interval is .10 secs.
	date_str: "v=" + (new Date).getTime(),
	date_qry: (sidecar.preboot.asset_url == "https://getsidecar.s3.amazonaws.com") ? "" : "?v=" + (new Date).getTime(),
	date_amp: (sidecar.preboot.asset_url == "https://getsidecar.s3.amazonaws.com") ? "" : "&v=" + (new Date).getTime(),
	waitForLoad: function() {
		if (++sidecar.boot.load_tries <= sidecar.boot.max_tries) {
			// If we exceed 1 sec waiting for jquery, add a tenth of a sec with each next try so we don't hinder page access.
			sidecar.boot.wait_time = (sidecar.boot.load_tries <= 10) ? sidecar.boot.wait_time : (sidecar.boot.load_tries * 10);
			if (typeof jQuery == "undefined") {
				sidecar.boot.to = window.setTimeout(sidecar.boot.waitForLoad, sidecar.boot.wait_time);
				return false;
			}
			// Check if jquery is version we requested. True indicates successful load.
			if (jQuery.fn.jquery != "1.4.2") {
				sidecar.boot.to = window.setTimeout(sidecar.boot.waitForLoad, sidecar.boot.wait_time);
				return false;
			} else {
				// jquery is loaded. Set to $$$. If old library exists, return it to $ namespace.
				$$$ = jQuery;
				sidecar.boot.releaseNamespaces();
				// Load sidecar.
				sidecar.boot.loadSidecar();
				return true;
			}
		} else {
			// Failed to load jquery. Nothing to do.
			return false;
		}
	},

	loadSidecar: function() {
		// jquery is ready under $$$. Start loading sidecar.
		if (typeof $$$ == 'undefined') { return; }

		/****************************
		* Last Minute jQuery Plugins
		****************************/
		// jQuery URL parser v.1.0
		// http://projects.allmarkedup.com/jquery_url_parser/
		$$$.url = function(){var segments={};var parsed={};var options={url:window.location,strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var parseUri=function(){str=decodeURI(options.url);var m=options.parser[options.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--){uri[options.key[i]]=m[i]||""}uri[options.q.name]={};uri[options.key[12]].replace(options.q.parser,function($0,$1,$2){if($1){uri[options.q.name][$1]=$2}});return uri};var key=function(key){if(!parsed.length){setUp()}if(key=="base"){if(parsed.port!==null&&parsed.port!==""){return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/"}else{return parsed.protocol+"://"+parsed.host+"/"}}return(parsed[key]==="")?null:parsed[key]};var param=function(item){if(!parsed.length){setUp()}return(parsed.queryKey[item]===null)?null:parsed.queryKey[item]};var setUp=function(){parsed=parseUri();getSegments()};var getSegments=function(){var p=parsed.path;segments=[];segments=parsed.path.length==1?{}:(p.charAt(p.length-1)=="/"?p.substring(1,p.length-1):path=p.substring(1)).split("/")};return{setMode:function(mode){strictMode=mode=="strict"?true:false;return this},setUrl:function(newUri){options.url=newUri===undefined?window.location:newUri;setUp();return this},segment:function(pos){if(!parsed.length){setUp()}if(pos===undefined){return segments.length}return(segments[pos]===""||segments[pos]===undefined)?null:segments[pos]},attr:key,param:param}}();
		// Add an indexOf method because IE doesn't support it.
		$$$.indexOf = function(t,o){for (var i = 0, len = t.length; i < len; i++){if(t[i] === o) return i;}return -1;}
		this.loadScript(sidecar.preboot.asset_url + "/js/jquery-ui.js");
		//this.loadCSS(sidecar.preboot.asset_url + "/css/jquery-ui.css" + sidecar.boot.date_qry);
		//var domain = document.domain;
		var domain = $$$.url.setUrl().attr("host");
		this.loadScript(sidecar.preboot.urlroot  + "/sidecar/?service=site_config&domain=" + domain + "&" + sidecar.boot.date_str);
	},

	checkJquery: function() {
		if (top.location != self.location) { return; }

		sidecar.preboot.urlroot = sidecar.preboot.urlroot.replace("http:", document.location.protocol);
		if (typeof jQuery == "undefined") {
			sidecar.boot.protectNamespaces();
			this.loadScript(sidecar.preboot.asset_url + "/js/jquery.tools.full.js" + sidecar.boot.date_qry);
			sidecar.boot.waitForLoad();
			return false;
		}
		// Check for jquery and load if necessary.
		if (jQuery != undefined && jQuery.fn.jquery != undefined && jQuery.inArray(jQuery.fn.jquery, sidecar.boot.ok_libs) != -1) {
			// jquery already loaded and acceptable version. Use it under $$$ namespace.
			$$$ = jQuery;
			this.loadScript(sidecar.preboot.asset_url + "/js/jquery.tools.min.js" + sidecar.boot.date_qry);
			sidecar.boot.loadSidecar();
		} else {
			sidecar.boot.protectNamespaces();
			this.loadScript(sidecar.preboot.asset_url + "/js/jquery.tools.full.js" + sidecar.boot.date_qry);
			sidecar.boot.waitForLoad();
		}
	},
	
	protectNamespaces: function() {
		sidecar.$ = (typeof $ != "undefined") ? $ : null;
		sidecar.j = (typeof jQuery != "undefined") ? jQuery : null;
	},

	releaseNamespaces: function() {
		if (typeof sidecar.$ != "undefined") {
			$ = sidecar.$;
			delete sidecar.$;
		}
		if (typeof sidecar.j != "undefined") {
			jQuery = sidecar.j;
			delete sidecar.j;
		}
	},

	loadScript: function(src) {
		var script = document.createElement("script");
		script.setAttribute("src", src);
		script.setAttribute("type", "text/javascript");
		var head = document.getElementsByTagName("head")[0] || document.documentElement;
		head.insertBefore(script, head.firstChild);
	},
	
	loadCSS: function(src) {
		var css = document.createElement("link");
		css.setAttribute("rel", "stylesheet");
		css.setAttribute("href", src);
		css.setAttribute("type", "text/css");
		var head = document.getElementsByTagName("head")[0] || document.documentElement;
		head.insertBefore(css, head.firstChild);
	},
	
	blend: function(txt) {
		var hex="";
		for (i=0; i < txt.length; i++) {
			hex += txt.charCodeAt(i).toString(16);
		}
		return hex;
	}
};

sidecar.boot.checkJquery();

