var addthis_pub = "developit";
window.JMDWiki_HTTP_HOST = "jasonmillerdesign.com";

window.Sitemappr_oldDOM = window.onDOM ? window.onDOM : function(){};
window.onDOM = function() {
	/*
	if(Sitemappr.loaded!=true)
		Sitemappr.Load();
	*/
	Sitemappr_oldDOM();
};

window.Sitemappr_oldload = window.onload ? window.onload : function(){};
window.onload = function() {
	if(Sitemappr.loaded!=true)
		Sitemappr.Load();
	Sitemappr_oldload();
	window.setTimeout("Scrollable.init();",10);
};

window.Sitemappr = (function(){
	var _data = {};
	var HttpRequest = {
		"create"	: function(url,postdata,oncomplete,onerror,autoDelete){ return new this._obj(this,url,postdata,oncomplete,onerror,autoDelete); },
		"stop"		: function(request){ if(request&&request.type=="request") request.abort(); },
		"init"		: function(request,url){ if(request&&request.type=="request"){ request.get(url); } },
		"close"		: function(request){
			if(!request||request.type!="request")
				return false;
			try{ request.abort(); }catch(err){}
		},
		"_obj"		: function(parent,url,postdata,oncomplete,onerror,autoDelete) {
			this.type = "request";
			this.parent = parent;
			this.__index = parent._requests.length;
			this.url = url;
			this.postdata = (postdata && postdata.constructor && (postdata.constructor==Object || postdata.constructor==Function)) ? postdata : {};
			this.poststring = (postdata && typeof(postdata)==String) ? postdata : "";
			this.autoDelete = autoDelete!==false;
			this.data = null;
			this.async = true;
			this.http_code = null;
			this.status = null;
			this.responseText = null;
			this.responseXML = null;
			this.complete = false;
			this.oncomplete = oncomplete?oncomplete:function(){};
			this.onerror = onerror?onerror:function(){};
			this.request = this.parent.XMLHttpRequestObj();
			this.request.parent = this;
			this.request.onreadystatechange = function() {
				try {
					this.parent.readyState = this.readyState;
					if(this.responseText!=null && this.responseText!="undefined") {
						this.parent.responseText = this.responseText;
						this.parent.data = this.responseText;
					}
					if(this.responseXML!=null && this.responseXML!="undefined")
						this.responseXML = this.responseXML;
				} catch(e){}
				try {
					this.parent.status = this.status;
					this.parent.http_code = this.status;
				}catch(e){}
				if(this.readyState==4) {
					this.parent.complete = true;
					this.parent.error = this.status!=200;
					if(this.status==200 && this.parent.oncomplete)
						try{ this.parent.oncomplete(); }catch(err){ window.setTimeout("throw(\"request.oncomplete > "+err.message+"\");",1); }
					else if(this.status!=200 && this.parent.onerror)
						try{ this.parent.onerror(); }catch(err){ window.setTimeout("throw(\"request.oncomplete > "+err.message+"\");",1); }
					if(this.parent.autoDelete==true) {
						this.parent.parent.close(this);
					}
				}
			};
			this.get = function(url){
				if(url!=null && url==url+"" && url.length>0)
					this.url = url;
				
				var requrl = this.url;
				
				this._poststring = this.poststring?this.poststring:"";
				for(var x in this.postdata)
					this._poststring += "&" + encodeURIComponent(x) + "=" + encodeURIComponent(this.postdata[x]);
				if(this._poststring.indexOf("&")==0)
					this._poststring = this._poststring.substring(1,this._poststring.length);
				this.request.open(this._poststring.length>2?"POST":"GET", requrl, this.async);
				this.request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				try {
					this.request.setRequestHeader("Content-length", this._poststring.length);
					this.request.setRequestHeader("Connection", "close");
				}catch(e){}
				this.request.send(this._poststring.length>2?this._poststring:null);
				return this;
			};
			this.send = this.get;
			this.Send = this.get;
			this.Get = this.get;
			this.abort = function(){
				if(this.readyState!=4) {
					this._oldOnError = this.onerror;
					this.onerror = function(){};
					this.request.abort();
					this.onerror = this._oldOnError;
					try{ delete this._oldOnError; }catch(e){ this._oldOnError=null; }
				}
				try{ delete this.parent._requests[this.__index]; }catch(e){}
				this.parent._requests.splice(this.__index,1);
				this.parent._delete(this);
				return null;
			};
			this.Abort = this.abort;
			this.cancel = this.abort;
			this.Cancel = this.abort;
			this.stop = this.abort;
			this.Stop = this.abort;
			this.parent._requests.push(this);
		},
		"XMLHttpRequestObj" : function() {
			var xmlHttp=null;
			try { xmlHttp=new XMLHttpRequest(); }
			catch (e) {
				try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
				catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
			}
			return xmlHttp;
		},
		"_delete"	: function(t){try{delete t;}catch(e){t=null;}},
		"_requests" : []
	};
	HttpRequest.Create	= HttpRequest.create;
	HttpRequest.Stop	= HttpRequest.stop;
	HttpRequest.Abort	= HttpRequest.stop;
	HttpRequest.Destroy	= HttpRequest.close;
	HttpRequest.Init	= HttpRequest.init;
	
	function XDR(url,onload,context,useProxy) {
		// Keep a counter for the number of scripts (prevents overwriting if random numbers are the same)
		if(window._scriptCount==null)
			window._scriptCount = 0;
		window._scriptCount++;
		
		// Give the connection a unique ID
		var cid = window._scriptCount + Math.floor(Math.random()*99999999999);
		var callbackID = "XDRcallback" + cid;
		
		// The server needs this ID in order to call the dynamic callback function
		if(useProxy===false)
			var srcURL = url.replace(/\|\%callback\%\|/,callbackID);
		else
			var srcURL = prefs.proxy.url + (prefs.proxy.url.indexOf("?")>-1 ? "&" : "?") + prefs.proxy.callbackparam+"="+encodeURIComponent(callbackID) + "&"+prefs.proxy.urlparam+"="+encodeURIComponent(url);
		
		// Create a dynamic callback function for the script to call once loaded:
		window.XDRCallback = function(cid,callbackID,data) {
			// find this connection's script tag
			var script = null;
			var scripts = document.getElementsByTagName("script");
			for(var x=0; x<scripts.length; x++)
				if( scripts[x]._cid && scripts[x]._cid==cid )
					script = scripts[x];
			
			if(script==null)
				return false;	// script tag not found
			
			// Call the request's onload() handler
			script._onload.apply(script._context,[data]);
			
			// Remove the script tag
			script.parentNode.removeChild(script);
			
			eval("try{delete window."+callbackID+"; }catch(err){ window."+callbackID+"=null; }");
		};
		
		window.eval("window."+callbackID+"=function(data){window.XDRCallback("+cid+",'"+callbackID+"',data);};");
		
		// Create the script tag
		var script = document.createElement('script');
		script._onload = onload ? onload : function(){};
		script._context = context ? context : window;
		script._cid = cid;
		script.setAttribute("src",srcURL);
		script.setAttribute("type","text/javascript");
		if(navigator.userAgent.indexOf('Safari'))
			script.charset = 'utf-8';	// Safari bug
		document.getElementsByTagName('head')[0].appendChild(script);
		
		return script;
	}
	
	var JSON = {
		parse	: function(json) {
			if( json==null || json=="undefined" || (json.length && json.length<2) )
				return false;
			var window,document,top,location,self,body,head,html,createElement,appendChild,Application,ApplicationFramework,reload,href,Function;
			try {
				var obj = eval('('+json+')');
			} catch(err) {
				return false;
			}
			if( obj )
				return obj;
			else
				return false;
		}
	};
	
	var prefs = {
		proxy : {
			url	: "http://jasonmillerdesign.com/services/xmltojson/",
			urlparam : "url",
			callbackparam : "callback"
		},
		addthis : {
			url		:"http://jasonmillerdesign.com/apps/sitemappr/",
			title	: "Sitemappr, the Sitemap PageRank Checker"
		}
	};
	
	var txt = {
		title	: "<span style=\"position:relative;overflow:visible;\"><span style=\"color:#666;position:absolute;left:0;top:-1px;z-index:1;padding:0;margin:0;\">Sitemappr<\/span><span style=\"color:#EEE;position:absolute;left:0;top:1px;z-index:1;padding:0;margin:0;\">Sitemappr<\/span><span style=\"color:#D63;position:relative;z-index:2;\">Sitemappr<\/span><\/span>",
		explain : "Check the PageRank&trade; of every URL in a sitemap.<br />To get started, enter the URL of your sitemap.",
		ok		: "Ok",
		close	: "Close",
		open	: "Open",
		check	: "Check",
		start	: "Start",
		stop	: "Stop"
	};
	
	var self = {
		Load	: function() {
			this.loaded = true;
			window.setTimeout("document.getElementById('loading_indicator').style.display='none';", 200);
			
			ApplicationFramework.onglobalkeydown.push(function(keyCode) {
				if(keyCode==27)
					return false;
			});
			
			// create the application wrapper
			var app = new Application("Sitemappr");
			this.app = app;
			app.DisableMinimize();
			app.DisableMaximize();
			app.ToggleFullscreen();
			
			// create the controls
			app.titleDisplay = new app.Controls.Label(txt.title, "display:block; position:relative; border:none; padding:0; margin:5px 5px 0; font-size:200%; text-align:center;");
			app.Controls.Add(app.titleDisplay);
			
			app.explain = new app.Controls.Label(txt.explain, "display:block; position:relative; border:none; padding:5px 0; margin:0; text-align:center;");
			app.Controls.Add(app.explain);
			
			app.sitemapURI = new app.Controls.TextInput("http://","display:block; position:relative; font-size:110%; padding:2px 1px; font-weight:bold; margin:0 0 0 10px;",1);
			app.sitemapURI.onkeypress.push(function(e,control) {
				var key = e.keyCode?e.keyCode:e.which;
				if(key==13)
					control.parentApplication.GetSitemap(control.getValue());
			});
			app.Controls.Add(app.sitemapURI);
			
			app.sitemapGet = new app.Controls.Button("Fetch Sitemap");
			app.sitemapGet.onclick.push(function(e,control){
				control.parentApplication.GetSitemap(control.parentApplication.sitemapURI.getValue());
			});
			app.Controls.Add(app.sitemapGet);
			app.sitemapGet.setPosition(app.getWidth()-app.sitemapGet.getWidth()-10, app.sitemapURI.getY() + (app.sitemapURI.getHeight()-app.sitemapGet.getHeight())/2);
			app.sitemapURI.setStyle({ width:(app.getWidth()-app.sitemapGet.getWidth()-25)+"px" });
			
			
			// sharing / options
			app.moreInfo = new app.Controls.Image("images/info.png",32,32);
			app.moreInfo.onclick.push(function(e,control) {
				window.open("http://jasonmillerdesign.com/Web_Apps/Sitemappr");
			});
			app.Controls.Add(app.moreInfo);
			app.moreInfo.setStyle({ position:"absolute" , top:"2px" , left:"4px" , cursor:"pointer" });
			
			
			app.openApp = new app.Controls.Image("images/open-app.png",32,32);
			app.openApp.onclick.push(function(){ window.open("http://jasonmillerdesign.com/apps/sitemappr/"); });
			app.Controls.Add(app.openApp);
			app.openApp.setStyle({ position:"absolute" , top:"2px" , right:"36px" , cursor:"pointer" });
			
			
			app.getWidget = new app.Controls.Image("images/get-widget.png",32,32);
			app.getWidget.onclick.push(function(e,control) {
				window.open("http://jasonmillerdesign.com/Web_Apps/Sitemappr/#widget-code");
			});
			app.Controls.Add(app.getWidget);
			app.getWidget.setStyle({ position:"absolute" , top:"2px" , left:"36px" , cursor:"pointer" });
			
			
			app.addFav = new app.Controls.Image("images/add-fav.png",32,32);
			app.addFav.onclick.push(function(e,control) {
				Sitemappr.ShowSharing();
			});
			app.Controls.Add(app.addFav);
			app.addFav.setStyle({ position:"absolute" , top:"2px" , right:"4px" , cursor:"pointer" });
			
			
			// status bar
			app.statusBar = new app.Controls.StatusBar("position:absolute; bottom:0; left:0; width:100%;");
			app.Controls.Add(app.statusBar);
			
			app.statusBar.progress = new app.Controls.ProgressBar(0);
			app.statusBar.progress.setPosition( 5 , 3 );
			app.statusBar.Controls.Add(app.statusBar.progress);
			
			/*
			app.statusBar.exp = new app.Controls.Label("(NR: No Rank, ERR: Communication Error)","font-size:88%");
			app.statusBar.exp.setPosition( 120 , 3 );
			app.statusBar.Controls.Add(app.statusBar.exp);
			*/
			
			app.statusBar.link = new app.Controls.Label("App by <span style=\"text-decoration:underline; color:#26A;\">Jason Miller Design<\/span>");
			app.statusBar.link.onclick.push(function(){
				window.open("http://jasonmillerdesign.com/");
			});
			app.statusBar.link.setStyle({ position:"absolute" , right:"20px" , top:"1px" , cursor:"pointer" });
			app.statusBar.Controls.Add(app.statusBar.link);
			
			app.sitemapDisplay = new app.Controls.Panel("display:block; top:3px; position:relative; padding:0; margin:0 1px; width:"+(app.getWidth()-2)+"px; background:#FFF; border:none; overflow:hidden;");
			app.sitemapDisplay.baseArea.className += " scrollable";
			app.Controls.Add(app.sitemapDisplay);
			app.sitemapDisplay.setStyle({ height:(app.getHeight()-app.sitemapDisplay.getY()-app.statusBar.getHeight())+"px" });
			//Scrollable.Activate(app.sitemapDisplay.baseArea);
			
			
			app.GetSitemap = function(uri) {
				if(uri && uri.length && uri.length>2) {
					this.attemptedURI = uri;
					this.statusBar.progress.setValue(100);
					XDR(uri,function(response){
						this.statusBar.progress.setValue(0);
						if( response.$error && response.$error.length && response.$error.length>0 ) {
							alert( response.$error+"" );
						}
						else if( !response.urlset || !response.urlset.url || !response.urlset.url.length ) {
							alert("There was an error parsing the requested sitemap.");
						}
						else {
							this._uri = this.attemptedURI;
							
							location.href = location.href.replace(/#(.*?)$/mgi,'') + "#sitemap="+encodeURIComponent(this._uri);
							
							var urls = [];
							for(var x=0; x<response.urlset.url.length; x++)
								urls.push( response.urlset.url[x].loc );
							
							while(this.sitemapDisplay.Controls.All.length>0)
								this.sitemapDisplay.Controls.Remove(this.sitemapDisplay.Controls.All[0]);
							
							var domain = this._uri.replace(/^(http|https)\:\/\//mgi,'');
							domain = domain.substring( 0,domain.indexOf("/") );
							
							this._items = [];
							this.itemsLoaded = 0;
							for(var p=0; p<urls.length; p++) {
								var url = new this.Controls.Panel();
								url.setStyle({ display:"block" , position:"relative" , border:"none" , padding:"1px" , margin:"0" , background:(p%2==0?"#E6F3FF":"#FFF") });
								this.sitemapDisplay.Controls.Add( url );
								
								var _url = urls[p].replace(/^(http|https)\:\/\//mgi,'');
								_url = _url.substring( _url.indexOf("/") , _url.length );
								
								url._uri = new this.Controls.Label( _url );
								url._uri.setStyle({ border:"none" , padding:"0" , margin:"0 0 0 124px" , color:"#26A" , textDecoration:"underline" , cursor:"pointer" });
								url._uri._selfURI = urls[p];
								url._uri.onclick.push(function(e,control){ window.open(control._selfURI); });
								url.Controls.Add( url._uri );
								
								url._loading = new this.Controls.ProgressBar( 100 );
								url._loading.setStyle({ position:"absolute" , left:"22px" , top:"2px" , border:"none" , borderTop:"1px solid #000" , borderBottom:"1px solid #DDD" , background:"#333" });
								url.Controls.Add( url._loading );
								
								url._value = new this.Controls.Label("...");
								url._value.setStyle({ position:"absolute" , display:"block" , width:"20px" , left:"1px" , top:"0px" , border:"none" , background:"none" , textAlign:"center" });
								url.Controls.Add( url._value );
								
								XDR("http://ranxd.com/api/?format=jsonp&callback=|%callback%|&domain="+encodeURIComponent(urls[p].replace(/^(http|https|ftp)\:\/\//mgi,'')), function(response){
									var item = this;
									item.parentApplication.itemsLoaded++;
									if(item.parentApplication.itemsLoaded>=item.parentApplication._items.length)
										item.parentApplication.statusBar.progress.setValue( 0 );
									else
										item.parentApplication.statusBar.progress.setValue( Math.round(item.parentApplication.itemsLoaded/item.parentApplication._items.length*100) );
									if(!response) {
										item._value.setText("ERR");
										item._loading.setValue(0);
										item._loading.baseArea.style.background = "#F00";
										item.setStyle({ background:"#FCC" , color:"#900" });
									}
									else if(response.pagerank) {
										var pr = parseInt(response.pagerank);
										if( pr==99 || pr==null || pr=="undefined" || pr+""=="NaN" ) {
											item._value.setText("NR");
											item._loading.setValue(0);
											item._loading.baseArea.style.background = "#544";
										}
										else {
											item._value.setText(pr+"");
											item._loading.setValue( pr*10 );
											item._loading.bar.style.background = "#3CB776";
										}
									}
								}, url, false);
								
								this._items.push(url);
							}
							// done display
							//app.sitemapDisplay.baseArea.setScrollSnapping( null , this._items[0].getHeight()-0.5 );
						}
					},this);
					return true;
				}
				return false;
			};
			
			
			app.onresize.push(function(app,w,h) {
				app.sitemapGet.setPosition(w-app.sitemapGet.getWidth()-10, app.sitemapURI.getY() + (app.sitemapURI.getHeight()-app.sitemapGet.getHeight())/2);
				app.sitemapURI.setStyle({ width:(w-app.sitemapGet.getWidth()-25)+"px" });
				app.sitemapDisplay.setStyle({ height:(h-app.sitemapDisplay.getY()-app.statusBar.getHeight())+"px" , width:(w-2)+"px" });
			});
			
			
			// initialize AddThis:
			
			this.w3c = document.getElementById("w3c");
			this.sharingWrap = document.getElementById("addthis_wrapper");
			this.sharingCloser = document.getElementById("addthis_close");
			this.sharingCover = document.getElementById("sharing_cover");
			this.setOpacity( this.sharingCover , 70);
			this.sharingCover.onclick = this.sharingCloser.onclick = function(e) {
				if(!e)e=window.event;
				Sitemappr.HideSharing();
				return ApplicationFramework.NullFunction(e);
			};
			this.sharingCover.onmousedown = this.sharingCloser.onmousedown = function(e) {
				if(!e)e=window.event;
				return ApplicationFramework.NullFunction(e);
			};
			
			try { addthis_open(null, '', prefs.addthis.url, prefs.addthis.title); } catch(err) {}
			
			window._addthis_interval = window.setInterval(function(){
				if( a=document.getElementById("at16p") ) {
					try{ window.clearInterval(window._addthis_interval); }catch(err){}
					a.parentNode.removeChild(a);
					a.style.top = "0";
					a.style.left = "0";
					a.style.right = "auto";
					a.style.visibility = "visible";
					a.style.position = "relative";
					a.style.margin = "0";
					a.style.zIndex = 1;
					Sitemappr.sharingWrap.appendChild(a);
					Sitemappr.sharingWrap.style.height = a.offsetHeight+"px";
					Sitemappr.sharingWrap.style.width = a.offsetWidth+"px";
				}
			},100);
			
			
			
			// init and finish
			app.init();
			
			if( window.location && window.location.href && window.location.href.indexOf("?sitemap=")>-1 ) {
				var i = decodeURIComponent(window.location.href.substring(window.location.href.indexOf("?sitemap=")+9,window.location.href.length));
				app.sitemapURI.setText(i.replace(/</mgi,'&lt;').replace(/>/mgi,'&gt;'));
				window.setTimeout("getApplicationById("+app.appid+").GetSitemap(decodeURIComponent('"+encodeURIComponent(i)+"'));", 100);
			}
			else if( window.location && window.location.href && window.location.href.indexOf("#sitemap=")>-1 ) {
				var i = decodeURIComponent(window.location.href.substring(window.location.href.indexOf("#sitemap=")+9,window.location.href.length));
				app.sitemapURI.setText(i.replace(/</mgi,'&lt;').replace(/>/mgi,'&gt;'));
				window.setTimeout("getApplicationById("+app.appid+").GetSitemap(decodeURIComponent('"+encodeURIComponent(i)+"'));", 100);
			}
			else if( window.location && window.location.href && window.location.href.indexOf("#widgetmode=true")==-1 ) {
				app.sitemapURI.focus();
				try{ app.sitemapURI.baseArea.SelectAll(); }catch(err){}
				try{ app.sitemapURI.baseArea.select(); }catch(err){}
			}
			// <end load>
		},
		ShowSharing	: function(animDir) {
			if( animDir!==1 && animDir!==-1 )
				animDir = 1;
			if(this._sharingDir && this._sharingDir==animDir)
				return false;
			if(this._sharingAnimator)
				try{ window.clearInterval(this._sharingAnimator); }catch(err){}
			if(this._isFirstSharingShow==true && animDir==1) {
				this.sharingWrap.style.top = -this.sharingWrap.offsetHeight + "px";
				this._isFirstSharingShow = false;
			}
			this.sharingWrap.style.left = (this.w3c.offsetWidth - this.sharingWrap.offsetWidth)/2 + "px";
			if( animDir==1 )
				this.sharingCover.style.display = "block";
			this._sharingDir = animDir;
			this._sharingStep = 0;
			this._sharingStepMax = 20;
			this._sharingStart = this.sharingWrap.offsetTop;
			this._sharingMax = animDir==1 ? 0 : -this.sharingWrap.offsetHeight;
			this._sharingAnimator = window.setInterval(function(){ Sitemappr._animateSharing(); }, 20);
		},
		HideSharing	: function() {
			this.ShowSharing(-1);
		},
		_animateSharing	: function() {
			var dir = this._sharingDir;
			this._sharingStep++;
			this.sharingWrap.style.top = ( this._sharingStart+(Math.sin(Math.PI*(this._sharingStep/this._sharingStepMax-1/2))+1)*(this._sharingMax-this._sharingStart)/2 )+"px";
			if( this._sharingStep>=this._sharingStepMax ){
				this._sharingDir = null;
				if( this._sharingMax!=0 )
					this.sharingCover.style.display = "none";
				window.clearInterval( this._sharingAnimator );
			}
		},
		_isFirstSharingShow	: true,
		sharingWrap : null,
		sharingCloser : null,
		sharingCover : null,
		w3c : null,
		setOpacity	: (
			(document.all&&navigator.userAgent.toLowerCase().indexOf("msie")>-1&&parseFloat(navigator.appVersion)<8) ? function(el,o) {
				el.style.filter = "alpha(opacity="+Math.round(o)+")";
			} : function(el,o) {
				el.style.opacity = Math.round(o)/100 + "";
			}
		),
		loaded	: false
	};
	return self;
})();
