window.onDOM = function() {
	
	document.body.scrollTop = 0;
	
	var app = new Application("miniPNG");
	
	
	var previewBackground = "url('/apps/delitweet/ajs/themes/default/images/midtone-checkerboard.jpg') center 0";
	var crushedPreviewBackground = "url('/apps/delitweet/ajs/themes/default/images/midtone-checkerboard.jpg') center top";
	
	var upload = {
		submit : function() {
			var w = app.toolbar.openFromDisk.getWidth();
			app.toolbar.openFromDisk.setText("Opening...");
			app.toolbar.openFromDisk.setIcon("img/loading-sm.gif");
			app.toolbar.openFromDisk.setWidth(w);
		},
		complete : function(response) {
			app.toolbar.openFromDisk.setText("Open from Disk");
			app.toolbar.openFromDisk.setIcon("img/toolbar/open-from-disk.png");
			
			if(response && response.result===true) {
				app.Open( (response.download||response.url)+"/"+encodeURIComponent(response.name) , response.name , response.size );
			}
			else {
				if(response && response.message)
					alert("Error uploading: "+response.message);
				else
					alert("An unknown error occurred while uploading the file.");
			}
		}
	};
	
	
	
	
	// create application
	
	app.ToggleFullscreen();
	
	app.toolbar = new app.Controls.Toolbar();
	app.Controls.Add(app.toolbar);
	
	app.toolbar.openFromDisk = new app.Controls.ToolbarButton("Open from Disk", "img/toolbar/open-from-disk.png");
	app.toolbar.Controls.Add(app.toolbar.openFromDisk);
	
	app.toolbar.openFromWeb = new app.Controls.ToolbarButton("Open from Web", "img/toolbar/open-from-web.png");
	app.toolbar.openFromWeb.onclick.push(function() {
		this.parentApplication.OpenFromWeb();
	});
	app.toolbar.Controls.Add(app.toolbar.openFromWeb);
	
	app.toolbar.openFromFTP = new app.Controls.ToolbarButton("Open from FTP", "img/toolbar/open-from-ftp.png");
	app.toolbar.openFromFTP.onclick.push(function() {
		this.parentApplication.OpenFromFTP();
	});
	app.toolbar.Controls.Add(app.toolbar.openFromFTP);
	
	
	// centered
	app.logoImage = new app.Controls.Image("img/welcome-sm.png", 120, 30, null, true, 100);
	app.toolbar.Controls.Add(app.logoImage);
	app.logoImage.setPosition( (app.getWidth()-app.logoImage.getWidth())/2 , (app.toolbar.getHeight()-app.logoImage.getHeight())/2 );
	
	
	// right-aligned
	app.toolbar.showSharing = new app.Controls.ToolbarButton("Add This", "img/toolbar/addthis.png");
	app.toolbar.showSharing.onclick.push(function(){
		window.sharing.show();
	});
	app.toolbar.Controls.Add(app.toolbar.showSharing);
	app.toolbar.showSharing.setPosition(app.getWidth()-app.toolbar.showSharing.getWidth());
	
	app.toolbar.saveToDisk = new app.Controls.ToolbarButton("Save to Disk", "img/toolbar/save-to-disk.png");
	app.toolbar.saveToDisk.onclick.push(function(){ this.parentApplication.SaveToDisk(); });
	app.toolbar.Controls.Add(app.toolbar.saveToDisk);
	app.toolbar.saveToDisk.setPosition(app.getWidth()-app.toolbar.saveToDisk.getWidth()-app.toolbar.showSharing.getWidth());
	app.toolbar.saveToDisk.Disable();
	
	app.toolbar.toggleView = new app.Controls.ToolbarButton("Toggle View", "img/toolbar/toggle-view.png");
	app.toolbar.toggleView.onclick.push(function(){
		app.toggleViewState = app.toggleViewState===false;
		app.resizeImageDisplay( app.toggleViewState?app.content.getHeight():0 );
	});
	app.toolbar.Controls.Add(app.toolbar.toggleView);
	app.toolbar.toggleView.setPosition(app.getWidth()-app.toolbar.showSharing.getWidth()-app.toolbar.saveToDisk.getWidth()-app.toolbar.toggleView.getWidth());
	
	
	
	app.status = new app.Controls.StatusBar();
	app.Controls.Add(app.status);
	
	app.status.nameDisplay = new app.Controls.Label("Use the menu items on the left to open files.");
	app.status.nameDisplay.setPosition(10,2);
	app.status.Controls.Add(app.status.nameDisplay);
	
	app.status.sizeInfo = new app.Controls.Label(" ");
	app.status.Controls.Add(app.status.sizeInfo);
	app.status.sizeInfo.setPosition(app.getWidth()/2-app.status.sizeInfo.getWidth()/2 , 1);
	
	app.status.progress = new app.Controls.ProgressBar();
	app.status.Controls.Add(app.status.progress);
	app.status.progress.setPosition( app.getWidth()-app.status.progress.getWidth()-20 , 2 );
	
	
	app.main = new app.Controls.Panel({
		height : app.getHeight()-app.toolbar.getHeight()-app.status.getHeight()
	});
	app.main.adoptStyle("none","fullwidth");
	app.Controls.Add(app.main);
	
	
	
	app.sidebar = new app.Controls.Panel();
	app.sidebar.adoptStyle("sidebar","fullheight");
	app.sidebar.setPosition(0,0);
	app.sidebar.setWidth(220);
	app.main.Controls.Add(app.sidebar);
	app.sidebar.minWidth = 120;
	app.sidebar.maxWidth = 360;
	
	
	function sidebarResizeHandler(e) {
		this._grabbedX = e.pageX?e.pageX:e.clientX;
		this._grabbedLeft = this.parentApplication.sidebar.getWidth();
		this._resizingCover = ApplicationFramework.CreateShim(999);
		this.parentApplication._dragStartEv();
		this.moveEvt = ApplicationFramework.RegisterGlobalMouse("move",function(e,x,y){
			this.parentApplication.resizeLeftPanel( this._grabbedLeft + x - this._grabbedX );
			return false;
		},this);
		this.upEvt = ApplicationFramework.RegisterGlobalMouse("up",function(e,x,y,b) {
			ApplicationFramework.UnregisterGlobalMouse("move",this.moveEvt);
			ApplicationFramework.UnregisterGlobalMouse("up",this.upEvt);
			this.parentApplication.resizeLeftPanel( this._grabbedLeft + x - this._grabbedX );
			ApplicationFramework.RemoveShim(this._resizingCover);
			try{ delete this._grabbedX; }catch(err){}
			this.parentApplication._dragStopEv();
			return false;
		},this);
		return false;
	}
	
	app.sidebar.resizer = new app.Controls.Image("img/panel-resize.png", 10,15);
	app.sidebar.resizer.setStyle("position:absolute; right:3px; bottom:0; z-index:800;");
	app.sidebar.Controls.Add(app.sidebar.resizer);
	app.sidebar.resizer.onmousedown.push(sidebarResizeHandler);
	
	app.sidebarResizerBar = new app.Controls.Label(" ", {top:0,left:app.sidebar.getWidth(),width:3,zIndex:800});
	app.sidebarResizerBar.adoptStyle("none","fullheight");
	app.sidebarResizerBar.onmouseover.push(function(){ this.setStyle({ background:"#98A8BA" }); });
	app.sidebarResizerBar.onmouseout.push(function(){ this.setStyle({ background:"none" }); });
	app.sidebarResizerBar.onmousedown.push(sidebarResizeHandler);
	app.main.Controls.Add(app.sidebarResizerBar);
	
	
	app.sidebar.toolbar = new app.Controls.Toolbar("small");
	app.sidebar.Controls.Add(app.sidebar.toolbar);
	
	app.sidebar.status = new app.Controls.StatusBar();
	app.sidebar.status.adoptStyle("none");
	app.sidebar.Controls.Add(app.sidebar.status);
	
	app.sidebar.status.progress = new app.Controls.ProgressBar();
	app.sidebar.status.Controls.Add(app.sidebar.status.progress);
	app.sidebar.status.progress.setPosition(3,3);
	
	app.sidebar.list = new app.Controls.Panel("overflow:scroll;");
	app.sidebar.list.adoptStyle("fullwidth", "ListView");
	app.sidebar.list.setHeight(app.sidebar.getHeight()-app.sidebar.toolbar.getHeight()-app.sidebar.status.getHeight());
	app.sidebar.Controls.Add(app.sidebar.list);
	
	
	app.content = new app.Controls.Panel("background:#292929;");
	app.content.setPosition( app.sidebar.getWidth()+3 , 0 );
	app.content.adoptStyle("none","fullheight");
	app.content.setWidth( app.getWidth()-app.sidebar.getWidth()-3 );
	app.main.Controls.Add(app.content);
	app.lastContentPanelHeight = app.content.getHeight();
	
	
	
	
	
	app.imageDisplay = new app.Controls.PictureBox("");
	app.imageDisplay.minHeight = 0;
	app.imageDisplay.setStyle({ background:previewBackground , backgroundPosition:"center "+(app.content.getHeight()/2-1)+"px" });
	app.imageDisplay.setPosition(0,0);
	app.imageDisplay.setWidth(app.content.getWidth());
	app.imageDisplay.setHeight(app.content.getHeight()/2-2);
	app.content.Controls.Add(app.imageDisplay);
	
	app.crushedDisplay = new app.Controls.PictureBox("");
	app.crushedDisplay.minHeight = 0;
	app.crushedDisplay.setStyle({ background:crushedPreviewBackground });
	app.crushedDisplay.setPosition(0,app.imageDisplay.getHeight()+3);
	app.crushedDisplay.setWidth(app.content.getWidth());
	app.crushedDisplay.setHeight(app.content.getHeight()-app.imageDisplay.getHeight()-3);
	app.content.Controls.Add(app.crushedDisplay);
	
	app.content.loading = new app.Controls.Image("img/loading.gif", 32, 32, "left", false, 100);
	app.content.loading.setPosition(50,25,"%");
	app.content.loading.setStyle("background:url('img/loading_bg.png') center no-repeat; padding:8px; margin:-24px 0 0 -24px; display:none;");
	app.content.Controls.Add(app.content.loading);
	
	app.content.crushedLoading = new app.Controls.Image("img/loading.gif", 32, 32, "left", false, 100);
	app.content.crushedLoading.setPosition(50,75,"%");
	app.content.crushedLoading.setStyle("background:url('img/loading_bg.png') center no-repeat; padding:8px; margin:-24px 0 0 -24px; display:none;");
	app.content.Controls.Add(app.content.crushedLoading);
	
	
	app.content.imageLabel = new app.Controls.Image("img/label-current.png", 90, 20, null, true, 100);
	app.content.Controls.Add(app.content.imageLabel);
	app.content.imageLabel.setPosition(5,app.imageDisplay.getHeight()-app.content.imageLabel.getHeight()-5);
	
	app.content.crushedLabel = new app.Controls.Image("img/label-crushed.png", 90, 20, null, true, 100);
	app.content.Controls.Add(app.content.crushedLabel);
	app.content.crushedLabel.setPosition(5,app.imageDisplay.getHeight()+8);
	
	
	app.content.imageSeparator = new app.Controls.Label(" ","height:3px; font-size:1px; overflow:hidden;");
	app.content.imageSeparator.setPosition(0, app.imageDisplay.getHeight());
	app.content.imageSeparator.adoptStyle("none","fullwidth","ColumnTitle");
	app.content.Controls.Add(app.content.imageSeparator);
	app.content.imageSeparator.onmouseover.push(function(){ this.adoptStyle("selected"); });
	app.content.imageSeparator.onmouseout.push(function(){ if(!this._grabbedY) this.removeStyle("selected"); });
	app.content.imageSeparator.onmousedown.push( function(e) {
		this.removeStyle("ColumnTitle");
		this.adoptStyle("selected");
		this._grabbedY = e.pageY?e.pageY:e.clientY;
		this._grabbedTop = this.parentApplication.imageDisplay.getHeight();
		this._resizingCover = ApplicationFramework.CreateShim(999);
		this.parentApplication._dragStartEv();
		this.moveEvt = ApplicationFramework.RegisterGlobalMouse("move",function(e,x,y){
			this.parentApplication.resizeImageDisplay( this._grabbedTop + y - this._grabbedY );
			return false;
		},this);
		this.upEvt = ApplicationFramework.RegisterGlobalMouse("up",function(e,x,y,b) {
			this.adoptStyle("ColumnTitle");
			this.removeStyle("selected");
			ApplicationFramework.UnregisterGlobalMouse("move",this.moveEvt);
			ApplicationFramework.UnregisterGlobalMouse("up",this.upEvt);
			this.parentApplication.resizeImageDisplay( this._grabbedTop + y - this._grabbedY );
			ApplicationFramework.RemoveShim(this._resizingCover);
			try{ delete this._grabbedY; delete this._grabbedTop; }catch(err){}
			this.parentApplication._dragStopEv();
			return false;
		},this);
		return false;
	});
	
	
	
	app.contentOverlay = new app.Controls.Label(" ","font-size:1px; background:url('img/welcome-overlay-arrow.png') 10px 10px no-repeat #222; opacity:93; z-index:900;");
	app.contentOverlay.adoptStyle("none","fullheight","fullwidth");
	app.main.Controls.Add(app.contentOverlay);
	
	app.welcomeExplainer = new app.Controls.Panel("width:400px; left:"+(app.getWidth()/2-200)+"px; top:0px; padding:10px 0 5px; background:#555; z-index:950;");
	app.welcomeExplainer.adoptStyle("separated");
	app.main.Controls.Add(app.welcomeExplainer);
	app.welcomeExplainer._open = true;
	
	app.welcomeExplainerImage = new app.Controls.Image("img/welcome.png", 400, 100, null, true, 100);
	app.welcomeExplainerImage.setStyle({ margin:"0 0 0 10px" });
	app.welcomeExplainer.Controls.Add(app.welcomeExplainerImage);
	
	app.welcomeExplainerText = new app.Controls.Label("miniPNG is a simple web-based PNG Crushing app. To get started, open a PNG image from FTP, a URL or your computer using the buttons above. Then click <u>Save to Disk</u> to save to your computer, or <u>Crush</u> to save back to FTP.<br />miniPNG is brought to you by <a href=\"http://jasonmillerdesign.com/\" target=\"_blank\">Jason Miller Design</a>.", "display:block; clear:both; float:none; padding:15px 10px 0; font-size:120%; font-weight:normal; text-align:left;");
	app.welcomeExplainerText.adoptStyle("none");
	app.welcomeExplainer.Controls.Add(app.welcomeExplainerText);
	
	app.welcomeExplainerClose = new app.Controls.Button("Close", "float:right; clear:both; margin:5px 10px 0 auto;");
	app.welcomeExplainerClose.onclick.push(function() {
		app.contentOverlay.setStyle({display:"none"});
		app.welcomeExplainer.setStyle({display:"none"});
		app.welcomeExplainer._open = false;
	});
	app.welcomeExplainer.Controls.Add(app.welcomeExplainerClose);
	
	
	
	app.onresize.push(function(app,w,h) {
		app.logoImage.setPosition( (w-app.logoImage.getWidth())/2 , (app.toolbar.getHeight()-app.logoImage.getHeight())/2 );
		
		app.main.setHeight(h-app.toolbar.getHeight()-app.status.getHeight());
		app.content.setWidth(w-app.sidebar.getWidth()-3);
		app.sidebar.list.setHeight(app.sidebar.getHeight()-app.sidebar.toolbar.getHeight()-app.sidebar.status.getHeight());
		
		app.imageDisplay.setWidth(app.content.getWidth());
		if( Math.abs(app.imageDisplay.getHeight()+1-app.lastContentPanelHeight/2)<6)
			app.imageDisplay.setHeight(app.content.getHeight()/2-1);
		else if( app.imageDisplay.getHeight()>app.lastContentPanelHeight-3-app.crushedDisplay.minHeight-6)
			app.imageDisplay.setHeight(app.content.getHeight()-app.crushedDisplay.minHeight-3);
		else if( app.imageDisplay.getHeight()<app.imageDisplay.minHeight+6)
			app.imageDisplay.setHeight(app.imageDisplay.minHeight);
		else if(app.imageDisplay.getHeight()>app.lastContentPanelHeight-app.crushedDisplay.minHeight-3)
			app.imageDisplay.setHeight( app.content.getHeight()-app.crushedDisplay.minHeight-3 );
		app.imageDisplay.setStyle({ backgroundPosition:"center "+app.imageDisplay.getHeight()+"px" });
		app.content.imageSeparator.setPosition(0, app.imageDisplay.getHeight());
		
		app.crushedDisplay.setPosition(0, app.imageDisplay.getHeight()+3);
		app.crushedDisplay.setHeight(app.content.getHeight()-app.imageDisplay.getHeight()-3);
		app.crushedDisplay.setWidth(app.content.getWidth());
		
		app.content.imageLabel.setPosition(5,app.imageDisplay.getHeight()-app.content.imageLabel.getHeight()-5);
		app.content.crushedLabel.setPosition(5,app.imageDisplay.getHeight()+8);
		
		app.imageDisplay.setCentered();
		app.crushedDisplay.setCentered();
		
		app.toolbar.showSharing.setPosition(w-app.toolbar.showSharing.getWidth());
		app.toolbar.saveToDisk.setPosition(w-app.toolbar.showSharing.getWidth()-app.toolbar.saveToDisk.getWidth());
		app.toolbar.toggleView.setPosition(w-app.toolbar.showSharing.getWidth()-app.toolbar.saveToDisk.getWidth()-app.toolbar.toggleView.getWidth());
		
		app.status.progress.setX( w-app.status.progress.getWidth()-20 );
		app.status.sizeInfo.setX( (w-app.status.sizeInfo.getWidth())/2 );
		
		app.welcomeExplainer.setX( w/2-200 );
		
		app.lastContentPanelHeight = app.content.getHeight();
	});
	
	app.resizeImageDisplay = function(height) {
		var sticking = 9;
		height = Math.round(height);
		if(Math.abs(height+1-this.content.getHeight()/2)<sticking) {
			height = this.content.getHeight()/2-1;
		}
		else if(height<this.imageDisplay.minHeight + sticking) {
			height = this.imageDisplay.minHeight;
		}
		else if(height>this.content.getHeight()-this.crushedDisplay.minHeight-3 - sticking) {
			height = this.content.getHeight()-this.crushedDisplay.minHeight-3;
		}
		
		this.crushedDisplay.setHeight(this.content.getHeight()-height-3);
		this.crushedDisplay.setY(height+3);
		this.content.imageSeparator.setY(height);
		this.imageDisplay.setHeight(height);
		this.imageDisplay.setStyle({ backgroundPosition:"center "+height+"px" });
		this.content.imageLabel.setPosition(5,height-this.content.imageLabel.getHeight()-5);
		this.content.crushedLabel.setPosition(5,height+8);
		
		this.imageDisplay.setCentered();
		this.crushedDisplay.setCentered();
	};
	
	app.resizeLeftPanel = function(width) {
		width = Math.round(width);
		if(width<this.sidebar.minWidth)
			width = this.sidebar.minWidth;
		else if(width>this.sidebar.maxWidth)
			width = this.sidebar.maxWidth;
		this.sidebar.setWidth(width);
		this.sidebarResizerBar.setX(width);
		width += 3;
		var cw = app.getWidth()-width;
		
		this.content.setWidth(cw);
		this.content.setX( width );
		
		this.imageDisplay.setWidth(cw);
		this.crushedDisplay.setWidth(cw);
		
		this.imageDisplay.setCentered();
		this.crushedDisplay.setCentered();
	};
	
	
	
	app.onkeypress.push(function(key) {
		var controlKey = ApplicationFramework.isGlobalKeyDown(224) || ApplicationFramework.isGlobalKeyDown(16);
		var ftpConnected = (this.FTP.list) ? true : false;
		var charCode = (String.fromCharCode(key)+"").toLowerCase();
		var ret = true;
		
		if(key==13 && this.currentlySelected) {
			this.currentlySelected.open();
			ret = false;
		}
		else if(charCode=="s" && controlKey && this.currentlySelected) {
			this.SaveToDisk();
			ret = false;
		}
		else if(charCode=="1" && controlKey) {
			/*
			try{
				this.toolbar.openFromDisk._overlay.childNodes[0].contentWindow.document.getElementById('jsonupload_file').focus();
			} catch(err) { alert(err.message); }
			*/
			ret = false;
		}
		else if(charCode=="2" && controlKey) {
			this.OpenFromWeb();
			ret = false;
		}
		else if(charCode=="3" && controlKey) {
			this.OpenFromFTP();
			ret = false;
		}
		else if(charCode=="o" && controlKey) {
			this.OpenFromWeb();
			ret = false;
		}
		else if(key==40 && controlKey && this.currentlySelected) {
			this.currentlySelected.open();
			ret = false;
		}
		else if(key==38 && controlKey && ftpConnected) {
			this.FTP.showDir("..");
			ret = false;
		}
		else if(key==38 && this.currentlySelected && this.currentlySelected.baseArea.previousSibling) {
			this.currentlySelected.baseArea.previousSibling.parentControl.select();
			ret = false;
		}
		else if(key==40 && this.currentlySelected && this.currentlySelected.baseArea.nextSibling) {
			this.currentlySelected.baseArea.nextSibling.parentControl.select();
			ret = false;
		}
		
		
		if(ret===false) {
			return false;
		}
	});
	
	
	
	
	
	
	
	
	
	
	// funcs
	
	app.FTP = {
		serviceURL	: "http://jasonmillerdesign.com/services/jsonFTP/",
		downloadURL	: "http://local.jsonftp.services.jasonmillerdesign.com/get/",
		hostname	: "",
		username	: "",
		password	: "",
		dir			: "",
		showhidden	: false,
		list		: [],
		connection	: null,
		output		: app.sidebar.list,
		progressBar	: app.sidebar.status.progress,
		uploadFile	: function(to, from, onComplete) {
			function ftpComplete() {
				//this.self.progressBar.setValue(0);
				
				if(this.error===true) {
					this._uploadCompleted(false, "FTP connection error");
					return false;
				}
				
				var response = {result:false,message:"There was an error parsing the FTP response."};
				if(this.responseText) {
					try {
						response = eval('('+this.responseText+')');
					} catch(err) {
						response = {result:false,message:"There was an error parsing the FTP response."};
					}
				}
				
				if(response.result!==true) {
					//alert(response.message || "An unknown error occurred while uploading the file via FTP.");
					this._uploadCompleted(false, response.message || "An unknown error occurred while uploading the file via FTP.");
					return false;
				}
				
				// successful
				this._uploadCompleted(true, "Upload successful.");
			}
			
			//this.progressBar.setValue(-1);
			var c = HttpRequest.create(this.serviceURL+"put", {
				hostname	: this.hostname,
				username	: this.username,
				password	: this.password,
				path		: to,
				from		: from
			}, ftpComplete, ftpComplete);
			c.self = this;
			c._uploadCompleted = onComplete || function(){};
			c.Send();
		},
		showDir			: function(dir, absolute) {
			if(absolute!==true) {
				dir = this.dir + dir;
			}
			dir = dir.replace(/([^\/]*?\/\.\.(\/?)|^\/?\.\.)/mgi,'');
			
			if(this.connection && this.connection.Abort && this.connection.completed!==true) {
				this.connection.abort();
			}
			
			function ftpComplete() {
				this.self.progressBar.setValue(0);
				
				if(this.error===true) {
					alert("FTP connection failed.");
					return false;
				}
				
				this.self.showDirCallback(this.responseText);
			}
			
			this.progressBar.setValue(-1);
			this.connection = HttpRequest.create(this.serviceURL+"list", {
				hostname	: this.hostname,
				username	: this.username,
				password	: this.password,
				showhidden	: (this.showhidden===true?true:false),
				path		: dir
			}, ftpComplete, ftpComplete);
			this.connection.self = this;
			this.connection.Send();
		},
		showDirCallback : function(data) {
			var response = {result:false,message:"There was an error parsing the FTP response."};
			if(data) {
				try {
					response = eval('('+data+')');
				} catch(err) {
					response = {result:false,message:"There was an error parsing the FTP response."};
				}
			}
			
			if(response.result!==true) {
				alert(response.message || "An unknown error occurred while retrieving the folder via FTP.");
				return false;
			}
			
			this.list = response.list;
			this.dir = response.dir.replace(/\/$/mgi,'')+"/";
			
			
			// remove current controls:
			while(this.output.Controls.All.length>0) {
				this.output.Controls.Remove(this.output.Controls.All[0]);
			}
			while(this.app.sidebar.toolbar.Controls.All.length>0) {
				this.app.sidebar.toolbar.Controls.Remove(this.app.sidebar.toolbar.Controls.All[0]);
			}
			
			
			// build toolbar:
			var upBtn = new app.Controls.ToolbarButton("Up", "img/sidebar/up.png");
			if(this.dir.replace(/\//mgi,'').length<1) {
				upBtn.Disable();
			}
			else {
				upBtn.onclick.push(function(){
					this.parentApplication.FTP.showDir("..");
				});
			}
			this.app.sidebar.toolbar.Controls.Add(upBtn);
			
			
			var reloadBtn = new app.Controls.ToolbarButton("Reload", "img/sidebar/reload.png");
			reloadBtn.onclick.push(function(){
				this.parentApplication.FTP.showDir(this.parentApplication.FTP.dir, true);
			});
			this.app.sidebar.toolbar.Controls.Add(reloadBtn);
			
			
			var crushBtn = new app.Controls.ToolbarButton("Crush", "img/sidebar/crush.png");
			crushBtn.onclick.push(function(){
				var sel = this.parentApplication.currentlySelected;
				if(!sel._filename || sel._isimage!==true) {
					return false;
				}
				
				var size = sel._size;
				var filename = sel._loadFile_url;
				
				function c(result) {
					if(!sel) {
						return false;
					}
					if(result===false) {
						sel.size.setText( sel.parentApplication.friendlySize(size) );
					}
					else {
						sel.parentApplication.getCrushedSize( filename , function(size) {
							this.setText( this.parentApplication.friendlySize(size) );
						}, sel.size);
					}
				}
				
				sel.size.setText("<img src=\"img/loading.gif\" style=\"height:1.1em; width:1.1em; margin:0 2px -0.6em 0; float:left; clear:none; position:relative; top:1px;\" /> <span style=\"color:#69F;\">crushing</span>");
				this.parentApplication.FTP.uploadFile(sel._filename, this.parentApplication.GenerateCrushURL(sel.loadFile_url), c);
			});
			this.app.sidebar.toolbar.Controls.Add(crushBtn);
			
			
			var f, item, isdir, type, icon, isimage;
			var itemHeight = 20;
			var iconSize = 18;
			for(var i=0; i<this.list.length; i++) {
				f = this.list[i];
				isdir = f.type=="dir" ? true : false;
				type = f.type.replace(/\sfile$/mgi,'').toLowerCase();
				icon = isdir ? "img/sidebar/dir.png" : "img/sidebar/file.png";
				isimage = false;
				if(type=="png" || type=="jpg" || type=="gif" || type=="gd2") {
					icon = "img/sidebar/image.png";
					isimage = true;
				}
				
				item = new app.Controls.ListItem();
				item._filename = this.dir+f.name;
				item._filetype = type;
				item._isdir = isdir;
				item._size = f.size;
				item._isimage = isimage;
				item.setHeight(itemHeight);
				item.setSelectability(false);
				item.draggable = false;
				if(isdir===true) {
					item.loadDir_dir = this.dir + f.name;
					item.open = function() {
						this.parentApplication.FTP.showDir(this.loadDir_dir, true);
					};
				}
				else if(isimage) {
					item.loadFile_url = this.downloadURL+f.id;
					item.loadFile_name = f.name;
					item.open = function() {
						this.parentApplication.Open(this.loadFile_url, this.loadFile_name, this._size);
					};
				}
				else {
					this.downloadFile_url = this.downloadURL+f.id;
					item.open = function() {
						this.parentApplication.downloadFile(this.downloadFile_url);
					};
				}
				item.select = function() {
					for(var x=0; x<this.parentPanel.Controls.All.length; x++) {
						if(this.parentPanel.Controls.All[x]!=this) {
							this.parentPanel.Controls.All[x].removeStyle("selected");
						}
					}
					this.adoptStyle("selected");
					try {
						if(this.getY()+this.getHeight()>=this.parentPanel.baseArea.scrollTop+this.parentPanel.getHeight()) {
							this.parentPanel.scrollTo(null,this.getY()+this.getHeight()-this.parentPanel.getHeight());
						}
						else if(this.getY()<=this.parentPanel.baseArea.scrollTop) {
							this.parentPanel.scrollTo(null,this.getY());
						}
					} catch(err){}
					this.parentApplication.currentlySelected = this;
				};
				item.onclick.push(function(e) {
					this.select();
					if(this.doubleClickWaiting===true) {
						this.doubleClickWaiting = false;
						ApplicationFramework.UnregisterTimer(this.doubleClickTimer);
						this.open();
						return false;
					}
					this.doubleClickWaiting = true;
					this.doubleClickTimer = ApplicationFramework.RegisterTimer(function(){
						this.doubleClickTimer = null;
						this.doubleClickWaiting = false;
					}, 20, this, 1);
					return false;
				});
				this.output.Controls.Add(item);
				
				item.icon = new app.Controls.Image(icon, iconSize, iconSize);
				item.icon.setSelectability(false);
				item.icon.setPosition(2, (itemHeight-iconSize)/2);
				item.Controls.Add(item.icon);
				
				item.label = new app.Controls.Label(f.name.replace(/</,'&lt;'), "font-size:90%;");
				item.label.setSelectability(false);
				item.label.adoptStyle("none");
				item.Controls.Add(item.label);
				item.label.setPosition(iconSize+6, Math.ceil((itemHeight-item.label.getHeight())/2));
				
				if(!isdir) {
					item.size = new app.Controls.Label( this.app.friendlySize(f.size) , "position:absolute; right:3px; font-size:80%; padding:1px 3px; color:#FFF; background:url('img/sidebar/filesize-grad.png') center #999; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px;" );
					item.size.setSelectability(false);
					item.size.adoptStyle("none");
					item.Controls.Add(item.size);
					item.size.setY( Math.ceil((itemHeight-item.size.getHeight())/2) );
				}
				
				if(i==0) {
					item.select();
				}
			}
		},
		app : app
	};
	
	app.OpenFromFTP = function(hostname, username, password) {
		if(!hostname) {
			var cover = ApplicationFramework.CreateShim(this.formframe.style.zIndex, "dialog_backgroundcover");
			cover.onmousedown = cover.onmouseup = cover.onclick = function(){ this.dialog.focus(); };
			var dialog = new Application(this.name, 400, 200);
			dialog.cover = cover;
			cover.dialog = dialog;
			dialog.parentApplication = this;
			dialog.setTitle("FTP Connection");
			dialog.DisableMaximize();
			dialog.DisableMinimize();
			
			
			dialog.serverPanel = new dialog.Controls.Panel();
			dialog.serverPanel.adoptStyle("separated","fullwidth");
			dialog.Controls.Add(dialog.serverPanel);
			
			dialog.serverTitle = new dialog.Controls.Label("Server <i>(:port)</i>");
			dialog.serverPanel.Controls.Add(dialog.serverTitle);
			
			dialog.serverField = new dialog.Controls.TextInput(this.FTP.hostname,"",1);
			dialog.serverPanel.Controls.Add(dialog.serverField);
			
			dialog.usernamePanel = new dialog.Controls.Panel();
			dialog.usernamePanel.adoptStyle("separated","fullwidth");
			dialog.Controls.Add(dialog.usernamePanel);
			
			dialog.usernameTitle = new dialog.Controls.Label("Username");
			dialog.usernamePanel.Controls.Add(dialog.usernameTitle);
			
			dialog.usernameField = new dialog.Controls.TextInput(this.FTP.username,"",2);
			dialog.usernamePanel.Controls.Add(dialog.usernameField);
			
			
			dialog.passwordPanel = new dialog.Controls.Panel();
			dialog.passwordPanel.adoptStyle("separated","fullwidth");
			dialog.Controls.Add(dialog.passwordPanel);
			
			dialog.passwordTitle = new dialog.Controls.Label("Password");
			dialog.passwordPanel.Controls.Add(dialog.passwordTitle);
			
			dialog.passwordField = new dialog.Controls.TextInput(this.FTP.password,"",3,true);
			dialog.passwordPanel.Controls.Add(dialog.passwordField);
			
			
			dialog.connectBtn = new dialog.Controls.Button("Connect");
			dialog.connectBtn.onclick.push(function() {
				this.parentApplication.Submit();
			});
			dialog.Controls.Add(dialog.connectBtn);
			
			
			dialog.onresize.push(function(app,w,h) {
				if(h>this.minHeight) {
					this.setHeight(this.minHeight);
					return false;
				}
				var padding = 10;
				var itemHeight = Math.max(this.serverField.getHeight(), this.serverTitle.getHeight()) + (padding*2);
				var mid = Math.max(this.serverTitle.getWidth(), this.usernameTitle.getWidth(), this.passwordTitle.getWidth()) + padding;
				
				this.serverPanel.setHeight( itemHeight );
				this.usernamePanel.setHeight( itemHeight );
				this.passwordPanel.setHeight( itemHeight );
				
				this.serverTitle.setPosition( mid-this.serverTitle.getWidth() , padding+2 );
				this.usernameTitle.setPosition( mid-this.usernameTitle.getWidth() , padding+2 );
				this.passwordTitle.setPosition( mid-this.passwordTitle.getWidth() , padding+2 );
				
				this.serverField.setPosition( mid , padding );
				this.usernameField.setPosition( mid , padding );
				this.passwordField.setPosition( mid , padding );
				
				this.serverField.setWidth( w-mid-padding );
				this.usernameField.setWidth( w-mid-padding );
				this.passwordField.setWidth( w-mid-padding );
				
				this.connectBtn.setPosition( (w-this.connectBtn.getWidth())/2 , (itemHeight+2)*3 + padding );
			});
			
			
			dialog.onkeyup.push(function(key){
				if(key==13) {
					this.Submit();
				}
				else if(key==27) {
					this.Close();
				}
			});
			
			
			dialog.Submit = function() {
				var server = this.serverField.getValue();
				var username = this.usernameField.getValue();
				var password = this.passwordField.getValue();
				
				if(server.length<1) {
					return this.serverField.focus();
				}
				
				this.parentApplication.OpenFromFTP(server, username, password);
				
				this.Close();
			};
			
			
			dialog.onclose.push(function() {
				ApplicationFramework.RemoveShim(this.cover);
				this.parentApplication.focus();
			});
			
			
			dialog.init();
			dialog.resizeTo(400,200,true);
			var min = dialog.connectBtn.getY()+dialog.connectBtn.getHeight()+10
			dialog.setMinSize(200,min);
			dialog.resizeTo(400,min);
			
			dialog.serverField.focus();
			
			return true;
		}
		
		
		// connect and show root directory:
		
		this.FTP.hostname = hostname;
		this.FTP.username = username;
		this.FTP.password = password;
		
		this.FTP.progressBar.setValue(-1);
		
		function ftpComplete() {
			this.app.FTP.progressBar.setValue(0);
			
			if(this.error===true) {
				alert("FTP connection failed.");
				return false;
			}
			
			// connection successful; read out root dir:
			this.app.FTP.showDirCallback(this.responseText);
		}
		
		this.FTP.connection = HttpRequest.create(this.FTP.serviceURL+"list", {
			hostname	: hostname,
			username	: username || "",
			password	: password || "",
			showhidden	: (this.FTP.showhidden===true?true:false)
		}, ftpComplete, ftpComplete);
		this.FTP.connection.app = this;
		this.FTP.connection.Send();
		
		
		if(this.welcomeExplainer._open===true) {
			this.contentOverlay.setStyle({display:"none"});
			this.welcomeExplainer.setStyle({display:"none"});
			this.welcomeExplainer._open = false;
		}
	};
	
	
	
	app.OpenFromWeb = function() {
		var cover = ApplicationFramework.CreateShim(this.formframe.style.zIndex, "dialog_backgroundcover");
		cover.onmousedown = cover.onmouseup = cover.onclick = function(){ this.dialog.focus(); };
		var dialog = new Application(this.name, 400, 200);
		dialog.cover = cover;
		cover.dialog = dialog;
		dialog.parentApplication = this;
		dialog.setTitle("Open URL");
		dialog.DisableMaximize();
		dialog.DisableMinimize();
		
		
		dialog.locationPanel = new dialog.Controls.Panel();
		dialog.locationPanel.adoptStyle("none","fullwidth");
		dialog.Controls.Add(dialog.locationPanel);
		
		dialog.locationTitle = new dialog.Controls.Label("Location:");
		dialog.locationPanel.Controls.Add(dialog.locationTitle);
		
		dialog.locationField = new dialog.Controls.TextInput(this.currentURL||"http://","",1);
		dialog.locationPanel.Controls.Add(dialog.locationField);
		
		
		dialog.connectBtn = new dialog.Controls.Button("Open");
		dialog.connectBtn.onclick.push(function() {
			this.parentApplication.Submit();
		});
		dialog.Controls.Add(dialog.connectBtn);
		
		
		dialog.onresize.push(function(app,w,h) {
			if(h>this.minHeight) {
				this.setHeight(this.minHeight);
				return false;
			}
			var padding = 10;
			var itemHeight = Math.max(this.locationField.getHeight(), this.locationTitle.getHeight()) + (padding*2);
			var mid = this.locationTitle.getWidth() + padding;
			
			this.locationPanel.setHeight( itemHeight );
			
			this.locationTitle.setPosition( mid-this.locationTitle.getWidth() , padding+2 );
			
			this.locationField.setPosition( mid , padding );
			
			this.locationField.setWidth( w-mid-padding );
			
			this.connectBtn.setPosition( (w-this.connectBtn.getWidth())/2 , itemHeight );
		});
		
		
		dialog.onkeyup.push(function(key){
			if(key==13) {
				this.Submit();
			}
			else if(key==27) {
				this.Close();
			}
		});
		
		
		dialog.Submit = function() {
			var location = this.locationField.getValue();
			
			if(location.length<1 || location.indexOf("://")<2 || location.replace(/[a-z0-9]*?:\/\//mgi,'').length<2) {
				return this.locationField.focus();
			}
			
			this.parentApplication.Open(location);
			
			this.Close();
		};
		
		
		dialog.onclose.push(function() {
			ApplicationFramework.RemoveShim(this.cover);
			this.parentApplication.focus();
		});
		
		
		dialog.init();
		dialog.resizeTo(400,200,true);
		var min = dialog.connectBtn.getY()+dialog.connectBtn.getHeight()+10
		dialog.setMinSize(200,min);
		dialog.resizeTo(400,min);
		
		dialog.locationField.focus();
		if(dialog.locationField.getText()!="http://") {
			try{ dialog.locationField.baseArea.select(); }catch(err){}
		}
		
		return true;
	};
	
	
	
	app.Open = function(location, name, size) {
		if(!location) {
			return false;
		}
		if(!location.match(/^[a-z0-9]*?\:\/\//)) {
			lcoation = "http://" + location;
		}
		if(!name) {
			name = location.replace(/^.*\//mgi,'');
		}
		if(!size) {
			size = 0;
		}
		var protocol = location.substring(0,location.indexOf("://")).toLowerCase();
		switch( protocol ) {
			case "http":
			case "https":
			case "ftp":
			case "ftps":
				this._doOpen(location, name, size);
			break;
			
			default:
				alert(this.name+" doesn't know how to open that location because it uses an unknown protocol ("+protocol+").");
			break;
		}
	};
	
	app._doOpen = function(src, name, size) {
		if(this._openWaiter) {
			ApplicationFramework.UnregisterTimer(this._openWaiter);
		}
		this.content.loading.setStyle({display:"block"});
		this.content.crushedLoading.setStyle({display:"block"});
		
		if(this.welcomeExplainer._open===true) {
			this.contentOverlay.setStyle({display:"none"});
			this.welcomeExplainer.setStyle({display:"none"});
			this.welcomeExplainer._open = false;
		}
		
		this.loading = true;
		
		this.currentName = name;
		this.currentSize = size;
		
		this.status.nameDisplay.setText(this.currentName);
		
		this.setTitle(this.currentName + " -miniPNG");
		
		this.currentURL = src;
		this.currentCrushedURL = this.GenerateCrushURL(src);
		
		this.imageLoaded = false;
		this.crushedLoaded = false;
		
		this.imageDisplay.setImage(this.currentURL);
		this.crushedDisplay.setImage(this.currentCrushedURL);
		
		this.toolbar.saveToDisk.Enable();
		
		this._openWaiter = ApplicationFramework.RegisterTimer(function() {
			if(this.imageDisplay.src===this.currentURL && this.imageDisplay.image.style.visibility=="visible") {
				this.content.loading.setStyle({display:"none"});
				this.imageLoaded = true;
			}
			if(this.crushedDisplay.src===this.currentCrushedURL && this.crushedDisplay.image.style.visibility=="visible") {
				this.content.crushedLoading.setStyle({display:"none"});
				this.crushedLoaded = true;
			}
			if((this.imageLoaded && this.crushedLoaded) || this.currentURL!=src) {
				this.loading = false;
				ApplicationFramework.UnregisterTimer(this._openWaiter);
				this._openWaiter = null;
				
				if(this.currentURL!=src) {
					return false;
				}
				
				var f = document.createElement("iframe");
				f.setAttribute("src","about:blank");
				document.body.appendChild(f);
				try { f.contentWindow.stop(); }catch(err){}
				document.body.removeChild(f);
				
				this.ShowSizes();
			}
		}, 2, this);
	};
	
	app.GenerateCrushURL = function(url) {
		return "http://local.pngcrush.services.jasonmillerdesign.com/download/?name="+encodeURIComponent(this.currentName)+"&url="+encodeURIComponent(url);
	};
	
	app.getCrushedSize = function(url, callback, context) {
		if(!url) {
			if(this.currentURL)
				url = this.currentURL;
			else
				return false;
		}
		
		function c() {
			var size = -1;
			if(!this.error && (this.data+"").replace(/[^0-9\.]*/mgi,'')==this.data+"") {
				size = parseInt(this.data);
			}
			this._crushedCallback.apply(this._crushedContext, [size,url]);
		}
		
		var serv = "http://jasonmillerdesign.com/services/pngcrush/size/?url="+encodeURIComponent(url);
		var l = HttpRequest.create(serv, null, c, c);
		l._crushedContext = context || this;
		l._crushedCallback = callback || function(){};
		l.send();
		return l;
	};
	
	app.ShowSizes = function(size, crushed) {
		if(this.crushedSizeLoader) {
			this.crushedSizeLoader.abort();
		}
		
		size = size || this.currentSize;
		if(!size) {
			return false;
		}
		
		if(!crushed) {
			this.showSizesSize = size;
			this.crushedSizeLoader = this.getCrushedSize(null, function(r){ this.ShowSizes(this.crushedSizesSize, r); }, this);
			return true;
		}
		
		if(crushed==size)
			var compression = "no compression";
		else if(crushed<size)
			var compression = Math.round((size-crushed)/crushed*1000)/10 + "% smaller";
		else
			var compression = Math.round((crushed-size)/size*1000)/10 + "% larger";
		
		this.status.sizeInfo.setText( this.friendlySize(size) + " ➔ " + this.friendlySize(crushed) + " ("+compression+")" );
		this.status.sizeInfo.setX( (this.getWidth()-app.status.sizeInfo.getWidth())/2 );
		
		return true;
	};
	
	
	app.SaveToDisk = function() {
		if(this.loading===true || !this.currentCrushedURL) {
			return false;
		}
		this.downloadFile(this.currentCrushedURL);
	};
	
	app.downloadFile = function(url) {
		var ifr = document.createElement("iframe");
		ifr.style.cssText = "position:absolute; left:0; top:-999em; display:block; width:1px; height:1px; border:none; visibility:visible;";
		ifr.setAttribute("onload", "var me=this; window.setTimeout(function(){me.parentNode.removeChild(me);},500);");
		ifr.setAttribute("onerror", "alert('There was an error downloading the file.'); var me=this; window.setTimeout(function(){me.parentNode.removeChild(me);},500);");
		ifr.setAttribute("src", url);
		document.body.appendChild(ifr);
	};
	
	
	app.friendlySize = function(bytes) {
		function number_format(num){
			num = Math.round(num*100)/100;
			while( num+"" != (num=(num+"").replace(/([0-9]{1,3})([0-9]{3})($|\,)/mgi,'$1,$2')) ){}
			return num;
		}
		
		if(bytes>1500000000) {
			return number_format(bytes/1000000000) + " gb";
		}
		if(bytes>1500000) {
			return number_format(bytes/1000000) + " mb";
		}
		else if(bytes>1500) {
			return number_format(bytes/1000) + " kb";
		}
		return bytes+" b";
	};
	
	
	
	
	app.init();
	
	function ajaxUploader(appendTo, action, postData, onSubmit, onComplete) {
		if(appendTo && appendTo.constructor==Object && appendTo.parent) {
			var u = appendTo;
		}
		else {
			var u = {
				parent	: (appendTo || document.body),
				action	: (action || "./"),
				post	: (postData || {}),
				submit	: (onSubmit || function(){}),
				complete: (onComplete || function(){})
			};
		}
		
		if(!u.ip) {
			var s = document.createElement("script");
			
			window.jsonuploadclientipcallback = function(ip) {
				s.parentNode.removeChild(s);
				delete s;
				u.ip = ip;
				ajaxUploader(u);
			}
			
			s.setAttribute("src", "http://services.jasonmillerdesign.com/clientip/?format=jsonp&callback=jsonuploadclientipcallback");
			document.body.appendChild(s);
			
			return true;
		}
		
		u.action = "http://"+u.ip+".jsonupload.services.jasonmillerdesign.com/";
		
		u.frame = document.createElement("iframe");
		u.frame._u = u;
		u.frame.style.cssText = "display:block; position:absolute; left:0; top:0; width:100%; height:100%; z-index:998; cursor:pointer; opacity:0.01; filter:alpha(opacity=1); overflow:hidden; visibility:visible;";
		u.frame.setAttribute("frameBorder","0");
		u.frame.setAttribute("scrolling","no");
		u.frame.setAttribute("border","0");
		u.frame.setAttribute("src","about:blank");
		u.parent.appendChild(u.frame);
		try { u.frame.contentWindow.stop(); }catch(err){}
		
		function paramFormat(t) {
			return (t+"").replace(/</mgi,'&lt;').replace(/>/mgi,'&gt;').replace(/"/mgi,'&quot;');
		}
		
		if(u.post && u.post.constructor==String) {
			var newpost = {};
			var split = u.post.split("&");
			var param;
			for(var x=0; x<split.length; x++) {
				param = split[x].substring(0,split[x].indexOf("="));
				newpost[param] = split[x].substring(param.length+1, split[x].length);
			}
			u.post = newpost;
			delete param;
			delete split;
		}
		if(!u.post.jsonupload_receiver_url)
			u.post.jsonupload_receiver_url = location.href.substring(0, location.href.lastIndexOf("/")+1) + "receiver.html";
		
		var post_fields = "";
		var paramValue;
		for(var paramName in u.post) {
			paramValue = u.post[paramName];
			if(paramValue===true || paramValue===false)
				paramValue = paramValue===true?"true":"false";
			post_fields += "<input type=\"hidden\" name=\""+paramFormat(paramName)+"\" value=\""+paramFormat(paramValue)+"\" style=\"position:absolute;left:0;top:-999em;display:block;width:1px;height:1px;font-size:1px;z-index:1;\" />";
		}
		
		u.action += (u.action.indexOf("?")>-1?"&":"?") + "jsonupload_rndid="+(new Date()).getTime()+""+Math.round(Math.random()*99999);
		
		u.frame.contentWindow.document.open();
		u.frame.contentWindow.document.write("<html><head><style type=\"text/css\">form,input,div{font:90px/1.21 arial,helvetica,sans;overflow:hidden;cursor:pointer;background:none;display:block;position:absolute;right:0;left:0;bottom:0;top:0;width:100%;height:100%;min-height:100%;min-width:100%;margin:0;padding:0;border:0;text-align:center;z-index:500;}html,body{margin:0;padding:0;height:100%;width:100%;min-height:100%;min-width:100%;cursor:pointer;}<\/style><\/head><body><form id=\"frm1\" enctype=\"multipart/form-data\" action=\""+paramFormat(u.action)+"\" method=\"POST\">"+post_fields+"<input style=\"display:inline;height:auto;width:auto;position:absolute;left:auto;bottom:auto;right:-3px;top:-3px;font-size:150%;margin:0;padding:0;z-index:999;\" type=\"file\" id=\"jsonupload_file\" name=\"jsonupload_file\" onmouseover=\"_messenger('mouseover');\" onmouseout=\"_messenger('mouseout');\" onmousedown=\"_messenger('mousedown');\" onmouseup=\"_messenger('mouseup');\" onchange=\"_messenger('submit');stop();parentNode.submit();\" \/><\/form><\/body><\/html>");
		u.frame.contentWindow.document.close();
		
		u.frame._messenger = u.frame.contentWindow._messenger = u.frame.contentWindow.document._messenger = function(type) {
			var pn = u.parent;
			while((!pn.parentControl || (pn.parentControl.baseArea && pn.parentControl.baseArea!=pn)) && pn!=document)
				pn = pn.parentNode;
			if(!pn.parentControl || pn.parentControl.baseArea!=pn)
				pn = null;
			if(type=="mouseover") {
				if(pn.onmouseover)
					pn.onmouseover({type:'mouseover'});
			}
			if(type=="mouseout" || type=="submit") {
				if(pn.onmouseout)
					pn.onmouseout({type:'mouseout'});
			}
			if(type=="mousedown") {
				if(pn.onmousedown)
					pn.onmousedown({type:'mousedown'});
			}
			if(type=="mouseup") {
				if(pn.onmouseup)
					pn.onmouseup({type:'mouseup'});
				if(pn.onmouseout)
					pn.onmouseout({type:'mouseout'});
			}
			if(type=="submit" && u.submit && u.submit.constructor && u.submit.constructor==Function) {
				u._waiter = ApplicationFramework.RegisterTimer(function() {
					var worked = false;
					try {
						worked = this.frame.contentWindow && this.frame.contentWindow.location && this.frame.contentWindow.location.href && this.frame.contentWindow.location.href.match(/\?jsonupload_callback=/);
					} catch(err) {
						worked = false;
					}
					if(worked) {
						var objStr = decodeURIComponent( this.frame.contentWindow.location.href.substring(this.frame.contentWindow.location.href.indexOf("?jsonupload_callback=")+21,this.frame.contentWindow.location.href.length) );
						var data;
						try {
							data = eval('('+objStr+')');
						} catch(err) {
							data = {result:false,message:'Parse error.'};
						}
						this.frame._completed(data);
						ApplicationFramework.UnregisterTimer(this._waiter);
					}
				}, 2, u);
				u.submit();
			}
		};
		
		u.frame._completed = function(data) {
			if(u.complete && u.complete.constructor && u.complete.constructor==Function) {
				u.complete(data);
			}
			// re-create the uploader
			try { u.frame.contentWindow.stop(); }catch(err){}
			u.frame.parentNode.removeChild(u.frame);
			delete u.frame;
			ajaxUploader(u);
		};
		
		return true;
	}
	
	ajaxUploader(app.toolbar.openFromDisk._overlay, upload.action, upload.post, upload.submit, upload.complete);
	
	
	
	
	
	window.setInterval(function() {
		document.title = app.getTitle();
	}, 500);
	
	
	
	
	
	
	
	
	
	
	// sharing, etc:
	window.sharing = new (function() {
		this.url = "http://jasonmillerdesign.com/apps/minipng/";
		this.title = "miniPNG | Web-based PNG Compression / PNG Crusher";
		
		
		this.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 + "";
			}
		);
		
		this.show = 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(){ sharing._animateSharing(); }, 20);
		};
		this.hide = function() {
			this.show(-1);
		};
		this._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 );
			}
		};
		this._isFirstSharingShow = true;
		
		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 , 40);
		this.sharingCover.onclick = this.sharingCloser.onclick = function(e) {
			if(!e)e=window.event;
			sharing.hide();
			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, '', this.url, this.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;
				sharing.sharingWrap.appendChild(a);
				sharing.sharingWrap.style.height = a.offsetHeight+"px";
				sharing.sharingWrap.style.width = a.offsetWidth+"px";
			}
		},100);
	})();
	
	
	app.welcomeExplainer.setPosition( app.getWidth()/2-200 , 0 );
	
	
	document.getElementById("loading_indicator").style.display = "none";
};












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;

