/**
 * @author djL
 */


 var _AppPage_ = {
 	
	loginOpen: false,
	loginBoxHt: "174px",
	namespace: "pageL",
	loginBox: null,
	regDialog: null,
	formCache: null,
	regmgr: null,
	imgOrder: [8,4,1,3,7,6],
	imgDelay: 7000,
	img1: null,
	img2: null,
	currImg: 1,
	cpy1: null,
	cpy2: null,
	currCpy: 1,
	timerId: null,

	_init_: function() {
		this.loginBox = $dom.querySelector(".login-box");
		this.LoginManager.init();
		if ($dom.byId("promptSignin")) {
			$event.click($dom.byId("promptSignin"), "openLogin", this, this.namespace);
		}
		$event.clicks($dom.querySelectorAll("a.prompt_create"), "launchRegForm", this, this.namespace);

		if (window._learnMore_) {
			this.rotateLearnMore();
		}
	},
	
	showCredits: function(atId) {
		if (this.regDialog != null) return;
		this.closeLogin();
		if (window._learnMore_) this.killRotate();
		var content = "One moment...";
		this.regDialog = $ui.createDialog(960, 510, "", content, $dom.byId(atId), $css.CENTERED_OVER);
		this.regDialog.addEventListener($ui.controls.Events.CLOSE, this, "hRegCancel");
		var client = this.regDialog.getClient();
		$asyncIO.getHTMLFragment(client, "html_frags/credits.html");
	},
	
	openLogin: function (event){
		event.stopPropagation();
		event.preventDefault();
		if (this.regDialog != null) {
			this.regDialog.close();
			this.regDialog = null;
		}
		if (window._learnMore_) this.killRotate();
		if (!this.loginOpen) {
			this.loginOpen = true;
			$ui.fadeInElement(this.loginBox, function(){
				$dom.querySelector(".login-box .shadow").style.visibility = "visible";
				$dom.byId("login_userName").focus();
			}, 200);
		}
		else {
			this.closeLogin();
		}
	},
	
	closeLogin: function() {
		if (!this.loginOpen) return;
		$dom.byId("login_userName").blur();
		$dom.querySelector(".login-box .shadow").style.visibility = "hidden";
		$ui.fadeOutElement(this.loginBox, null, 200);
		this.loginOpen = false;
	},
	
	launchRegForm: function() {
		this.closeLogin();
		if (window._learnMore_) this.killRotate();
		var content = this.formCache || "One moment..."
		this.regDialog = $ui.createModalDialog(610, 380, "Building Skills 4 Work - Sign Up", content, "#ffffff");
		this.regDialog.addEventListener($ui.controls.Events.CLOSE, this, "hDialogBeforeClose");
		if (!this.formCache) {
			var scop = this;
			var client = this.regDialog.getClient();
			$asyncIO.getHTMLFragment(client, "html_frags/reg_form.html", function(text, status, xhr){
				scop.hFormReturn(text, status, xhr);
			});
		}
		else {
			this.initReg();
		}
	},
	
	initReg: function() {
		this.regmgr = new RegManager(this.regDialog);
		this.regmgr.addEventListener(RegManager.CANCEL, this, "hRegCancel");
	},
	
	hRegCancel: function() {
		this.regDialog.removeEventListener($ui.controls.Events.DESTROY, this, "hDialogBeforeClose");
		this.regDialog.close();
		this.regDialog = null;
		this.regmgr = null;
		if (window._learnMore_) this.nextImage();
	},
	
	hFormReturn: function(text, status, xhr) {
		this.formCache = text;
		this.initReg();
	},
	
	hDialogBeforeClose: function(event) {
		this.regDialog.removeEventListener($ui.controls.Events.DESTROY, this, "hDialogBeforeClose");
		this.regmgr.destroy();
		this.regDialog.close();
		this.regDialog = null;
		this.regmgr = null;
	},
	
    LoginManager: {
		
		usrField: null,
		pwdField: null,
		subBtn: null,
		loginForm: null,
		namespace: "loginmgr",
		errorTarget: null,
		currentNote: null,
		loginUrl: "login2.php",
		
		errors: {
			usr: "<span class='error'>Username</span>: May only contain letters and numbers - no spaces.",
			pwd: "<span class='error'>Password</span>: Make sure it's filled in and contains no spaces."
		},

		init: function () {
			
			this.errorTarget = {
				target: $dom.querySelector(".login-box"),
				relativePos: $css.LEFT_CENTER
			}
			this.usrField = $dom.byId("login_userName");
			this.pwdField = $dom.byId("login_password");
			this.subBtn = $dom.byId("btnSignin");
			this.loginForm = $dom.querySelector(".login-box form");
			$event.addEventListener(this.loginForm, "submit", function(){return false;});
	
			$event.click(this.subBtn, "hSigninClick", this, this.namespace);
			$event.addEventListener(this.usrField, "keyup", "hFieldKeyUp", this, this.namespace);
			$event.addEventListener(this.pwdField, "keyup", "hFieldKeyUp", this, this.namespace);
		},
		
		hFieldKeyUp: function(e) {
			if(e.keyCode == 9) return; // tab
			var f = e.currentTarget;
			var usrOK = Validation.vNonEmpty(this.usrField.value);
			var pwdOK = Validation.vNonEmpty(this.pwdField.value);
			$ui.disableElement(this.subBtn, !(usrOK && pwdOK));
			var lbl = FormUtil.findLabel(f);
			$ui.signalError(lbl, f.value == "");
			if (e.keyCode == 13) {
				e.preventDefault();
				e.stopPropagation();
				if (this.validate()) {
					var data = {
						userName: this.usrField.value, 
						password: hex_sha1(this.pwdField.value)
					};
					var ro = new $asyncIO.RequestObject(this.loginUrl, data, this, "hLoginReturn");
					var ac = $asyncIO.call(ro);
				}
			}
		},
		
		hSigninClick: function(e) {
			if ($ui.isDisabled(e.currentTarget)) return;
			if (this.validate()) this.doLogin();
		},
		
		hNoteDestroy: function(e) {
			this.currentNote.removeEventListener($ui.controls.Events.DESTROY, this, "hNoteDestroy");
			this.currentNote = null;
		},
		
		hLoginReturn: function(data, statusMsg) {
			if (data != null && data.status == "success") {
				window.location.href = data.location;
				return;
			}
			else {
				if (data != null && data.status == "error") {
					var msg = data.errorMessage;
				}
				else {
					var msg = "Sorry! We can't find this account. Make sure you provide the username and password " +
					"that you used when signing up.";
				}
				this.showError(msg);
			}
		},
		
		doLogin: function() {
			var data = {
				userName: this.usrField.value, 
				password: hex_sha1(this.pwdField.value)
			};
			var ro = new $asyncIO.RequestObject(this.loginUrl, data, this, "hLoginReturn");
			var ac = $asyncIO.call(ro);
		},

		validate: function() {
			var usrOK = Validation.validateUsr(this.usrField);
			var pwdOK = Validation.validatePwd(this.pwdField);
			var hasError = (!usrOK || !pwdOK);
			if (hasError) {
				$ui.disableElement(this.subBtn, true);
				var msg = "";
				msg += (!usrOK ? this.errors.usr : "");
				msg += (!pwdOK ? (msg == "" ? "" : "<br /><br />") + this.errors.pwd : "");
				this.showError(msg);
			}
			return !hasError;
		},
		
		showError: function(msg) {
			var et = this.errorTarget;
			if (this.currentNote == null) {
				this.currentNote = $ui.createErrorPopup(msg, et.target, et.relativePos);
				this.currentNote.addEventListener($ui.controls.Events.DESTROY, this, "hNoteDestroy");
			}
			else this.currentNote.setContent(msg);
		}
		
	},
	
	killRotate: function() {
		clearTimeout(this.timerId);
		if (this.currImg == 1) {
			this.img1.style.opacity = 1;
			this.img1.style.zIndex = 1;
			this.img2.style.display = "none";
		}
		else if (this.currImg == 2) {
			this.img2.style.opacity = 1;
			this.img2.style.zIndex = 1;
			this.img1.style.display = "none";
		}
	},
	
	rotateLearnMore: function() {
		for (var i=0;i<8;i++) {
			var img = new Image();
			img.src = this.getImgPath(i+1);
		}
		this.img1 = $dom.byId("imageHost1");
		this.img2 = $dom.byId("imageHost2");
		this.cpy1 = $dom.byId("copyHost1");
		this.cpy2 = $dom.byId("copyHost2");
		
		$event.click($dom.byId("nextCtrl"),"nextCopy", this, "_apppage_");
		var scop = this;
		this.timerId = setTimeout(function(){scop.nextImage();}, _AppPage_.imgDelay);
	},
	
	nextCopy: function() {
		var nxt = LearnMoreContent.shift();
		LearnMoreContent.push(nxt);
		var c = nxt.title + nxt.copy;
		var cb = function(){this.innerHTML = c;};
		if (this.currCpy == 1) {
			$ui.fadeOutElement(this.cpy1, cb, 800);
			$ui.fadeInElement(this.cpy2);
			this.currCpy = 2;
		}
		else {
			$ui.fadeOutElement(this.cpy2, cb);
			$ui.fadeInElement(this.cpy1, null, 800);
			this.currCpy = 1;
		}
	},
	
	
	nextImage: function() {
		var nxt = this.imgOrder.shift();
		this.imgOrder.push(nxt);
		var n = this.getImgPath(nxt);
		var cb = function(){this.style.backgroundImage = "url("+n+")";};
		if (this.currImg == 1) {
			$ui.fadeOutElement(this.img1, cb, 800);
			$ui.fadeInElement(this.img2);
			this.currImg = 2;
		}
		else {
			$ui.fadeOutElement(this.img2, cb);
			$ui.fadeInElement(this.img1, null, 800);
			this.currImg = 1;
		}
		var scop = this;
		this.timerId = setTimeout(function(){scop.nextImage();}, _AppPage_.imgDelay);
	},
	
	getImgPath:function (n) {
		return "images/screens/bs4w_0"+ n +"_360x246.jpg";
	}
}

var RegManager =  jsClass(null, {
	
	CANCEL: "cancel",
	regUrl: "register2.php",
	dialog: null,
	USERNAME_UNAVAILABLE: "Sorry! - that user name is unavailable.",
	
	constructor: function RegManager(dialog) {
		JSEventDispatcher.initialize(this);
		this.dialog = dialog;
		this.namespace = $util.getUid();
		this.Fields = {
   			userName: {vFn:"validateUsr",  group:"usr",  f:null, 
					   hint:"Use only letters and numbers (no spaces).", error:"Must not contain spaces or punctuation."},           
   			password: {vFn:"validatePwd",  group:"pwd1",  f:null, 
					   hint:"Any chars okay except spaces.", error:"Must not contain spaces."},
   			password2:{vFn:"validatePwd2", group:"pwd2", f:null, 
					   hint: "Please re-type your password.", error: "Passwords don't match. Please try again."}
		};
		this.form = $dom.querySelector(".reg-form");
		this.init();
	},
	
	init: function() {
		var f, flds = this.Fields;
		for (var q in flds) {
			f = $dom.querySelector(".reg-form #reg_"+q);
			flds[q].f = f;
			$event.addEventListener(f, "focus", "hFocusBlur", this, this.namespace);
			$event.addEventListener(f, "blur", "hFocusBlur", this, this.namespace);
			$event.addEventListener(f, "keyup", "hFieldKeyUp", this, this.namespace);
		}
		$event.addEventListener($dom.byId("email"), "keyup", "hFieldKeyUp", this, this.namespace);
		this.cancelBtn = $dom.querySelector(".button-block .secondary");
		this.submitBtn = $dom.querySelector(".button-block .primary");
		$event.click(this.cancelBtn, "hCancel", this, this.namespace);
		$event.click(this.submitBtn, "hSubmit", this, this.namespace);
		flds.userName.f.focus();
	},
	
	
	destroy: function() {
		for (var q in this.Fields) {
			$event.removeAllListenersForNamespace(this.Fields[q].f, this.namespace);
			this.Fields[q].f = null;
		}
		$event.removeAllListenersForNamespace(this.cancelBtn, this.namespace);
		$event.removeAllListenersForNamespace(this.submitBtn, this.namespace);
		this.cancelBtn = null;
		this.submitBtn = null;
	},
	
	submitReg: function() {
		$ui.disableElement(this.submitBtn, true);
		$ui.disableElement(this.cancelBtn, true);
		var data = {
			userName: this.Fields.userName.f.value,
			password: hex_sha1(this.Fields.password.f.value),
			email: $dom.byId("email").value,
			action: "register"
		};
		var ro = new $asyncIO.RequestObject(this.regUrl, data, this, "hRegReturn");
		var ac = $asyncIO.call(ro);
	},
	
	checkUserName: function (val) {
		var data = {userName: val, action:"checkUserName"};
		var ro = new $asyncIO.RequestObject(this.regUrl, data, this, "hUsrCheck");
		var ac = $asyncIO.call(ro);
	},
	
	hRegReturn: function(data, statusMsg) {
		var p1 = "<p class='reg-welcome'>";
		var p2 = "<\/p>";
		var ok = "Welcome, $USR$!<br />Thanks for joining BuildingSkills4Work.";
		var notOK = "We're sorry! - there was a problem on the server and we could not create your account.<br /><br />"
				  + "Please try again later.";
		if (data != null && data.status == "success") {
			var msg = ok.replace("$USR$", data.user || "");
			this.dialog.setContent(p1 + msg + p2);
			setTimeout(function(){window.location.href = data.location;}, 3000);
			return;
		}
		else {
			if (data.errorMessage == "USERNAME_UNAVAILABLE") {
				this.setUsernameUnavailMsg();
			}
			else this.dialog.setContent(p1 + notOK + p2);
		}
	},
	
	hUsrCheck: function(data, statusMsg) {
		var o = "";
		if (data == null) {
			throw new Error("error checking user name " + statusMsg);
			return;
		}
		if (data.status == "error" && data.errorMessage == "USERNAME_UNAVAILABLE") {
			this.setUsernameUnavailMsg();
		}
		else if (data.status == "error") {
			this.dialog.setContent("We're Sorry - an error occurred. Please try signing up later.");
		}
	},
	
	
	hCancel: function() {
		this.destroy();
		this.dispatchEvent(new JSEvent(RegManager.CANCEL, this, null));
	},
	
	hSubmit: function() {
		if(this.validate()) this.submitReg();
	},
	
	hFocusBlur: function(e) {
		var f = e.currentTarget;
		if (e.type == "focus") this.setHint(f);
		else {
			if (f.value == "") { 
				this.setDefaultState(f);
				return; 
			}
			var stat = this.getStatus(f);
			if (stat && FormUtil.getFieldName(f) == "userName") {
				this.checkUserName(f.value);
			}
		}
	},
	
	setUsernameUnavailMsg: function() {
		var uf = this.Fields.userName;
		var hEl = FormUtil.findHintEl(uf.group);
		var lbl = FormUtil.findLabel(uf.f);
		$ui.signalError(lbl, true);
		hEl.className = "msg error";
		hEl.innerHTML = this.USERNAME_UNAVAILABLE;
	},

	setHint: function(f) {
		var fld = this.Fields[FormUtil.getFieldName(f)];
		var hEl = FormUtil.findHintEl(fld.group);
		if ($dom.hasClass(hEl, "valid")) return;
		hEl.className = "msg hint";
		hEl.innerHTML = fld.hint;
	},
	
	setDefaultState: function(f) {
		var fld = this.Fields[FormUtil.getFieldName(f)];
		var hEl = FormUtil.findHintEl(fld.group);
		hEl.className = "msg";
		hEl.innerHTML = "&nbsp;";
	},
	
	getStatus: function(f) {
		var fld = this.Fields[FormUtil.getFieldName(f)];
		var hEl = FormUtil.findHintEl(fld.group);
		if (fld.group != "pwd2") {
			var ok = Validation[fld.vFn](f);
		}
		else {
			var ok = Validation[fld.vFn](this.Fields.password.f, f);
		}
		hEl.className = "msg" + (ok ? " valid" : " error");
		hEl.innerHTML = ok ? "&nbsp;" : fld.error;
		return ok;
	},
	
	validate: function() {
		var ok = true;
		for(var q in this.Fields) {
			var fs = this.getStatus(this.Fields[q].f);
			if (!fs) ok = false;
		}
		return ok;
		
	},
	
//	hFieldKeyPress: function(e) {
//		e.preventDefault();
//			e.stopPropagation();
//	},
	
	hFieldKeyUp: function(e) {
		if (e.keyCode == 13) {
			e.preventDefault();
			e.stopPropagation();
			if(this.validate()) {
				$ui.disableElement(this.submitBtn, true);
				$ui.disableElement(this.cancelBtn, true);
				var data = {
					userName: this.Fields.userName.f.value,
					password: hex_sha1(this.Fields.password.f.value),
					email: $dom.byId("email").value,
					action: "register"
				};
				var ro = new $asyncIO.RequestObject(this.regUrl, data, this, "hRegReturn");
				var ac = $asyncIO.call(ro);
			}
		}
	}

});

var FormUtil = {
	findLabel: function(f) {
		return $dom.querySelector("label[for='" + f.id + "']");
	},
	findHintEl: function(id) {
		return $dom.querySelector("#"+id + " > .msg");
	},
	getFieldName: function(f) {
		return fname = f.id.split("_")[1];
	}
};
 
var Validation = {
	

	vNonEmpty: function(s) {
		return s != "" && (/\w/).test(s);
	},

	vNoSpace: function(s) {
		return !((/\s/).test(s));
	},
	
	validateUsr: function(f) {
		var badChars = /[^A-Za-z0-9]/;
		var val = f.value;
		var lbl = FormUtil.findLabel(f);
		var ok = this.vNonEmpty(val) && this.vNoSpace(val) && !(badChars.test(val));
		$ui.signalError(lbl, !ok);
		return ok;
	},
	
	validatePwd: function(f) {
		var val = f.value;
		var lbl = FormUtil.findLabel(f);
		var ok = this.vNonEmpty(val) && this.vNoSpace(val);
		$ui.signalError(lbl, !ok);
		return ok;
	},
	
	validatePwd2: function(f1,f2) {
		var ok = f1.value === f2.value && this.validatePwd(f2);
		var lbl = FormUtil.findLabel(f2);
		$ui.signalError(lbl, !ok);
		return ok;
	}
		
};


var LearnMoreContent = [
		
	{
		title: "<h2>How will this help me?</h2>",
		copy: "<p>All of the lessons are set in real job situations.</p>"
			 + "<p>The skills taught are skills that many employers have identified as the skills they expect from the people they hire.</p>"
			 + "<p>Building skills will help you gain confidence in looking for a new job or advancing in a current job.</p>"
	},
	
	{
		title: "<h2>What skills are taught?</h2>",
		copy: "<p>Reading at Work</p>"
			 + "<p>Math at Work</p>"
			 + "<p>Cooperate and Resolve Conflict</p>"
			 + "<p>Solve Problems and Make Decisions</p>"
			 + "<p>Listen Actively</p>"
			 + "<p>Observe Critically</p>"
	},
	
	{
		title: "<h2>How does it work?</h2>",
		copy: "<p>You will create a free account with Username and Password, which takes only a few moments.</p>"
			 + "<p>You choose the lessons you want to work on and work at your own pace. You may repeat things as often as you like.</p>"
			 + "<p>You will be able to track your own progress.</p>"
			 + "<p>The lessons are audio-visual and interactive and do not require a lot of reading.</p>"
	},
	
	{
		title: "<h2>What is BuildingSkills4Work (BS4W)?</h2>",
		copy: "<p>BS4W is a website that has free lessons that teach workplace skills that employers look for in the people they hire.</p>"
			 + "<p>BS4W is a website with information about different careers and resources to help you.</p>"
	},
	{
		title: "<h2>Who is BS4W website intended for?</h2>",
		copy: "<p>BS4W has been developed for people who want to improve their work readiness skills.</p>"
			 + "<p>The website has been designed for people of different backgrounds and different ages.</p>"
			 + "<p>The skills taught are for people who seek high demand, good paying jobs.</p>"
	}

];
