function resolveIncludes(codeString,includeTable){
	try{
		var findincludes=/\$\.include\s*\(\s*["'](.*?)["']\s*\)\s*\;/g;
		var change=false;
		
		
		codeString=codeString.replace(findincludes,function(fullMatch,partialMatch1){
			if(typeof(includeTable[partialMatch1])!="function") return "";
			
			change=true;
			return "$."+partialMatch1+"="+includeTable[partialMatch1].toString()+";";
		});
		
		
		return [codeString,change];
	}catch(e){alert("resolveIncludes "+e.description);}
}

function randomString(len){
	try{
		var out="";
		for(var i=0;i<len;i++){
			var n=Math.floor(Math.random()*62);
			if(n<10) out+=String.fromCharCode(("0").charCodeAt(0)+n);
			else if(n<36) out+=String.fromCharCode(("a").charCodeAt(0)+n-10);
			else out+=String.fromCharCode(("A").charCodeAt(0)+n-36);
		}
		return out;
	}catch(e){alert("randomString "+e.description);}
}

$.addEventListener(window,"load",function(evt){new $.HttpRequest("bookmarklets.xml",main); });

function main(response){
	try{
		var bookmarklets=$.xmlToJs(response.responseXML).bookmarklets;
		var anchors=$.getElementsByClass("a","bookmarklet-anchor");
		var e=function(str){return encodeURIComponent(str).replace('"',"%22").replace("'","%27")};
		for(var i=0;i<anchors.length;i++){
			var name=anchors[i].textContent;
			var escName=anchors[i].getAttribute("alt");
			if(bookmarklets[escName]){
				var title=bookmarklets[escName].title.textContent;
				var icon=bookmarklets[escName].icon.textContent;
				var code=bookmarklets[escName].code.textContent;
				var ident=randomString(4);
				var resolveResult=resolveIncludes(code,$);
				var code=resolveResult[0];
				var hasIncludes=resolveResult[1];
				if(hasIncludes) code="var $={};"+code;
				
				
				var bm=("javascript:if(window.__XBM"+ident+")eval(window.__XBM"+ident+");else("+$.removeNonLiteralWhitespaces((new Function(code)).toString().replace(/\n/g," ").replace(/anonymous/,""))+")();");
				
				anchors[i].onmousedown=$.silenceEvt;
				anchors[i].onclick=$.fixScope(function(evt){
					var data="({p:\\'"+e((/^(.*)\//).exec(document.location)[0])+"\\',t:\\'"+e(this.d.title.textContent)+"\\',d:\\'"+e(this.d.desc.textContent)+"\\',i:\\'"+e(this.d.icon.textContent)+"\\',n:\\'"+e(this.d.name.textContent)+"\\',a:\\'"+e(this.d.author.textContent)+"\\'});";
					window["__XBM"+this.i]="'<html><head><title></title><script>__XBM=eval(\""+data+"\");</script><script src=\""+(/^(.*)\//).exec(document.location)[0]+"src/infoscreen.js\"></script></head></html>';";
					document.location=this.v;
					$.silenceEvt(evt);
				},{v:bm,d:bookmarklets[escName],i:ident});
				anchors[i].href="bookmarklet://"+bookmarklets[escName].name.textContent;
				anchors[i].innerHTML="<img src=\""+bookmarklets[escName].icon.textContent+"\" /> "+bookmarklets[escName].name.textContent;
			}
		}
	}catch(e){alert("main "+e.description);}
}
