Ext.namespace("dlr.cmp.login");
dlr.cmp.login.loginWindow = function(cfg){
	// ------------------------------------------------
	// private properties
	// ------------------------------------------------
	var that = this;
	var windowCfg = {
		closable: false,
		resizable: false,
		draggable: false,
		constrain: true,
		layout: "anchor",
		width: Ext.getBody().getWidth() / 2,
		height: Ext.getBody().getHeight() / 1.3,
		items:[{
			xtype: "panel",
			html: "&nbsp;<img src='assets/images/logo-sm.png' />",
			bodyStyle: "padding-top:8px;background:#f4f7fc url(assets/images/blue-grad-sm.png) bottom repeat-x;",
			height: 45,
			frame: false,
			border: false
		},{
			xtype: "tabpanel",
			activeTab: 1,
			anchor: "100% -30",
			frame: false,
			border: false,
			items:[{
				xtype: "form",
				layout: "form",
				title: "Login",
				labelWidth: 100,
				defaultType: 'textfield',
				defaults: {
					width: "100%"
				},
				bodyStyle: "padding:20px;background:transparent url(assets/images/grass.gif) bottom repeat-x;",
				autoScroll: true,
				keys: [{
					key: [Ext.EventObject.ENTER],
					fn: login
				}],
				items:[{
						xtype: "panel",
						anchor: "100%",
						html: "<h1>Let\'s Get Started!</h1><p>To login you will need to <a href='javascript:layout.getLoginWindow().tabTo(\"register\");'>register</a> with Fuisti and note that you do not use your Flickr login.</p>",
						bodyStyle: "margin-bottom:10px;padding:20px;background-color:#fbffcc;",
						frame: false,
						border: false
					},{
						fieldLabel: 'User Name',
						name: 'userName',
						allowBlank: false
					},{
						fieldLabel: 'Password',
						name: 'password',
						allowBlank: false,
						inputType: "password"
					},{
						xtype: "panel",
						html: "<br />Forgot your password? <a href='javascript:layout.getLoginWindow().getPw();'>Click here to get it.</a><br />",
						frame: false,
						border: false,
						bodyStyle: "background:transparent;"
					}]
			},{
				title: "About",
				bodyStyle: "padding:20px;background:transparent url(assets/images/grass.gif) bottom repeat-x;",
				autoScroll: true,
				items:[{
					xtype: "panel",
					anchor: "100%",
					html: "<h1>What is Fuisti?</h1><p>Fuisti is a project created to allow for batch organizing and downloading of public domain Flickr photos.</p>",
					bodyStyle: "padding:20px;background-color:#fbffcc;",
					autoScroll: true,
					frame: false,
					border: false
				},{
					xtype: "panel",
					anchor: "100%",
					html: "<p><img src='http://l.yimg.com/g/images/flickr_logo_gamma.gif.v59899.14' align='right' /> This project came about from the want to download large quantities of photos from Flickr, as well as having the ability to back-up your own photos. Flickr is an incredible new generation web based application that has re-defined how we use the internet to interact with photos, our own and others. If you aren't familiar with Flickr, <a href='http://www.flickr.com/' target='_blank'>I suggest you check it out</a>.</p>",
					bodyStyle: "margin-bottom:10px;padding:10px 0 20px 0;background:transparent;",
					autoScroll: true,
					frame: false,
					border: false
				},{
					xtype: "panel",
					anchor: "100%",
					html: "<p>If you are interested, go <a href='javascript:layout.getLoginWindow().tabTo(\"register\");'>register</a> and start downloading! For already existing members, <a href='javascript:layout.getLoginWindow().tabTo(\"login\");'>login!</a></p>",
					bodyStyle: "margin-bottom:10px;padding:0 0 20px 0;background:transparent;",
					autoScroll: true,
					frame: false,
					border: false
				}]
			},{
				xtype: "form",
				layout: "form",
				id: "regForm",
				title: "Register",
				labelWidth: 100,
				defaultType: 'textfield',
				defaults: {
					width: "100%"
				},
				bodyStyle: "padding:20px;background:transparent url(assets/images/grass.gif) bottom repeat-x;",
				autoScroll: true,
				keys: [{
					key: [Ext.EventObject.ENTER],
					fn: register
				}],
				items:[{
						xtype: "panel",
						anchor: "100%",
						html: "<h1>Come Join the Party!</h1><p>We would love to have you join! Fuisti is currently in a pre-alpha stage and we are working to get the core functionality done. Feel free to play witht he tool and report any bugs. At the top right of tha application next to settings and logout, there is a report a bug tool - you are welcome to abuse it!</p>",
						bodyStyle: "margin-bottom:10px;padding:20px;background-color:#fbffcc;",
						frame: false,
						border: false
					},{
						fieldLabel: 'User Name',
						name: 'userName',
						allowBlank: false,
						listeners: {
							"change": function(fld, newVal, oldVal){
								if (newVal != oldVal){
									Ext.Ajax.request({
										url: 'loginHelper.cfc',
										success: (function(response, options){
											var response = Ext.decode(response.responseText);
											if (!response.status)
												fld.markInvalid("This User Name is Taken.");
										}),
										failure: (function(){
											alert("fail");
										}),
										params: {
											method: "userNameCheck",
											data: "{userName: '"+newVal+"'}"
										}
									});
								} // if
							} // end change fn
						},// end listeners
						validator: basicVal
					},{
						fieldLabel: 'Password',
						id: "regPassword",
						name: 'password',
						allowBlank: false,
						inputType: "password",
						validator: basicVal
					},{
						fieldLabel: 'Confirm Password',
						name: 'passwordConfirm',
						allowBlank: false,
						inputType: "password",
						listeners: {
							"change": function(fld, newVal, oldVal){
								if (Ext.getCmp("regForm").findById("regPassword").getValue() != newVal)
									fld.markInvalid("Passwords Do Not Match.");
							} // end change fn
						},// end listeners
						validator: basicVal
					},{
						fieldLabel: 'First Name',
						name: 'firstName',
						allowBlank: false
					},{
						fieldLabel: 'Last Name',
						name: 'lastName',
						allowBlank: false
					},{
						fieldLabel: 'Email',
						id: "regEmail",
						name: 'email',
						allowBlank: false,
						vtype: "email",
						vtypeText: "Please Enter a Valid Email Address."
					},{
						fieldLabel: 'Confirm Email',
						name: 'confirmEmail',
						allowBlank: false,
						listeners: {
							"change": function(fld, newVal, oldVal){
								if (Ext.getCmp("regForm").findById("regEmail").getValue() != newVal)
									fld.markInvalid("Emails Do Not Match.");
							} // end change fn
						},// end listeners
						vtype: "email",
						vtypeText: "Please Enter a Valid Email Address."
					},{
						xtype: "panel",
						html: "<br /><br />",
						frame: false,
						border: false,
						bodyStyle: "background:transparent;"
					}]
			}]
		}],
		buttons:[{
			text: "Login",
			handler: login
		},{
			text: "Contact Me @ joe@seemecreate.com",
			handler: function(){
				location.href = "mailto:joe@nicora.net?subject=I was at fuisti.com and..."
			}
		},{
			text: "Register",
			handler: register
		}]
	};
	var pwWin = null;
	// ------------------------------------------------
	// private functions
	// ------------------------------------------------
	function basicVal(val){
		var myRegxp = /^([a-zA-Z0-9_-]+)$/;
		var isVal = true;
		if(myRegxp.test(val) == false){
			isVal = "Only Letters and Numbers are Allowed.";
		}
		if (val.length < 3){
			isVal = "Must be More Than 3 Characters.";
		}
		return isVal;
	}; // end basicVal
	function login(){
		var form = getCmps().loginOwnerCtForm;
		var valid = validateLogin();
		var params = {method: "login"};
		var ldMsk = null;

		ldMsk = ldMsk || new Ext.LoadMask(getCmps().loginOwnerCt.body, {msg: "Authenticating Request..."});
		if (form.isValid()){
			ldMsk.show();
			params.data = Ext.encode(form.getValues());
			Ext.Ajax.request({
				url: 'loginHelper.cfc',
				success: (function(response, options){
					var response = Ext.decode(response.responseText);
					if (!response.status){
						Ext.Msg.show({
						   title:'Authentication Failed',
						   msg: response.message,
						   buttons: Ext.Msg.OK,
						   icon: Ext.MessageBox.ERROR
						});
						ldMsk.hide();
					}
					else{
						that.userStore.loadData(response.usersession);
						getStores(ldMsk);
					}
				}),
				failure: (function(){
					alert("fail");
					ldMsk.hide();
				}),
				params: params
			});
		}
	}; // end login
	function getStores(ldMsk){
		Ext.Ajax.request({
			url: 'loginHelper.cfc',
			params: {
				method: "getStores"
			},
			success: (function(response, options){
				var response = Ext.decode(response.responseText);
				layout.getQueueStore().loadData(response.queues);
				layout.getQueueItemStore().loadData(response.queueitems);
				ldMsk.hide();
				that.hide();
				that.viewport.items.get(0).add(that.workSpacePanel);
				that.viewport.doLayout();
			}),
			failure: (function(){
				alert("fail");
			})
		});
	}; // end getStores
	function register(){
		var form = getCmps().regOwnerCtForm;
		var params = {method: "reg"};
		var ldMsk = null;

		ldMsk = ldMsk || new Ext.LoadMask(getCmps().regOwnerCt.body, {msg: "Registering..."});
		if (form.isValid()){
			ldMsk.show();
			params.data = Ext.encode(form.getValues());
			Ext.Ajax.request({
				url: 'loginHelper.cfc',
				success: (function(response, options){
					var response = Ext.decode(response.responseText);
					if (!response.status){
						Ext.Msg.show({
						   title:'Authentication Failed',
						   msg: response.message,
						   buttons: Ext.Msg.OK,
						   icon: Ext.MessageBox.ERROR
						});
						ldMsk.hide();
					}
					else{
						//_d(response.usersession);
						that.userStore.loadData(response.usersession);
						getStores(ldMsk);
						ldMsk.hide();
						that.hide();
						that.viewport.items.get(0).add(that.workSpacePanel);
						that.viewport.doLayout();
					}
				}),
				failure: (function(){
					alert("fail");
					ldMsk.hide();
				}),
				params: params
			});
		}
	}; // end register
	function validateLogin(){
		var form = getCmps().loginOwnerCtForm;
		var valid = true;

		if (form.getValues().userName.length < 1){
			valid = false;
			form.markInvalid({"userName": "Please enter a User Name."});
		}
		if (form.getValues().password.length < 1){
			valid = false;
			form.markInvalid({"password": "Please enter a password."});
		}
		return valid;
	}; // end validateLogin
	function getCmps(){
		return {
			tabPanel: that.items.get(1),
			loginOwnerCt: that.items.get(1).items.get(0),
			loginOwnerCtForm: that.items.get(1).items.get(0).getForm(),
			regOwnerCt: that.items.get(1).items.get(2),
			regOwnerCtForm: that.items.get(1).items.get(2).getForm(),
			loginBtn: that.buttons[0],
			contactBtn: that.buttons[1],
			registerBtn: that.buttons[2]
		};
	}; // end getCmps
	function resize(){
		if (that.isVisible()){
			that.setSize(Ext.getBody().getWidth() / 2, Ext.getBody().getHeight() / 1.3);
			that.center();
		}
	}; // end resize
	function onTabChange(tabPanel, tab){
		if (tab.title == "Login"){
			getCmps().loginBtn.show();
			getCmps().contactBtn.hide();
			getCmps().registerBtn.hide();
		}
		if (tab.title == "About"){
			getCmps().loginBtn.hide();
			getCmps().contactBtn.show();
			getCmps().registerBtn.hide();
		}
		if (tab.title == "Register"){
			getCmps().loginBtn.hide();
			getCmps().contactBtn.hide();
			getCmps().registerBtn.show();
		}
	}; // end onTabChange
	// ------------------------------------------------
	// public properties
	// ------------------------------------------------
	// ------------------------------------------------
	// public methods
	// ------------------------------------------------
	this.tabTo = function(which){
		var tabPanel = getCmps().tabPanel;
		switch(which){
			case "login" : tabPanel.activate(0);
				break;
			case "about" : tabPanel.activate(1);
				break;
			case "register" : tabPanel.activate(2);
				break;
		}
	}; // end tabTo
	this.getPw = function(){
		pwWin = pwWin || new Ext.Window({
			closable: false,
			resizable: false,
			draggable: false,
			constrain: true,
			modal: true,
			layout: "anchor",
			width: 275,
			height: 150,
			title: "What\'s My Password Again?",
			items:[{
				xtype: "panel",
				bodyStyle: "padding:10px;",
				html: "Enter the email address you used to sign up with.",
				frame: false,
				border: false
			},{
				xtype: "form",
				layout: "form",
				labelWidth: 70,
				anchor: "100% 0",
				defaultType: 'textfield',
				frame: false,
				border: false,
				defaults: {
					width: "100%"
				},
				bodyStyle: "padding:10px;",
				autoScroll: true,
				items:[{
					fieldLabel: "Email",
					name: "email",
					allowBlank: false,
					vtype: "email",
					vtypeText: "Please Enter a Valid Email Address."

				}]
			}],
			buttons:[{
				text: "Get Password",
				handler: (function(){
					var form = pwWin.items.get(1).getForm();
					var params = {method: "getPw"};
					var ldMsk = null;

					ldMsk = ldMsk || new Ext.LoadMask(pwWin.body, {msg: "Getting Password..."});
					if (form.isValid()){
						ldMsk.show();
						params.data = Ext.encode(form.getValues());
						Ext.Ajax.request({
							url: 'loginHelper.cfc',
							params: params,
							success: (function(response, options){
								var response = Ext.decode(response.responseText);
								Ext.Msg.alert((response.status ? "Yay!" : "Oops!"), response.message);
								ldMsk.hide();
							}),
							failure: (function(){
								alert("fail");
								ldMsk.hide();
							})
						});
					}
				})
			},{
				text: "Cancel",
				handler: (function(){pwWin.hide();})
			}]
		});
		pwWin.show();
	}; // end getPw
	// ------------------------------------------------
	// constructor code
	// ------------------------------------------------
	Ext.apply(this, cfg);
	// apply private cfgs
	Ext.apply(this, windowCfg);
	dlr.cmp.login.loginWindow.superclass.constructor.call(this, cfg);
	// events
	this.viewport.on("resize", resize);
	getCmps().tabPanel.on("tabchange", onTabChange);
};
Ext.extend(dlr.cmp.login.loginWindow, Ext.Window);
Ext.reg("loginWindow", dlr.cmp.login.loginWindow);