YAHOO.namespace("condenet");
var Webmonkey = YAHOO.condenet;
var BaseModule = Webmonkey.BaseModule;
var LoginModule = Webmonkey.LoginModule;
var RegisterModule = Webmonkey.RegisterModule;
var ForgotPassModule = Webmonkey.ForgotPassModule;
var ThankYouModule = Webmonkey.ForgotPassModule;
var FPConfModule = Webmonkey.FPConfModule;
var LoginAndRegController = Webmonkey.LoginAndRegController;

var userLoggedIn = false;
var linkUrl = "";
var checkedLogin = false; //login triggered from protected page

var YUC = YAHOO.util.Connect;

//custom events map. These need to match the eventTypes returned from DWR
var onUserLoggedInEvent = new YAHOO.util.CustomEvent('UserLoggedInEvent');
var onNoUserLoggedInEvent = new YAHOO.util.CustomEvent('NoUserLoggedInEvent');
var onLoginSuccessfulEvent = new YAHOO.util.CustomEvent('LoginSuccessfulEvent');
var onLoginFailureEvent = new YAHOO.util.CustomEvent('LoginFailureEvent');
var customEvents = {"UserLoggedInEvent":onUserLoggedInEvent, 
	"NoUserLoggedInEvent":onNoUserLoggedInEvent,
	"LoginSuccessfulEvent":onLoginSuccessfulEvent,
"LoginFailureEvent":onLoginFailureEvent};

BaseModule = function(divId) {
    this.init(divId, {
			  visible:false,
			  effect: {effect:YAHOO.widget.ContainerEffect.FADE,duration:0.5}
			  } ); 
    this.render();
};

BaseModule.prototype = {
isVisible: false,
showModule: function(contextId) {
	if(contextId != null) {
		// this.cfg.setProperty("context", [contextId, "tl", "bl"]);
		this.cfg.setProperty("fixedcenter", true); 
	}
	this.isVisible = true;
	this.show();
	
	// added for DE 80 TA 319 - cursor not displaying on login module
	if(document.getElementById("username") && document.getElementById("password")) {
		var username = document.getElementById("username");
		var password = document.getElementById("password");
		username.onfocus = highlightTextfield;
		password.onfocus = highlightTextfield;
	}
	
	// added for DE 80 TA 319 - cursor not displaying on forgotten password module
	if(document.getElementById("fp_username") && document.getElementById("fp_email")) {
		var fp_username = document.getElementById("fp_username");
		var fp_email = document.getElementById("fp_email");
		fp_username.onfocus = highlightTextfield;
		fp_email.onfocus = highlightTextfield;
	}
	
	
},
hideModule: function() {
	this.isVisible = false;
	this.hide();
	if(document.getElementById('lightbox_shadow'))
		document.getElementById('lightbox_shadow').style.display = 'none';
},
toggleModule: function(contextId, loginChecked) {
	if(loginChecked)
		checkedLogin = true;
	else
		checkedLogin = false;
	if(!this.isVisible){
		//show lightbox div
		if(document.getElementById('lightbox_shadow')) {
			document.getElementById('lightbox_shadow').style.display = 'block';
		} else {
			var lightbox_div = document.createElement('div');
			lightbox_div.setAttribute("id", "lightbox_shadow"); 
			document.body.appendChild(lightbox_div);
			document.getElementById('lightbox_shadow').style.display = 'block';
		}
		
		this.showModule(contextId);
		
	}
	else {
		this.hideModule();
		if($('lightbox_shadow'))
			document.getElementById('lightbox_shadow').style.display = 'none';
	}
}
};
YAHOO.lang.augment(BaseModule, YAHOO.widget.Overlay);

LoginModule = function(divId) {
    this.constructor.superclass.constructor.call(this, divId);
    //add listeners
    onUserLoggedInEvent.subscribe(this.handleUserLoggedIn);
    onNoUserLoggedInEvent.subscribe(this.handleNoUserLoggedIn);
}
YAHOO.lang.extend(LoginModule, BaseModule);

LoginModule.prototype.doLogin = function() {
    //validate that both fields have content
	document.getElementById('login_status_icon').style.display = 'block';
	var username = document.getElementById('username');
	var password = document.getElementById('password');
	if(username.value == '' || password.value == '')
	{
		this.showLoginError("Please enter your username and password.");
		document.getElementById('login_status_icon').style.display = 'none';
	}
	else{
		var formObject = document.getElementById('userLogin');
		YUC.setForm(formObject);
		YUC.asyncRequest('POST', '/user/login/light', logincallback);
	}
	
}
LoginModule.prototype.handleLoginCallback = function(e) {
    //alert("in handleLoginCallback");
	document.getElementById('login_status_icon').style.display = 'none';
	var response = e.responseText;
	var res = response.replace("org.springframework.validation.BindingResult.form","form");
	var result = YAHOO.lang.JSON.parse(res);
	
	if(result.loginSuccess) {
		this.handleLoginSuccessful();
	}
	else if (result.form != null && result.form.globalError != null && result.form.globalError.code == "username.blocked")
	{
		this.handleLoginFailure(result.form.globalError.defaultMessage);
	}
	else if (result.attemptLimitReached)
	{
        this.handleLoginFailure("Login attempt limit reached. Please try again later.");
	}
	else {
		this.handleLoginFailure("Please enter a valid username and password.");
	}
	//alert(result.loginFailed);
	//alert(result.form.returnto);
    //alert(e.responseText);
    //if(customEvents[e.eventType] != null) 
    //    customEvents[e.eventType].fire();
}
LoginModule.prototype.handleUserLoggedIn = function() {
    //alert("login was successful");
	if(linkUrl != "" && checkedLogin) {
		//alert(linkUrl);
		checkedLogin = false; //reset
		newUrl = linkUrl;
		linkUrl = "";
 	    location.href = newUrl;
	}
}
LoginModule.prototype.handleNoUserLoggedIn = function() {
    //alert("the user has logged out");
	var newUrl = window.location.href;
	var i = window.location.href.indexOf("?");
    if(i>-1) {
		newUrl = window.location.href.substring(0,i);
	}
	//alert(newUrl);
	var re =  new RegExp("(.*?)/edit$");
    if(newUrl.match(re)){
        var result = re.exec(newUrl);
		//alert("redirecting to: " + result[1]);
		location.href = result[1];
	}
}
LoginModule.prototype.handleLoginSuccessful = function() {
	//    alert("login was successful");
	//hide the sign in thing
	LoginModule.superclass.hideModule.call(this);
	//change signin to sign out
	updateLoginBar();
	customEvents["LoginSuccessfulEvent"].fire();
}
LoginModule.prototype.handleLoginFailure = function(message) {
	customEvents["LoginFailureEvent"].fire();
	this.showLoginError(message);
}
LoginModule.prototype.handleLoginRemoteFailure = function() {
    alert("login was unsuccessful");
}

LoginModule.prototype.showLoginError = function(msg){
	var login_error_div = document.getElementById('login_error_div');
	login_error_div.innerHTML = msg;
	login_error_div.style.display = "block";	
}

RegisterModule = function(divId) {
    this.constructor.superclass.constructor.call(this, divId);
	
	YAHOO.util.Event.addListener("reg_email", "focus", function() {showMsgField("email_msg", "info", "Enter your e-mail address")});
	YAHOO.util.Event.addListener("reg_username", "focus", function() {showMsgField("username_msg", "info", "Choose a username")});
	YAHOO.util.Event.addListener("reg_password1", "focus", function() {showMsgField("password1_msg", "info", "Type a password at least 6 characters long")});
	YAHOO.util.Event.addListener("reg_password2", "focus", function() {showMsgField("password2_msg", "info", "Retype your password")});
	
	YAHOO.util.Event.addListener("reg_email", "blur", function() {clearMsgField("email_msg")});
	YAHOO.util.Event.addListener("reg_username", "blur", function() {clearMsgField("username_msg")});
	YAHOO.util.Event.addListener("reg_password1", "blur", function() {clearMsgField("password1_msg")});
	YAHOO.util.Event.addListener("reg_password2", "blur", function() {clearMsgField("password2_msg")});
	YAHOO.util.Event.addListener("reg_optin1_yes", "blur", function() {clearMsgField("optin1_msg")});
	YAHOO.util.Event.addListener("reg_optin1_no", "blur", function() {clearMsgField("optin1_msg")});
	YAHOO.util.Event.addListener("reg_optin2_yes", "blur", function() {clearMsgField("optin2_msg")});
	YAHOO.util.Event.addListener("reg_optin2_no", "blur", function() {clearMsgField("optin2_msg")});
	
	// added for DE 80 TA 319 - cursor not displaying on register module
	if(document.getElementById("reg_email") && document.getElementById("reg_username") && document.getElementById("reg_password1") && document.getElementById("reg_password2")) {
		var reg_email = document.getElementById("reg_email");
		var reg_username = document.getElementById("reg_username");
		var reg_password1 = document.getElementById("reg_password1");
		var reg_password2 = document.getElementById("reg_password2");
		reg_email.onfocus = highlightTextfield;
		reg_username.onfocus = highlightTextfield;
		reg_password1.onfocus = highlightTextfield;
		reg_password2.onfocus = highlightTextfield;
	}
}
YAHOO.lang.extend(RegisterModule, BaseModule);
RegisterModule.prototype.doRegister = function() {
	document.getElementById('register_status_icon').style.display = 'block';
	var formObject = document.getElementById('userRegistration');
	YUC.setForm(formObject);
	YUC.asyncRequest('POST', '/user/registration/light', registercallback);
    //RegisterManager.getData(this.handleRegisterCallback);
}
RegisterModule.prototype.handleRegisterCallback = function(e) {
    var response = e.responseText;
	var res = response.replace("org.springframework.validation.BindingResult.form","form");
    var result = YAHOO.lang.JSON.parse(res);
	if(result.registrationSucess) {
		this.handleRegisterSuccessful();
	}
	else {
		this.handleRegisterFailure(result);
	}
}
RegisterModule.prototype.handleRegisterSuccessful = function() {
	document.getElementById('register_status_icon').style.display = 'none';
	RegisterModule.superclass.hideModule.call(this);
	//change signin to sign out
	updateLoginBar();
	
	var profile_link = document.getElementById('thank_you_profile_link');
	var amg_user = readCookie("amg_user_info");
	profile_link.href = "/user/profile/" + amg_user + "/edit";
	
	toggleThankYouModule(DEFAULT_CONTEXT);
}

RegisterModule.prototype.handleRegisterFailure = function(result) {
	document.getElementById('register_status_icon').style.display = 'none';
	for(var i=0; i<result.form.fieldErrorCount; i++) {
		//alert(result.form.fieldErrors[i].field + ":" + result.form.fieldErrors[i].defaultMessage);
		showMsgField(result.form.fieldErrors[i].field + "_msg", "error", result.form.fieldErrors[i].defaultMessage);
	}
	for(var i=0; i<result.form.errorCount; i++) {
		showMsgField(result.form.globalError.code + "_msg", "error", result.form.globalError.defaultMessage); //weird
	}
}
RegisterModule.prototype.handleRegisterRemoteFailure = function() {
    alert("remote register was unsuccessful");
}


ForgotPassModule = function(divId) {
    this.constructor.superclass.constructor.call(this, divId);
}
YAHOO.lang.extend(ForgotPassModule, BaseModule);
var fp_submit_type = null;
ForgotPassModule.prototype.doForgotPass = function() {
	document.getElementById('fp_status_icon').style.display = 'block';
	
    //alert("in doForgotPass");
	var formObject = document.getElementById('forgotPassword');
	if(document.getElementById('fp_email').value != '' && document.getElementById('fp_username').value != '')
		fp_submit_type = 3;
    else if(document.getElementById('fp_email').value != '')
		fp_submit_type = 1;
    else if(document.getElementById('fp_username').value != '')
		fp_submit_type = 2;
	
	YUC.setForm(formObject);
	YUC.asyncRequest('POST', '/user/forgot_password/light', forgotpasscallback);
    //RegisterManager.getData(this.handleForgotPassCallback);
}
ForgotPassModule.prototype.handleForgotPassCallback = function(e) {
    var result = YAHOO.lang.JSON.parse(e.responseText);
	//alert("result.loginSuccess: " + result.loginSuccess);
	resultstr = YAHOO.lang.JSON.stringify(result);
	if(resultstr == "{}") { //result comes back as {}
		this.handleForgotPassSuccessful();
	}
	else {
		this.handleForgotPassFailure();
	}
}
ForgotPassModule.prototype.handleForgotPassSuccessful = function() {
	document.getElementById('fp_status_icon').style.display = 'none';
	ForgotPassModule.superclass.hideModule.call(this);
	//change signin to sign out
	updateLoginBar();
	toggleFPConfModule(DEFAULT_CONTEXT);
}
ForgotPassModule.prototype.handleForgotPassFailure = function() {
	document.getElementById('fp_status_icon').style.display = 'none';
	var the_fp_submit_text;
	if(fp_submit_type == 1)
		the_fp_submit_text = 'e-mail address';
	else if(fp_submit_type == 2)
		the_fp_submit_text = 'username';
	else if(fp_submit_type == 3)
		the_fp_submit_text = 'username or email-address';
	else
		the_fp_submit_text = 'username or email-address';
	fp_submit_type = null;
	
	document.getElementById('fp_error_div').innerHTML = "We're sorry, the " + the_fp_submit_text + " you entered is invalid, please try again and re-submit";
	document.getElementById('fp_error_div').style.display = 'block';
	//ForgotPassModule.superclass.hideModule.call(this);
}
ForgotPassModule.prototype.handleForgotPassRemoteFailure = function() {
    alert("remote login was unsuccessful");	
}

ThankYouModule = function(divId) {
    this.constructor.superclass.constructor.call(this, divId);
}
YAHOO.lang.extend(ThankYouModule, BaseModule);

FPConfModule = function(divId) {
    this.constructor.superclass.constructor.call(this, divId);
}
YAHOO.lang.extend(FPConfModule, BaseModule);


var loginMod = null;
var registerMod = null;
var forgotpassMod = null;
var thankyouMod = null;
var fpConfMod = null;

//constants
var LOGIN_MOD = "loginMod";
var REGISTER_MOD = "registerMod";
var FORGOTPASS_MOD = "forgotpassMod";
var THANKYOU_MOD =  "thankyouMod";
var FPCONF_MOD = "fpConfMod";
var DEFAULT_CONTEXT = "signin_li";

function init() {
    loginMod = new LoginModule(LOGIN_MOD);
    registerMod = new RegisterModule(REGISTER_MOD);
    forgotpassMod = new ForgotPassModule(FORGOTPASS_MOD);
	thankyouMod = new ThankYouModule(THANKYOU_MOD);
	fpConfMod = new FPConfModule(FPCONF_MOD);
	
	//check to see if user is logged in.
	updateLoginBar();
    
    YAHOO.util.Event.addListener("forgotpassLink", "click", toggleForgotPassModule, DEFAULT_CONTEXT);
    YAHOO.util.Event.addListener("joinnowLink", "click", toggleRegisterModule, DEFAULT_CONTEXT);
    
    YAHOO.util.Event.addListener("closeLogin", "click", function() {loginMod.hideModule()});
    YAHOO.util.Event.addListener("closeRegister", "click", function() {registerMod.hideModule()});
    YAHOO.util.Event.addListener("closeForgotPass", "click", function() {forgotpassMod.hideModule()});
    
    YAHOO.util.Event.addListener("loginSubmit", "click", function() {loginMod.doLogin()});
    YAHOO.util.Event.addListener("registerSubmit", "click", function() {registerMod.doRegister()});
    YAHOO.util.Event.addListener("forgotpassSubmit", "click", function() {forgotpassMod.doForgotPass()});
	
	YAHOO.util.Event.addListener("closeThankYou", "click", function() {thankyouMod.hideModule()});
	YAHOO.util.Event.addListener("closeThankYouBtn", "click", function() {thankyouMod.hideModule()});
	
	YAHOO.util.Event.addListener("closeFPConf", "click", function() {fpConfMod.hideModule()});
	YAHOO.util.Event.addListener("fpConfSignIn", "click", toggleLoginModule, DEFAULT_CONTEXT);
	
}
init();

function toggleLoginModule(e, contextId, loginChecked) {
    registerMod.hideModule();
    forgotpassMod.hideModule();
	thankyouMod.hideModule();
	fpConfMod.hideModule();
    loginMod.toggleModule(contextId, loginChecked);
}

function toggleRegisterModule(e, contextId) {
    loginMod.hideModule();
    forgotpassMod.hideModule();
	thankyouMod.hideModule();
	fpConfMod.hideModule();
    registerMod.toggleModule(contextId);
}

function toggleForgotPassModule(e, contextId) {
    loginMod.hideModule();
    registerMod.hideModule();
	thankyouMod.hideModule();
	fpConfMod.hideModule();
    forgotpassMod.toggleModule(contextId);
}

function toggleThankYouModule(contextId) {
    loginMod.hideModule();
    registerMod.hideModule();
	forgotpassMod.hideModule();
	fpConfMod.hideModule();
    thankyouMod.toggleModule(contextId);
}

function toggleFPConfModule(contextId) {
    loginMod.hideModule();
    registerMod.hideModule();
	forgotpassMod.hideModule();
	thankyouMod.hideModule();
    fpConfMod.toggleModule(contextId);
}

function createSigninLink() {
	var signinLink = document.createElement("li");
	signinLink.id = "signin_li";
	
	var signinAnchor = document.createElement("a");
	signinAnchor.id = "signinLink";
	signinAnchor.href = "javascript:void(0);";
	
	var signinText = document.createTextNode("Sign In");
	
	signinAnchor.appendChild(signinText);
	signinLink.appendChild(signinAnchor);
	signinLink.appendChild(createPipe());
	
	return signinLink;
}

function createPipe() {
	var pipe = document.createElement("span");
	pipe.className = "pipe";
	var pipeText = document.createTextNode("|");
	pipe.appendChild(pipeText);
	return pipe;
}

function createSignoutLink() {
	var signoutLink = document.createElement("li");
	signoutLink.id = "signout_li";
	
	var signoutAnchor = document.createElement("a");
	signoutAnchor.id = "signoutLink";
	signoutAnchor.href = "javascript:void(0);";
	
	var signoutText = document.createTextNode("Sign Out");
	signoutAnchor.appendChild(signoutText);
	signoutLink.appendChild(signoutAnchor);
	signoutLink.appendChild(createPipe());
	return signoutLink;
	
}

function createRegisterLink() {
	var registerLink = document.createElement("li");
	registerLink.id = "register_li";
	
	var registerAnchor = document.createElement("a");
	registerAnchor.id = "registerLink";
	registerAnchor.href = "javascript:void(0);";
	
	var registerText = document.createTextNode("Register");
	registerAnchor.appendChild(registerText);
	registerLink.appendChild(registerAnchor);
	registerLink.appendChild(createPipe());
	return registerLink;
}

function createWelcome() {
	var amg_user = readCookie("amg_user_info");
	var welcome = document.createElement("li");
	welcome.id = "welcome_li";
	
	var welcomeSpan = document.createElement("span");
	welcomeSpan.className = "user_icon logged_in";
	
	var welcomeText = document.createTextNode("Welcome, " + amg_user);
	welcome.appendChild(welcomeSpan);
	welcome.appendChild(welcomeText);
	welcome.appendChild(createPipe());
	return welcome;
}

function createProfileLink() {
	var amg_user = readCookie("amg_user_info");
	var profileLink = document.createElement("li");
	profileLink.id = "profile_li";
	
	var profileAnchor = document.createElement("a");
	profileAnchor.id = "userprofileLink";
	profileAnchor.href = "/user/profile/" + amg_user + "/edit";
	
	var profileText = document.createTextNode("View Profile");
	profileAnchor.appendChild(profileText);
	profileLink.appendChild(profileAnchor);
	profileLink.appendChild(createPipe());
	return profileLink;
}

//updates the loginbar depending on the login state of the user
function updateLoginBar() {
	var loginbarlist = document.getElementById("head_login_bar_list");
	if(isLoggedIn()){
		//first remove signin_li, register_li
		var welcome_li = document.getElementById("welcome_li");
		if(welcome_li != null) {
			loginbarlist.removeChild(welcome_li);
		}
		var profile_li = document.getElementById("profile_li");
		if(profile_li != null) {
			loginbarlist.removeChild(profile_li);
		}
		var signout_li = document.getElementById("signout_li");
		if(signout_li != null) {
			loginbarlist.removeChild(signout_li);
		}
		
		var signin_li = document.getElementById("signin_li");
		if(signin_li != null) {
			loginbarlist.removeChild(signin_li);
		}
		var register_li = document.getElementById("register_li");
		if(register_li != null) {
			loginbarlist.removeChild(register_li);
		}
		
		var help_li = document.getElementById("help_li");
		if(help_li != null) {
			signout_li = createSignoutLink();
			profile_li = createProfileLink();
			welcome_li = createWelcome();
			loginbarlist.insertBefore(signout_li, help_li);
			loginbarlist.insertBefore(profile_li, signout_li);
			loginbarlist.insertBefore(welcome_li, profile_li);
		}
		
		YAHOO.util.Event.addListener("signoutLink", "click", function() {LogoutObject.startRequest();});
		
        customEvents["UserLoggedInEvent"].fire();
	}
	else {
		//first remove welcome_li, profile_li, and signout_li
		var signin_li = document.getElementById("signin_li");
		if(signin_li != null) {
			loginbarlist.removeChild(signin_li);
		}
		var register_li = document.getElementById("register_li");
		if(register_li != null) {
			loginbarlist.removeChild(register_li);
		}
		
		var welcome_li = document.getElementById("welcome_li");
		if(welcome_li != null) {
			loginbarlist.removeChild(welcome_li);
		}
		var profile_li = document.getElementById("profile_li");
		if(profile_li != null) {
			loginbarlist.removeChild(profile_li);
		}
		var signout_li = document.getElementById("signout_li");
		if(signout_li != null) {
			loginbarlist.removeChild(signout_li);
		}
		
		var help_li = document.getElementById("help_li");
		if(help_li != null) {
			signin_li = createSigninLink();
			register_li = createRegisterLink();
			loginbarlist.insertBefore(register_li, help_li);
			loginbarlist.insertBefore(signin_li, register_li);
		}
		
		YAHOO.util.Event.addListener("signinLink", "click", toggleLoginModule, DEFAULT_CONTEXT);
		YAHOO.util.Event.addListener("registerLink", "click", toggleRegisterModule, DEFAULT_CONTEXT);
	}
}

function isLoggedIn() {
	//do we need to make an ajax call to the server to make this check?
	var curCookie = document.cookie;
	if (curCookie.indexOf("amg_user_info") > -1) {
		// this should be a logged-in user
		userLoggedIn = true;
		return true;
	} 
	userLoggedIn = false;
	return false;
}

var LogoutObject = {
handleSuccess:function(o){
	//check response
	//change signout to signin
	updateLoginBar();
	customEvents["NoUserLoggedInEvent"].fire();
},
	
handleFailure:function(o){
	// Failure handler
	alert("failed logout");
},
	
startRequest:function() {
	var loginModeCookie = readCookie("loginmethod")
	if (loginModeCookie != null && loginModeCookie == 'openid') {
		YAHOO.util.Connect.asyncRequest('POST', 'http://openid.webmonkey.com/openid/login/doLogout', logoutcallback);    	
	} else {
		YAHOO.util.Connect.asyncRequest('POST', '/user/logout', logoutcallback);
	}
}
}
/*
 * Define the callback object for success and failure
 * handlers as well as object scope.
 */
var logincallback = {
success:loginMod.handleLoginCallback,
failure:loginMod.handleLoginRemoteFailure,
scope: loginMod
}
var logoutcallback = {
success:LogoutObject.handleSuccess,
failure:LogoutObject.handleFailure,
scope: LogoutObject
}
var registercallback = {
success:registerMod.handleRegisterCallback,
failure:registerMod.handleRegisterRemoteFailure,
scope: registerMod
}
var forgotpasscallback = {
success:forgotpassMod.handleForgotPassCallback,
failure:forgotpassMod.handleForgotPassRemoteFailure,
scope: forgotpassMod
}

function readCookie(name){var nameEQ=name+"=";var ca=document.cookie.split(';');for(var i=0;i< ca.length;i++){var c =ca[i];while(c.charAt(0)==' ')c=c.substring(1,c.length);if(c.indexOf(nameEQ)==0)return c.substring(nameEQ.length,c.length);}return null;}


//client side validation
/*
 function checkpasswords (password1, password2, type)
 {
 if(type == 'password') {
 if (password1.value.length == 0) {
 return;
 }
 if (password1.value.length < 5) {
 document.getElementById (password1.name+'checkitvalue').innerHTML = createInvalidField('<?php echo $smarty->get_config_vars('PLIGG_Visual_CheckField_PasswordShort'); ?>');
 return;
 }
 else {
 document.getElementById (password1.name+'checkitvalue').innerHTML = createValidField();
 return;
 }
 }
 if(type == 'verify') {
 if(password1.value.length == 0) {
 return;
 }
 if(password1.value == password2.value) {
 document.getElementById (password2.name+'checkitvalue').innerHTML = createValidField();
 }
 else {
 document.getElementById (password2.name+'checkitvalue').innerHTML = createInvalidField('passwords don\'t match');
 }
 }
 return false;
 }
 */
var MSG_HOLDER = "msgholder";
function showMsgField(field, type, msg)
{
	var theMsgElt = document.getElementById(field);
	theMsgElt.style.display = 'block';
	theMsgElt.innerHTML = msg;
	theMsgElt.setAttribute("class", "reg_mod_row reg_" + type);
	theMsgElt.setAttribute("className", "reg_mod_row reg_" + type);
    return false;
}

function clearMsgField(field)
{
	var fieldElement = document.getElementById(field);
	fieldElement.innerHTML = '';
	fieldElement.setAttribute("class", "reg_mod_row reg_error");
	fieldElement.setAttribute("className", "reg_mod_row reg_error");
    return false;
}

//show a check mark or something
function createValidField(){
    var wrapper = document.createElement("span");
	var validField = document.createElement("img");
	validField.src = "http://stag-webmonkey.advancemags.com/images/icon_check.png";
	var validFieldSpan = document.createElement("span");
	validFieldSpan.className = "inputError";
	var validFieldText = document.createTextNode(strmsg);
	
	validFieldSpan.appendChild(validFieldText);
	wrapper.appendChild(validField);
	wrapper.appendChild(validFieldSpan);
	
	return wrapper;
}

function createInvalidField(strmsg){
    //return '<img src="/images/some.gif"/> <span style="color:red">' + strmsg + '</span>';
	var wrapper = document.createElement("span");
	var invalidField = document.createElement("img");
	invalidField.src = "http://stag-webmonkey.advancemags.com/images/icon_error.png";
	var invalidFieldSpan = document.createElement("span");
	invalidFieldSpan.className = "inputError";
	var invalidFieldText = document.createTextNode(strmsg);
	
	invalidFieldSpan.appendChild(invalidFieldText);
	wrapper.appendChild(invalidField);
	wrapper.appendChild(invalidFieldSpan);
	
	return wrapper;
	
}

function createInfoField(strmsg){
    var wrapper = document.createElement("span");
	var infoField = document.createElement("img");
	infoField.src = "http://stag-webmonkey.advancemags.com/images/icon_info.png";
	var infoFieldSpan = document.createElement("span");
	infoFieldSpan.className = "inputError";
	var infoFieldText = document.createTextNode(strmsg);
	
	infoFieldSpan.appendChild(infoFieldText);
	wrapper.appendChild(infoField);
	wrapper.appendChild(infoFieldSpan);
	
	return wrapper;
}

function validateForm(){
}

var oOptions = {
method: "get",
onSuccess: function (oXHR, oJson) {
	//alert(oXHR.responseText);
	var result = YAHOO.lang.JSON.parse(oXHR.responseText);
	if(result.loginStatus == "failure") {
		userLoggedIn = false;
		toggleLoginModule(null, DEFAULT_CONTEXT, true);
	}
	else {
		userLoggedIn = true;
		//proceed with the request
	}
},
onFailure: function (oXHR, oJson) {
	alert("Request was unsuccessful.");
},
asynchronous: false
};

function checkLogin(elementId){
	checkedLogin = true;
	var loggedInSuccess = isLoggedIn();
	if (!loggedInSuccess) {
		toggleLoginModule(null, DEFAULT_CONTEXT, true);
	}
	return loggedInSuccess;
	//todo: update this
    /*
	 var amg_user = readCookie("amg_user_info");
	 //if(amg_user != null && amg_user != "") { //only check if the cookie is not present
	 var request = new Ajax.Request('/user/checklogin', oOptions);
	 //YAHOO.util.Event.addListener(elementid, "UserLoggedInEvent", forwardUrl);
	 //alert("returning checkLogin");
	 //alert(document.getElementById(elementId));
	    linkUrl = document.getElementById(elementId);
	    //alert("linkUrl: " + linkUrl);
	//}
	//else {
	//	toggleLoginModule(null, DEFAULT_CONTEXT, true);
	//}
    return userLoggedIn;
    */
}

function submitenter(myfield,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	
	if (keycode == 13)
	   {
	   LoginModule.prototype.doLogin();
	   return false;
	   }
	else
	   return true;
}


// added for DE 80 TA 319 - cursor not displaying on register module
// hightlight and blurTextfield added to let user know where focus is in reg form
function highlightTextfield() {
	this.style.backgroundColor = '#e5f9ff';
	this.onblur  = blurTextfield;
}

function blurTextfield() {
	this.style.backgroundColor='#fff';
}





