/**
*	register-login
**/


/**
* LoginManager Singleton
* 
**/
Invite.LoginManager = (function() {

	//private static members
	var loginModal = null;
	var user = (typeof userInfo=='string')? userInfo : null;
	
	//private functions here
	function isSecureUrl(url) {
		return (url.indexOf("/u/") > -1);
	}
	function hasUser() {
		return (_USERID?true:false);
	}
	function isUserRegistered() {
		return (_REGISTERED);
	}
	function windowFactory(container, options) {
        var window_header = new Element('div', {className: 'window_header'});
        var window_title = new Element('div', {className: 'window_title'});
        var window_close = new Element('div', {className: 'window_close'});
        var window_contents = new Element('div', {className: 'window_contents'});
        var w = new Control.Modal(container, Object.extend(
        	{	
        		overlayOpacity:'0.8',
        		fade: 'true', 
        		fadeDuration: '1',
        		className: 'window', 
        		closeOnClick: window_close, 
        		draggable: window_header, 
        		insertRemoteContentAt: window_contents, 
        		afterOpen: function() {
            		window_title.update(container.readAttribute('title'));
            		if($('login-email-section').visible()) $('login-email').activate();
            		else $('username').activate();
        		}
        	}, options || {}));
        w.container.insert(window_header);
        window_header.insert(window_title);
        window_header.insert(window_close);
        w.container.insert(window_contents);
        return w;
	}

	//these are the public members.
	return { 
		//these are public static (by naming convention only)
		//how to act after successful authentication
		_ACTION_REDIRECT: "redirect",
		_ACTION_RELOAD: "reload",
		_ACTION_RESUME: "resume",
		
		//these are public methods
		clearErrorFields: function() {
			// clear some error fields
		    $('password-err-msg').update("");
		    $('email-field-error').update("");
		},
		createLoginModal: function(options) {
			this.clearErrorFields();
		    // begin instantiating the modal address book window
		    return windowFactory($('login-modal'), options);
		},
		//an accessor method for the private var
		getLoginModal: function() {
			return loginModal;
		},
		
		//used as the onSuccess for _ACTION_REDIRECT
		redirect: function(url) {
			window.location.href = url;
		},
		//used as the onSuccess for the _ACTION_RELOAD
		reload: function(callback) {
			//alert("in reload");
			// split the request on ? , 0 is main action, 1 is everything else
	        var requestString = (window.location.href + '').split('?');
	        var newUrl = requestString[0];
	        //alert(requestString);
	        // make a hash out of the parms on the right, this might be empty
	        var paramsHash = new Hash();
	        if (requestString[1]) {
	            paramsHash = $H(requestString[1].toQueryParams());
	        }
	        // add the one we need
	        paramsHash.set('cacheBust', new Date().getTime());
	        //show slider if this is a slider callback.
	        if (callback && callback.toString() && callback.toString().indexOf("Slider")) {
				paramsHash.set('showSlider', "true");
			}
	        // continuing to build the new url.
	        newUrl += "?" + paramsHash.toQueryString();
	        if (callback) newUrl += "#" + callback;
	        window.location.href = newUrl;
	        
		},
		//The Main Method
		//args: actionType = _ACTION_REDIRECT, _ACTION_RELOAD, _ACTION_RESUME
		//		callback = pass in a pointer to your function to run after login success.
		// 		url = the url to redirect to in case of _ACTION_REDIRECT
		authorize: function(actionType, callback, url) {
			//check for user that is fully registered
			if(hasUser()==false) {
				if(actionType == Invite.LoginManager._ACTION_RESUME) {
					this.onSuccess = function() {
						Invite.LoginManager.loginModal.close();
						callback;
					}
				} else if (actionType == Invite.LoginManager._ACTION_RELOAD) { 
					this.onSuccess = function() { Invite.LoginManager.reload(callback); }
				} else if (actionType == Invite.LoginManager._ACTION_REDIRECT) {
					this.onSuccess = function() { Invite.LoginManager.redirect(url); }
				}
				Invite.RegisterLogin.onSuccess = this.onSuccess;
				if (!loginModal) {
					loginModal = Invite.LoginManager.createLoginModal();
					Invite.RegisterLogin.bindKeys();
					$('login-email-section').show();
					//$('login-email').activate();
				}
				loginModal.open();
				return false;
			} else {
				//we have an logged in user.
				//let's see if they need to complete registration
				if(isUserRegistered()==false) {
					if(actionType == Invite.LoginManager._ACTION_RESUME) {
						this.onSuccess = function() {
							callback;
							Invite.LoginManager.inviteModal.close();
						}
					} else if (actionType == Invite.LoginManager._ACTION_RELOAD) { 
						this.onSuccess = function() { Invite.LoginManager.reload(callback); }
					} else if (actionType == Invite.LoginManager._ACTION_REDIRECT) {
						this.onSuccess = function() { Invite.LoginManager.redirect(url); }
					}
					//all the specific registration functions call Invite.RegisterLogin.onSuccess
					Invite.RegisterLogin.onSuccess = this.onSuccess;
					if (!loginModal) {
						loginModal = Invite.LoginManager.createLoginModal();
						Invite.RegisterLogin.bindKeys();
						$('registration-section').show();
						//$('username').activate();
					}
					loginModal.open();
					return false;
					
				} else {
					//user is logged in and fully registered
					 if(actionType == Invite.LoginManager._ACTION_RESUME) {
						callback();
						//controlWindowOptions = {beforeClose:this.onSuccess};
					} else if (actionType == Invite.LoginManager._ACTION_RELOAD) { 
						try {
							eval(callback);
						} catch(err) {
							try {
								eval(callback)();
							} catch(err) {
								alert("I can't run the callback function: " + callback);
							}
						}
						//controlWindowOptions = {beforeClose:this.onSuccess};
					} else if (actionType == Invite.LoginManager._ACTION_REDIRECT) {
						Invite.LoginManager.redirect(url);
						//controlWindowOptions = {beforeClose:this.onSuccess};
					}
					return true;
				}
			}
			
		},
		//This called on page load to continue any functions passed in the hash.
		//You must put this in the page onload method for it to run.
		resume:  function() {
			if (document.location.hash) {
				//some basic checking that it's just a method name.
				if( document.location.hash.indexOf("function")==-1 && document.location.hash.indexOf(";")==-1 && document.location.hash.indexOf(":")==-1 ) {
					try {
						var func = eval(document.location.hash.substr(1,document.location.hash.length));
						if(func) func();
					} catch (err) {
						//throw('INFO: Invite.EventStreamState could not execute hash as function');
						//do nothing
					}
				} else {
					throw('this is not safe');
				}
			}
		}// end last method
	} // return object
})(); // end login manager singleton (and run immediately)

Invite.RegisterLogin = {
		//ajax responses
		_AUTHENTICATION_PASSED: 200,
		_NEW_USER_REGISTRATION: 210,
		_REQUIRE_EMAIL_VALIDATION: 220,
		_REQUIRE_PASSWORD: 230,
		_AUTHORIZATION_FAILED: 301,

		//these are the callback functions with default...standalone implementation first.
		//The login modal overrides these when needed.
		onSuccess: function() {
			//alert("onSuccess");
			/*
			if(_INVITEID) {
                 var rndm = Math.round(Math.random() * 1000000);
                 window.location.href = '/invite2.iggli?inviteId=' + _INVITEID + '&nocache=' + rndm;
			} else {
                var eventPageRX = new RegExp(".*?event-details.*?$");
                // if we're not on the event page, go do my invites (not sure why) -cp
                if (eventPageRX.test(window.location.href) == false) {
                    window.location.href = '/u/my-invites.iggli';
                }
			}*/
			Invite.Misc.reload(false);//no callback needed.

            //return false;

		},
		onEmailValidation: function() {
			window.location.replace("/invite2/login-awaiting-validation.iggli");
		},
		onFailure: function() {},//not being used yet.
		onError: function() {} //not being used yet.
};



Invite.RegisterLogin.bindKeys = function() {
    Event.observe('login-email', 'keyup', function(event) {
        if (event.keyCode == Event.KEY_RETURN) {
            Invite.RegisterLogin.submitEmail();
        }
    });

    Event.observe('login-password', 'keyup', function(event) {
        if (event.keyCode == Event.KEY_RETURN) {
            Invite.RegisterLogin.submitPassword();
        }
    });
}

Invite.RegisterLogin.submitEmail = function() {
    /*
     If they ended up here they are NOT LOGGED IN

     There are 3 possibilities here:
     1. first time user, just create an invitee and let them participate, and complete registration:  _AUTHENTICATION_NEW_USER
     2. registered user with incomplete registration, they need to validate email : _NEW_USER_REGISTRATION
     3, registered user with complete registration, they need to enter password : _REQUIRE_PASSWORD

     Let's find out from the server about this user

     */

    // first validate email address
    if (validateEmail($('login-email').value, false, null) == false) {
        new Effect.Shake('login-email');
        $('email-field-error').update("That email looks funny");
        return false;
    }
    $('email-field-error').update("");
    

    var returnCode;
    new Ajax.Request('/ajax2/login-submit-email.iggli', {
        method:'get',
        evalJSON: "force",
        parameters: {email: $('login-email').value, inviteId:_INVITEID},
        onSuccess:function(transport) {
            var json, message;
            try {
            	//alert(transport.responseText);
	        	json = transport.responseJSON;
	        	//alert("json object is: " + Object.keys(json));
	        	//if(json.debug) alert(json.debug);
	        	if(json.responseCode) {
	        		// first timer
		            if (json.responseCode == Invite.RegisterLogin._NEW_USER_REGISTRATION) {
		            	//we're going to finish this registration
		                Invite.RegisterLogin.showRegistration();
		            } else  
		            // lite vite user
		            if (json.responseCode == Invite.RegisterLogin._REQUIRE_EMAIL_VALIDATION) {
		                Invite.RegisterLogin.onEmailValidation();
		            } else 
		            // thick vite user
		            if (json.responseCode == Invite.RegisterLogin._REQUIRE_PASSWORD) {
		            	Invite.RegisterLogin.showPassword();
		                // they will submit pw
		            } else {
		            	alert("Something went wrong. " + json.message);
		            	Invite.LoginManager.getLoginModal().close();
		            }
	        	
	        	} else {
	            	//it's a json object without the expected response code.  Pray it has a message.
	            	//displayMessage(json.message, "error");
	            	alert(json.message);
		        }
	        } catch(err) {
	        	//not a json object probably.
	        	//displayMessage(transport.responseText, "error");
	        	alert("error: " + transport.responseText);
	        }
            //alert('success ' + returnCode);
        }, onError:function(transport) {
            returnCode = transport.responseText;
            //alert('error: ' + returnCode);
        }, onComplete:function(transport) {
            returnCode = transport.responseText;
            //alert('complete ' + returnCode);
        }
    });

    return false;
};

Invite.RegisterLogin.submitPassword = function() {
    var returnCode;
    new Ajax.Request('/ajax2/login-submit-password.iggli', {
        method:'post',
        evalJSON: "force",
        parameters: {email: $('login-email').value, password: $('login-password').value, inviteId:_INVITEID},
        onSuccess:function(transport) {
            
            var json, message;
            try {
            	//alert(transport.responseText);
	        	json = transport.responseJSON;
	        	//alert("json object is: " + Object.keys(json));
	        	//if(json.debug) alert(json.debug);
	        	if (json.responseCode) {
	        		// first timer
		            if (json.responseCode == Invite.RegisterLogin._AUTHENTICATION_PASSED) {
		                Invite.RegisterLogin.onSuccess();
		            } else {
		            	new Effect.Shake('login-password');
                		$('password-err-msg').update("incorrect email or password");
		            }
	        	
	        	} else {
	            	//it's a json object without the expected response code.  Pray it has a message.
	            	//displayMessage(json.message, "error");
	            	new Effect.Shake('login-password');
                	$('password-err-msg').update("Oops: " + json.message);
		        }
	        } catch(err) {
	        	//not a json object probably.
	        	//displayMessage(transport.responseText, "error");
	        	//alert("not json");
	        	new Effect.Shake('login-password');
                $('password-err-msg').update(transport.responseText);
	        }

        }, 
        onError:function(transport) {
        	//alert("onError here");
            new Effect.Shake('login-password');
            $('password-err-msg').update(transport.responseText);
        }
    });
}

Invite.RegisterLogin.validateRegistration = function() {
	var clearAllRegistrationValidationErrors = function() {
	    $('username-validation').update('');
	    $('password-validation').update('');
	    $('terms-validation').update('');
	}
    clearAllRegistrationValidationErrors();
    
    if ($F('username').length < 2) {
        $('username').focus();
        $('username-validation').update('&raquo; Let people know who this is.');
        //new Effect.Highlight('new-user-section');
        new Effect.Shake('username');
        return false;
    }

    /* 
    if (validateEmail($F('email'), false) == false) {
        $('email').focus();
        $('email-validation').update('&raquo; This email address doesn\'t look right.');
        //new Effect.Highlight('new-user-section');
        new Effect.Shake('reg-email');
        return false;
    } 
    */
    if ($F('password').length < 5) {
        $('password').focus();
        $('password-validation').update('&raquo; Minimum of 5 characters please.');
        //new Effect.Highlight('new-user-section');
        new Effect.Shake('password');
        return false;
    }
    /* No more confirm
    if ($F('password-confirm').length < 5) {
        $('password-confirm').focus();
        $('password-confirm-validation').update('&raquo; Oops. You must have overlooked this.');
        //new Effect.Highlight('new-user-section');
        new Effect.Shake('password-confirm');
        return false;
    }
    if ($F('password') != $F('password-confirm')) {
        $('password-confirm').focus();
        $('password-confirm-validation').update('&raquo; This doesn\'t match the password you entered above.');
        //new Effect.Highlight('new-user-section');
        new Effect.Shake('password-confirm');
        return false;
    }
	*/
    if ($F('terms') != "true") {
        $('terms').focus();
        $('terms-validation').update('&raquo; You must accept our Terms of Service to use iggli.');
        return false;
    }

    return true;
}

Invite.RegisterLogin.showRegistration = function() {
	Effect.BlindUp('login-email-section', { duration: 0.4, afterFinish: function() {
			Effect.BlindDown('registration-section', {duration: 0.4, afterFinish: function() {
					$('username').activate();
				} 
			});
		}
	});
}

Invite.RegisterLogin.showPassword = function() {
	Effect.BlindUp('login-email-section', { duration: 0.4, afterFinish: function() {
			Effect.BlindDown('login-password-section', {duration: 0.4, afterFinish: function() {
					$('login-password').activate();
				} 
			});
		}
	});
}
	
Invite.RegisterLogin.completeRegistration = function() {
	if (Invite.RegisterLogin.validateRegistration()) {
		 $('submit-link-processing').show();
         $('submit-link').hide();
         var partnerPromos = false;
         if ($('partnerPromos')) {
          partnerPromos = $('partnerPromos').checked;
         }
	    new Ajax.Request('/ajax2/complete-registration-submit.iggli', {
	        method:'post',
	        parameters:{
	            username:$('username').value,
	            password:$('password').value,
	            inviteId:$('hidden-invite-id').value,
	            partnerPromos:partnerPromos
	            },
	        onSuccess:function() {
	            Invite.RegisterLogin.onSuccess();
	        },
	        onError:function(transport) {
	            alert(transport.responseText);
	            $('submit-link-processing').hide();
	            $('submit-link').show();
	            Invite.RegisterLogin.onError();
	        },
	        onComplete:function() {
	        	
	        }
	    }); // end AJAX request
	}
}

//-----------------------------------------------------------------------------
//
//
//
//-----------------------------------------------------------------------------
function onFBUserConnected() {
	alert('whos calling this');
    $('fb-connected-true').show();
    $('fb-connected-false').hide();
}


//-----------------------------------------------------------------------------
//
//
//
//-----------------------------------------------------------------------------
function onFBUserNotConnected() {
    $('fb-connected-true').hide();
    $('fb-connected-false').show();
}



