<?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" 
		 width="100%" height="100%"
		 show="vwSignIn_ShowHandler(event);">
	
	<s:layout>
		<s:BasicLayout/>
	</s:layout>

	<fx:Script>
		<![CDATA[
			import org.umbraco.desktopmediauploader.events.*;
			import org.umbraco.desktopmediauploader.net.*;
			import org.umbraco.desktopmediauploader.util.*;
			
			import mx.controls.Alert;
			import mx.managers.*;
			import mx.events.FlexEvent;
			

			public function init():void
			{
				NativeApplication.nativeApplication.addEventListener(BrowserInvokeEvent.BROWSER_INVOKE, app_BrowserInvoke);
				
				reset();
				
				if(chkAutoSignIn.selected)
				{
					doSignIn();
				}
			}
			
			protected function vwSignIn_ShowHandler(event:FlexEvent):void
			{
				reset();
			}
			
			protected function app_BrowserInvoke(e:BrowserInvokeEvent):void
			{
				var encLaunchArg:String = unescape(e.arguments[0]);
				var launchArg:String = Base64.decodeToString(encLaunchArg);
				var launchArgs:Array = launchArg.split(";");
				
				Model.url = parseUrl(launchArgs[0]);
				Model.username = launchArgs[1];
				Model.password = "";
				Model.ticket = launchArgs[2];
				
				// Ok, time to hit the server
				CursorManager.setBusyCursor();
				this.enabled = false;
				
				// Authenticate credentials
				// NB: As every request authenticates anyway, just load config
				// and if it fails, assume login was invalid
				DmuRequest.makeRequest(DmuRequestAction.CONFIG,
					configRequest_Success,
					configRequest_Error);
			}
			
			protected function reset():void
			{
				chkRememberMe.selected = (getEncryptedValue("dmu_rememberme") == "true");
				chkRememberPassword.selected = (getEncryptedValue("dmu_rememberpassword") == "true");
				chkAutoSignIn.selected = (getEncryptedValue("dmu_autosignin") == "true");
				
				if (chkRememberMe.selected)
				{
					txtUrl.text = getEncryptedValue("dmu_url");
					txtUsername.text = getEncryptedValue("dmu_username");
					if (chkRememberPassword.selected)
					{
						txtPassword.text = getEncryptedValue("dmu_password");
					}
				}
			}
			
			protected function txtPassword_Enter(event:Event):void
			{
				doSignIn();
			}
			
			protected function btnSignIn_clickHandler(event:MouseEvent=null):void
			{
				doSignIn();
			}
			
			protected function configRequest_Success(event:DmuRequestEvent):void
			{
				this.enabled = true;
				CursorManager.removeBusyCursor();
				
				var xml:XML = event.result;
				
				// Store config
				Model.displayName = xml.displayName;
				Model.umbracoPath = xml.umbracoPath;
				Model.maxRequestLength = Number(xml.maxRequestLength);

				// Remember login
				if(!Model.ticket || Model.ticket == "")
				{
					setEncryptedValue("dmu_url", (chkRememberMe.selected)? Model.url : null);
					setEncryptedValue("dmu_username", (chkRememberMe.selected)? Model.username : null);
					setEncryptedValue("dmu_password", (chkRememberMe.selected && chkRememberPassword.selected) ? Model.password : null);
					setEncryptedValue("dmu_rememberme", chkRememberMe.selected.toString());
					setEncryptedValue("dmu_rememberpassword", chkRememberPassword.selected.toString());
					setEncryptedValue("dmu_autosignin", chkAutoSignIn.selected.toString());
				}
				
				dispatchEvent(new SignedInEvent(SignedInEvent.SIGNED_IN));
			}
			
			protected function configRequest_Error(event:Event):void
			{
				this.enabled = true;
				CursorManager.removeBusyCursor();
				
				Alert.show("Invalid login", "Ooops!");
			}
			
			private function doSignIn():void
			{
				Model.url = parseUrl(txtUrl.text);
				Model.username = txtUsername.text;
				Model.password = txtPassword.text;
				Model.ticket = "";
				
				// Ok, time to hit the server
				CursorManager.setBusyCursor();
				this.enabled = false;
				
				// Authenticate credentials
				// NB: As every request authenticates anyway, just load config
				// and if it fails, assume login was invalid
				DmuRequest.makeRequest(DmuRequestAction.CONFIG,
					configRequest_Success,
					configRequest_Error);
			}
			
			private function parseUrl(url:String):String
			{
				var urlPattern:RegExp = /^((?P<scheme>https?):\/\/)(?P<hostname>[^:\/\s]+)(?P<port>:([^\/]*))?((?P<path>(\/\w+)*\/)(?P<filename>[-\w.]+[^#?\s]*)?(?P<query>\?([^#]*))?(?P<fragment>#(.*))?)?$/gi;
				var result:Array = urlPattern.exec(url.toLowerCase());
				if (result != null && result.length > 0)
				{
					var parsedUrl:String = result.scheme + "://" + result.hostname + result.port + result.path + result.filename;
					
					while(parsedUrl.substr(parsedUrl.length - 1) == "/")
					{
						parsedUrl = parsedUrl.substr(0, parsedUrl.length - 1);
					}
					
					return parsedUrl;
				}
				return url;
			}
			
			private function setEncryptedValue(key:String, value:String):void
			{
				if (value != null)
				{
					var data:ByteArray = new ByteArray();
					data.writeUTFBytes(value);
					EncryptedLocalStore.setItem(key, data);
				}
				else
				{
					EncryptedLocalStore.removeItem(key);
				}
			}
			
			private function getEncryptedValue(key:String):String
			{
				var data:ByteArray = EncryptedLocalStore.getItem(key);
				return (data != null) ? data.readUTFBytes(data.length) : null;
			}

		]]>
	</fx:Script>

	<fx:Metadata>
		[Event(name="signedIn", type="org.umbraco.desktopmediauploader.events.SignedInEvent")]
	</fx:Metadata>
	
	<fx:Declarations>
		<!-- Place non-visual elements (e.g., services, value objects) here -->
	</fx:Declarations>
	
	<mx:Image horizontalCenter="0" source="@Embed('assets/logo.png')" verticalCenter="-145"/>
	<s:VGroup id="grpSignInForm" height="200" bottom="105" left="25" right="25">
		<s:Label text="URL" fontWeight="bold"/>
		<s:TextInput width="100%" id="txtUrl" text="@{Model.url}"/>
		<s:Label text="Username" fontWeight="bold"/>
		<s:TextInput width="100%" id="txtUsername" text="@{Model.username}"/>
		<s:Label text="Password" fontWeight="bold"/>
		<s:TextInput width="100%" id="txtPassword" displayAsPassword="true" text="@{Model.password}" enter="txtPassword_Enter(event)" />
		<s:CheckBox label="Remember Me" id="chkRememberMe" change="(!chkRememberMe.selected) ? chkRememberPassword.selected = chkAutoSignIn.selected = false : null"/>
		<s:CheckBox label="Remember Password" id="chkRememberPassword" enabled="{chkRememberMe.selected}" change="(!chkRememberPassword.selected) ? chkAutoSignIn.selected = false : null"/>
		<s:CheckBox label="Sign In Automaticaly" id="chkAutoSignIn" enabled="{chkRememberPassword.selected}"/>
	</s:VGroup>
	<mx:Button label="Sign In" bottom="25" id="btnSignIn" click="btnSignIn_clickHandler(event)" left="25" right="25" height="35" useHandCursor="true" buttonMode="true" styleName=""/>
	
</s:Group>
