<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009" 
		 xmlns:s="library://ns.adobe.com/flex/spark" 
		 xmlns:mx="library://ns.adobe.com/flex/mx" 
		 xmlns:components="org.umbraco.desktopmediauploader.components.*"
		 width="100%" height="100%" 
		 creationComplete="vwUpload_CreationCompleteHandler(event)" 
		 show="vwUpload_ShowHandler(event);">
	
	<s:layout>
		<s:BasicLayout/>
	</s:layout>
	
	<fx:Script>
		<![CDATA[
			import org.umbraco.desktopmediauploader.components.*;
			import org.umbraco.desktopmediauploader.events.*;
			import org.umbraco.desktopmediauploader.net.*;
			import org.umbraco.desktopmediauploader.util.*;
			
			import flash.desktop.*;
			import flash.events.*;
			import flash.filesystem.File;
			import flash.net.*;
			
			import mx.collections.Sort;
			import mx.collections.SortField;
			import mx.controls.Alert;
			import mx.controls.Menu;
			import mx.core.ScrollPolicy;
			import mx.events.FlexEvent;
			import mx.managers.*;
			
			import spark.events.IndexChangeEvent;
			
			[Bindable] public var currentUploadItem:UploadItem;
			[Bindable] public var uploadItems:ArrayCollection;
			
			[Bindable] private var uploading:Boolean = false;
			
			protected function vwUpload_CreationCompleteHandler(event:FlexEvent):void
			{
				uploadItems = new ArrayCollection();
				
				addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER, vwUpload_DragEnter);
				addEventListener(NativeDragEvent.NATIVE_DRAG_DROP, vwUpload_DragDrop);
				
				dmuStatus.addEventListener(Event.CANCEL, dmuStatus_Cancel);
			}
			
			protected function vwUpload_ShowHandler(event:FlexEvent):void
			{
				reset();
			}
			
			private function vwUpload_DragEnter(e:NativeDragEvent) :void
			{
				var valid:Boolean = false;
				if(e.clipboard.hasFormat(ClipboardFormats.FILE_LIST_FORMAT))
				{
					// Only allow drop if at least 1 file is valid
					var files:Array = e.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
					for each (var f:File in files)
					{
						if (isValidFile(f))
						{
							valid = true;
							break;
						}
					}

					if (valid)
						NativeDragManager.acceptDragDrop(this);
				}
			}
			
			private function vwUpload_DragDrop(e:NativeDragEvent) :void
			{
				var files:Array = e.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
				
				addFilesToQueue(files);
				
				// Sort alphabeticlly
				var sf:SortField = new SortField("fullPath", true);
				var s:Sort = new Sort();
				s.fields = [sf];
				
				uploadItems.sort = s;
				uploadItems.refresh();
				
				for(var i:int = 0; i < uploadItems.length; i++)
				{
					grpUploadItemContainer.addElement(uploadItems[i]);
				}
			}
			
			private function reset():void
			{
				Model.currentFolder = undefined;
				Model.folderId = undefined;
				Model.folderName = undefined;
				Model.folderPath = undefined;
				
				uploading = false;
				currentUploadItem == null;
				
				dmuStatus_Cancel();
			}
			
			private function isValidFile(file:File, path:String = ""):Boolean
			{
				var queued:Boolean = false;
				
				var i:int = uploadItems.length;
				while(i--)
				{
					var uploadItem:UploadItem = uploadItems[i] as UploadItem;
					if (uploadItem != null && uploadItem.file.name == file.name && uploadItem.path == path && uploadItem.file.size == file.size)
					{
						queued = true;
						break;
					}
				}
				
				// TODO: Handle .lnk files?
				// TODO: What to do with zip files?
				return (!file.isSymbolicLink && 
					!file.isPackage && 
					!file.isHidden && 
					!queued &&
					file.size <= (Model.maxRequestLength * 1024));
			}
			
			private function addFilesToQueue(files:Array, path:String = ""):void
			{
				for each (var f:File in files)
				{
					if(f.isDirectory)
					{
						addFilesToQueue(f.getDirectoryListing(), path + "/" + f.name)
					} 
					else if (isValidFile(f, path))
					{
						addFileToQueue(FileReference(f), path);
					}
				}
			}
			
			private function addFileToQueue(file:FileReference, path:String):void
			{
				var uploadItem:UploadItem = new UploadItem();
				uploadItem.file = file;
				uploadItem.path = path;
				uploadItem.addEventListener(Event.COMPLETE, uploadItem_Complete);
				uploadItem.addEventListener(Event.CANCEL, uploadItem_Cancel);
				uploadItem.addEventListener(HTTPStatusEvent.HTTP_STATUS, uploadItem_Error);
				uploadItem.addEventListener(IOErrorEvent.IO_ERROR, uploadItem_Error);
				uploadItem.addEventListener(SecurityErrorEvent.SECURITY_ERROR, uploadItem_Error);
				
				grpUploadItemContainer.addElement(uploadItem);
				uploadItems.addItem(uploadItem);
			}
			
			protected function ddlConnectedTo_Close(e:Event):void
			{
				var oldIndex:Number = ddlConnectedTo.selectedIndex;
				ddlConnectedTo.selectedIndex = -1;
				
				if (oldIndex >= 0)
				{
					switch(ddlConnectedTo.dataProvider[oldIndex])
					{
						case "Launch Site":
							navigateToURL(new URLRequest(Model.url));
							break;
						case "Launch Admin":
							navigateToURL(new URLRequest(Model.url + Model.umbracoPath + "/"));
							break;
					}
				}
			}
			
			protected function btnSignOut_Click(e:Event):void
			{
				if (uploading)
					Alert.show("Unable to sign out whilst uploading files.", "Ooops!");
				else 
					dispatchEvent(new SignedOutEvent(SignedOutEvent.SIGNED_OUT));
			}
			
			protected function uploadItem_Complete(e:Event):void
			{
				uploadItem_Cancel(e);
				
				uploading = false;
				currentUploadItem == null;
				
				if (uploadItems.length > 0)
					btnUpload_Click();
				else
					Alert.show("Upload complete.", "Woo hoo!");
			}
			
			protected function uploadItem_Cancel(e:Event):void
			{
				var uploadItem:UploadItem = e.target as UploadItem;
				
				var i:uint = uploadItems.length;
				while(i--)
				{
					var uploadItem2:UploadItem = uploadItems[i] as UploadItem;
					if(uploadItem2.file.name == uploadItem.file.name && uploadItem2.path == uploadItem.path)
					{
						grpUploadItemContainer.removeElement(uploadItem);
						uploadItems.removeItemAt(i);
						break;
					}
				}
			}
			
			protected function uploadItem_Error(e:Event):void
			{
				// TODO: Move item to bottom?
			}

			protected function dmuStatus_Cancel(event:Event = null):void
			{
				var i:uint = uploadItems.length;
				while(i--)
				{
					uploadItems[i].cancel();
				}
			}

			protected function btnUploadTo_Click(event:MouseEvent):void
			{
				var win:FolderPickerDialog = PopUpManager.createPopUp(this, FolderPickerDialog, true) as FolderPickerDialog;

				PopUpManager.centerPopUp(win);
			}


			protected function btnUpload_Click(event:MouseEvent = null):void
			{
				var uploadItem:UploadItem;
				var i:int;
				
				if (!uploading)
				{
					uploading = false;
					currentUploadItem = null;
					
					for(i = 0; i < uploadItems.length; i++)
					{
						uploadItem = uploadItems[i] as UploadItem;
						if (!uploadItem.uploaded)
						{
							currentUploadItem = uploadItem;
							currentUploadItem.upload();
							uploading = true;
							break;
						}
					}
				}
				else
				{
					for(i = 0; i < uploadItems.length; i++)
					{
						uploadItem = uploadItems[i] as UploadItem;
						if (!uploadItem.uploaded)
						{
							uploadItem.pause();
						}
					}
					
					uploading = false;
					currentUploadItem = null;
				}
			}

		]]>
	</fx:Script>
	
	<fx:Metadata>
		[Event(name="signedOut", type="org.umbraco.desktopmediauploader.events.SignedOutEvent")]
	</fx:Metadata>
	
	<fx:Declarations>
		<fx:Array id="uploadMenuItems">
			<fx:Object label="Clear Queue" />
			<fx:Object type="separator" />
			<fx:Object label="Overwrite existing files" type="check" />
			<fx:Object label="Auto extract zip files" type="check" />
		</fx:Array>
	</fx:Declarations>
	
	<s:BorderContainer top="0" left="0" right="0" height="70" styleName="header">
		<mx:Image source="@Embed('assets/icon-48.png')" x="10" y="10" />
		<mx:Label id="lblName" text="{Model.displayName}" left="64" y="10" right="50" truncateToFit="true" minWidth="0" />
		<s:DropDownList id="ddlConnectedTo" prompt="{Model.url}" close="ddlConnectedTo_Close(event)" x="65" y="33" typicalItem="{Model.url}" maxWidth="{StageHelper.stageWidth - 90}" open="ddlConnectedTo.scroller.setStyle('horizontalScrollPolicy', ScrollPolicy.OFF);" useHandCursor="true" buttonMode="true">
			<mx:ArrayCollection>
				<fx:String>Launch Site</fx:String>
				<fx:String>Launch Admin</fx:String>
			</mx:ArrayCollection>
		</s:DropDownList>
		<s:Button id="btnSignOut" width="13" height="15" top="11" right="25" useHandCursor="true" buttonMode="true" styleName="signOutButton" click="btnSignOut_Click(event)" />
		
	</s:BorderContainer>
	
	<s:VGroup top="90" left="25" right="25" gap="5">
		<s:Label text="Upload files to..."/>
		<s:Button id="btnUploadTo" label="{(Model.folderPath) ? Model.folderPath.replace(/\//g, ' › ') : 'Please select...'}"  width="100%" click="btnUploadTo_Click(event)" creationComplete="btnUploadTo.labelDisplay.setStyle('textAlign','left')"  height="25" useHandCursor="true" buttonMode="true" />
	</s:VGroup>
	
	<s:BorderContainer top="150" left="25" right="25" bottom="100" borderColor="#CCCCCC" backgroundColor="#FFFFFF">
		<s:Scroller width="100%" height="100%">
			<s:Group id="grpUploadItemContainer">
				<s:layout>
					<s:VerticalLayout paddingLeft="5" paddingRight="5" paddingTop="5" paddingBottom="5" gap="5"/>
				</s:layout>
				<components:StatusItem id="dmuStatus" visible="{uploadItems.length &gt; 0}" includeInLayout="{uploadItems.length &gt; 0}" totalItems="{uploadItems.length}" />
				<s:Label text="Drag Files and Folders Here To Upload" verticalAlign="middle" textAlign="center" 
						 width="100%" height="100%" fontSize="20" color="#CCCCCC" id="lblInstructions" 
						 paddingLeft="20" paddingRight="20" paddingTop="20" paddingBottom="20"
						 visible="{uploadItems.length == 0}" includeInLayout="{uploadItems.length == 0}"/>
			</s:Group>
		</s:Scroller>
	</s:BorderContainer>
	<s:CheckBox x="25" bottom="73" label="Overwrite existing files with the same filename?" id="chkReplace" selected="@{Model.replaceExisting}"  color="#333333"/>
	<mx:Button id="btnUpload" label="{!uploading ? 'Upload' : 'Cancel'}" useHandCursor="{btnUpload.enabled}" buttonMode="{btnUpload.enabled}" bottom="25" enabled="{uploadItems.length > 0 &amp;&amp; Model.folderId}" styleName="orange" height="35" left="25" right="25" click="btnUpload_Click(event)"/>
</s:Group>
