//login.js
var first_name;
var user;
var username;
var time = parseInt(((new Date).getTime()) / 1000);
var hash;
var loggedInUserData = {};

var login_urls = {
	info : "/sso/identity/info",
	registration : "/sso/registration/create",
	login : "/sso/identity/login",
	logout : "/sso/identity/logout",
	forgot_password : "/sso/identity/password"
};

$(document).ready(function(){
	username = $.cookie('loginstatus');
	//check to see if there's a login status cookie
	if(username){
		//create the hash for the SSOS server
		$.ajax({
			type: 'POST',
			url: "/ajax/getUserInfo",
			data: {	
				name: username
			},
			success: function(response){
				response = $.parseJSON(response);

				if(response.error){
					noLogin();
					$(document).trigger("loginComplete", [ false ]);
					$(document).trigger("gigyaLoginComplete", [ false ]);				
				} else {
					first_name = response.success.user.first_name;
					loggedIn();
					$(document).trigger("loginComplete", [ true, response ]);					
				}
			}
		});
	} else {
		noLogin();
		$(document).trigger("loginComplete", [ false ]);
		$(document).trigger("gigyaLoginComplete", [ false ]);
	}
});
function loggedIn(){
	$.get("/loggedin", function(response){
		//insert the HTML
		$("#login").html(response);

		//set settings link
		$("#settings-link").attr("href", $("#settings-link").attr("href") + "/user/" + username);
		
		//check with Gigya to see if you're logged in.
		var params = {  
			provider: 'facebook',
			callback: get_info_initial_callback
		};
		
		aetn.socialize.getUserInfo(params);
		

		$("#logout").click(function(e){
			e.preventDefault();
			var params = {
				callback: socialze_logout_callback
			}
			aetn.socialize.logout(params);
		});
	});
}
function noLogin(){
	$.get("/notloggedin", function(response){
		$("#login").html(response);
		$("#login .bio-select-drop-down").styled_select();	

		//initialize login
		$("#login .dialog .ui-icon-closethick").click(function(){
			$(this).parent().dialog("close");
		});

		$("#facebook-information-dialog").dialog({
			autoOpen: false,
			dialogClass: 'no-title login-dialog facebook-information-dialog',
			modal: false,
			show: 'fade',
			resizable: false,
			width: 425
		});
				
		//event handlers
		$("#login .fb-connect-header").unbind("click");
		$("#login .fb-connect-header").click(function(e){
			var params = {  
	             provider: 'facebook',
	             facebookExtraPermissions : "friends_birthday,friends_education_history,friends_hometown,friends_likes,friends_location,friends_relationship_details,friends_relationships,friends_religion_politics",
	             callback: 'socialze_login_callback'
			};
			aetn.socialize.login(params);
		});
		
		$("#facebook-sign-in").hoverIntent({
	        sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
	        interval: 200, // number = milliseconds for onMouseOver polling interval
	        timeout: 0, // number = milliseconds delay before onMouseOut
	        over: function(e) {
				$("#facebook-information-dialog").dialog("open");
				$("#facebook-information-dialog").dialog("widget").position({
				   	my: 'right top',
				    at: 'right bottom',
				    collision: 'none',
				    offset:	'0 10px',
				    of: $("#login")
				 });
			},
			out: function(e) {
				if(!$.contains($(this)[0], e.relatedTarget) && !$(e.relatedTarget).hasClass("universal-rollover")){
					$("#facebook-information-dialog").dialog("close");
				}
			}
		});
		
		$("#login .dialog").dialog({
			autoOpen: false,
			dialogClass: 'no-title login-dialog',
			modal: true,
			show: "fade",
			resizable: false,
			width:		350,
			position: ["center", 34]
		});
		
		//register
		$("#login-register-now, .registration-handle").click(function(){
			$(":ui-dialog").dialog("close");
			$("#registration-dialog").dialog("open");
			trackRegistrationStart();
		});
		$("#registration-form").validate({
			rules: {
				"registration-email-address"	: "required email",
			    "registration-display-name"		: {
			    	required: true,
			        rangelength: [4, 32]
			    },
			    "registration-first-name"		: "required",
			    "registration-last-name"		: "required",
			    "registration-password"			: "required",
			    "registration-confirm-password"	: {
			      equalTo: "#registration-password"
			    },
			    "registration-zip-code"			: "required",
			    "registration-terms"			: "required"
			},
			errorPlacement: function(error, element) {
				error.appendTo(element.parent());
			},
			submitHandler: function(form) {
				$.ajax({
					type: 'POST',
					url: login_urls.registration,
					data: {	
						pid: "123",
						name: $("#registration-display-name").val(),
						first_name: $("#registration-first-name").val(),
						last_name: $("#registration-last-name").val(),
						email: $("#registration-email-address").val(),
						dob: $("#registration-year").val() + "-" + $("#registration-month").val() + "-" + $("#registration-day").val(),
						country_code: $("#registration-country").val(),
						zip: $("#registration-zip-code").val(),
						terms: "1",
						pass: $("#registration-password").val()
					},
					success: function(response){
						response = $.parseJSON(response);
						if(response.error){
							for(var i = 0; i < response.error.messages.error.length; i++){
								$(form).before('<div class="error server-error">' + response.error.messages.error[i] + '</div>');
							}
							$(form).show().parent().find(".loading").remove();
						} else {
							trackRegistrationNonFacebook();
							//Allow time for track track registration ominture to complete
							setTimeout("window.location.reload();",1000);
						}
					},
					error: function(jqXHR, textStatus, errorThrown){
					}
				});
				$(form).after('<div class="loading" style="height:' + $(form).height() + 'px;"></div>').hide().parent().find(".server-error").remove();
			}
		});
		
		//sign in
		$("#login-sign-in, .sign-in-handle").click(function(){
			$(":ui-dialog").dialog("close");
			$("#sign-in-dialog").dialog("open");
		});
		$("#sign-in-form").validate({
			rules: {
				"sign-in-email-address"		: "required email",
			    "sign-in-password"			: "required"
			},
			submitHandler: function(form) {
				$.ajax({
					type: 'POST',
					url: login_urls.login,
					data: {	
						pid: "123",
						name: $("#sign-in-email-address").val(),
						pass: $("#sign-in-password").val()
					},
					success: function(response){
						response = $.parseJSON(response);
						if(response.error){
							for(var i = 0; i < response.error.messages.error.length; i++){
								$(form).before('<div class="error server-error">' + response.error.messages.error[i] + '</div>');
							}
							$(form).show().parent().find(".loading").remove();
						} else {
							trackLoginNonFacebook();
							aetn.socialize.notifyLogin({callback: function(){window.location.reload();}});
						}
					},
					error: function(jqXHR, textStatus, errorThrown){
					}
				});
				$(form).after('<div class="loading" style="height:' + $(form).height() + 'px;"></div>').hide().parent().find(".server-error").remove();
			}
		});
		
		//forgot-password
		$(".forgot-password").click(function(){
			$(":ui-dialog").dialog("close");
			$("#forgot-password-dialog").dialog("open");
		});
		$("#forgot-password-form").validate({
			rules: {
				"forgot-password-email-address"		: "required email"
			},
			submitHandler: function(form) {
				$.ajax({
					type: 'POST',
					url: login_urls.forgot_password,
					data: {	
						pid: "123",
						mail: $("#forgot-password-email-address").val()
					},
					success: function(response){
						response = $.parseJSON(response);
						if(response.error){
							$(form).before('<div class="error server-error">No account found for specified email address.</div>');
							$(form).show().parent().find(".loading").remove();
						} else {
							$(form).parent().find(".loading").html("<p><strong>" + response.success.messages.status[0] + "</strong></p>").removeClass('loading');
						}
					},
					error: function(jqXHR, textStatus, errorThrown){
					}
				});
				$(form).after('<div class="loading" style="height:' + $(form).height() + 'px;"></div>').hide().parent().find(".server-error").remove();
			}
		});
	});
}

function socialze_login_callback(response){
	if(response.status == true){
		trackLoginViaFacebook();
		//Allow time for track login ominture to complete
		setTimeout("window.location.reload();",1000);
	} else if(response.status == "notfound"){
		if(username){ //if logged in with account but not yet account linked
			socialize_link_accounts();
		}else{ //if no account
			var params = {  
				provider: 'facebook',
				callback: socialize_registration_callback
			};
			aetn.socialize.getUserInfo(params);
		} 
	} else {
		alert("Unexpected system error.");
	};
}

function socialize_link_accounts(){
	var params = {
		callback : 'socialize_link_callback'
	};
	aetn.socialize.linkAccountToCurrentUser(params);
}


/* Callbacks */
function get_info_initial_callback(response){
	if(response.user.isConnected){
		user = {
			name: response.user.firstName,
			photo: response.user.photoURL
		}
		$("#login").addClass("socialized").prepend(
			'<img src="' + response.user.photoURL + '"/>' +
			'<div id="socialized-greeting"><span>Hi ' + response.user.firstName +'!</span></div>'
		);

		$(document).trigger("gigyaLoginComplete", [ true, response ]);

	} else {
		$(document).trigger("gigyaLoginComplete", [ false ]);

		//create non-socialized HTML
		$(".logged-in").prepend(
			'<li>' +
				'<img class="fb-connect-header" src="/assets/images/facebook-connect.png"/>' +
				'<div id="facebook-information-dialog" class="dialog">' +
					'<span id="registration-close" class="ui-icon ui-icon-closethick">close</span>' +
					'<h3><span>When You Connect</span></h3>' +
					'<p>You can enjoy the fully personalized experience of BIO. Here are some features:</p>' +
					'<ul>' +
						'<li>See what you and your friends have in common with famous icons.</li>' +
						'<li>Share your activity with Facebook friends.</li>' +
						'<li>Express your ideas & see what your friends have to say.</li>' +
					'</ul>' +
				'</div>' +
				'<span id="login-greeting">Hi <span class="username">' + first_name +'</span></span>' +
				'<li class="divider">&middot;</li>' +
			'</li>'
		);
		
		//information popup
		$("#login .dialog .ui-icon-closethick").click(function(){
			$(this).parent().dialog("close");
		});
		$("#facebook-information-dialog").dialog({
			autoOpen: false,
			dialogClass: 'no-title login-dialog facebook-information-dialog',
			modal: false,
			show: 'fade',
			resizable: false,
			width: 425
		});
		
		//event handlers
		$("#login .fb-connect-header").click(function(e){
			var params = {  
	             provider: 'facebook',
	             callback: 'socialze_login_callback'
			};
			aetn.socialize.login(params);
		}).mouseover(function(e){
			$("#facebook-information-dialog").dialog("open");
			$("#facebook-information-dialog").dialog("widget").position({
			   	my: 'right top',
			    at: 'right bottom',
			    collision: 'none',
			    offset:	'0 10px',
			    of: $("#login")
			 });			
			$("#login .fb-connect-header").unbind("mouseover");
		});
	}
}

function socialze_logout_callback(response){
	$.ajax({
		type: 'POST',
		url: "/ajax/logout",
		data: {	
			name: username
		},
		success: function(response){
			window.location.reload();
		}
	});
}

function socialize_link_callback(response){
	trackRegistrationViaFacebook();
	//Allow time for track registration ominture to complete
	setTimeout("window.location.reload();",1000);
}

function socialize_registration_callback(response){
	
	
	if(response.user){
		$(document).trigger("gigyaLoginComplete", [ true, response ]);
	}
	else{
		$(document).trigger("gigyaLoginComplete", [ false ]);
	}
	
	if(response.user){
		//create the hash for the SSOS server
		$.ajax({
			type: 'POST',
			url: "/ajax/getUserInfo",
			data: {	
				name: response.user.email
			},
			success: function(login_response){
				login_response = $.parseJSON(login_response);
				if(login_response.success){
					//socialize sign in
					$("#socialize-sign-in-form").validate({
						rules: {
							"socialize-sign-in-email-address"		: "required email",
						    "socialize-sign-in-password"			: "required"
						},
						submitHandler: function(form) {
							$.ajax({
								type: 'POST',
								url: login_urls.login,
								data: {	
									pid: "123",
									name: $("#socialize-sign-in-email-address").val(),
									pass: $("#socialize-sign-in-password").val()
								},
								success: function(response){
									response = $.parseJSON(response);
									if(response.error){
										for(var i = 0; i < response.error.messages.error.length; i++){
											$(form).before('<div class="error server-error">' + response.error.messages.error[i] + '</div>');
										}
										$(form).show().parent().find(".loading").remove();
									} else {
										socialize_link_accounts();
									}
								},
								error: function(jqXHR, textStatus, errorThrown){
								}
							});
							$(form).after('<div class="loading" style="height:' + $(form).height() + 'px;"></div>').hide().parent().find(".server-error").remove();
						}
					});
					
					$("#socialize-sign-in-message").html('<img src="'+ response.user.thumbnailURL + '"/><p><span class="user">' + response.user.nickname + '</span>, looks like you already have a Bio account. Log In to connect your Bio and Facebook accounts.</p>');
					
					$(":ui-dialog").dialog("close");
					$("#socialize-sign-in-dialog").dialog("open");		
				} else {
					//initalize socialize-register-form
					$("#socialize-registration-form").validate({
						rules: {
							"socialize-registration-email-address"	: "required email",
						    "socialize-registration-display-name"		: {
						    	required: true,
						        rangelength: [4, 32]
						    },
						    "socialize-registration-first-name"			: "required",
						    "socialize-registration-last-name"			: "required",
						    "socialize-registration-password"			: "required",
						    "socialize-registration-zip-code"			: "required",
						    "socialize-registration-terms"				: "required"
						},
						errorPlacement: function(error, element) {
							error.appendTo(element.parent());
						},
						submitHandler: function(form) {
							$.ajax({
								type: 'POST',
								url: login_urls.registration,
								data: {	
									pid: "123",
									name: $("#socialize-registration-display-name").val(),
									fisrt_name: $("#socialize-registration-first-name").val(),
									last_name: $("#socialize-registration-last-name").val(),
									email: $("#socialize-registration-email-address").val(),
									dob: $("#socialize-registration-year").val() + "-" + $("#socialize-registration-month").val() + "-" + $("#socialize-registration-day").val(),
									country_code: $("#socialize-registration-country").val(),
									zip: $("#socialize-registration-zip-code").val(),
									terms: "1",
									pass: $("#socialize-registration-password").val()
								},
								success: function(response){
									response = $.parseJSON(response);
									if(response.error){
										for(var i = 0; i < response.error.messages.error.length; i++){
											$(form).before('<div class="error server-error">' + response.error.messages.error[i] + '</div>');
										}
										$(form).show().parent().find(".loading").remove();
									} else {
										socialize_link_accounts();
									}
								},
								error: function(jqXHR, textStatus, errorThrown){
								}
							});
							$(form).after('<div class="loading" style="height:' + $(form).height() + 'px;"></div>').hide().parent().find(".server-error").remove();
						}
					});		
					
					//prepopulate fields
					$("#socialize-registration-email-address").val(response.user.email);
					$("#socialize-registration-month").val(response.user.birthMonth);
					$("#socialize-registration-day").val(response.user.birthDay);
					$("#socialize-registration-year").val(response.user.birthYear);
					$("#socialize-registration-country").val(response.user.country);
					$("#socialize-registration-zip-code").val(response.user.zip);
					$("#socialize-registration-message").html('<img src="'+ response.user.thumbnailURL + '"/><p><span class="user">' + response.user.nickname + '</span>, sign up to connect your BIO and Facebook accounts.</p>');
					
					//generate random password
					var password = "AE";
					for(var i = 0; i < 8; i++){
						password = password + Math.floor(Math.random()*10);
					}
					$("#socialize-registration-password").val(password);
					
					$(":ui-dialog").dialog("close");
					$("#socialize-registration-dialog").dialog("open");									
				}
			}
		});	
	} 
}

function disqus_logout(){
	var params = {
			callback: socialze_logout_callback
		}
		aetn.socialize.logout(params);
}
