var AccountAjaxUrl = "http://www.sonaalab.co.uk/account-ajax";

function fbConnectLogin (){
	var url			= AccountAjaxUrl,
		data		= "&service=login&facebook=true";
	
	$.ajax({  
		type: "POST",  
		url: url,  
		data: data,  
		success: function(html){
			alert(html);
			if (html == ""){
				$("#account").hide().load(url, function(){
					$("#account").fadeIn("slow");
				});
			}
		} 
	});
}

function fbConnectLogout (){
	var url			= AccountAjaxUrl,
		data		= "&service=logout&facebook=true";
	
	$.ajax({  
		type: "GET",  
		url: url,  
		data: data,  
		success: function(html){
			$("#account").hide().html(html).fadeIn("slow");
			$('body').data('label2valueInside')();
			$('body').data('hijaxRegLoginInside')();
		}
	});
}

$(document).ready(function () {
	$('body').data('label2valueInside', label2value);
	$('body').data('hijaxRegLoginInside', hijaxRegLogin);
							
							
	// Pick random colour from array and add class to logo
	var bgClasses = ['pink-bg','blue-bg','green-bg','yellow-bg'],
		bgChoice = Math.floor(Math.random() * bgClasses.length),
		colorClasses = ['blue','green','black','yellow','pink'],
		colorChoice,
		i= 0;
		
	// Set random background color to logo
	$("#logo a").attr("class", bgClasses[bgChoice]);
	$("#tag-cloud ul").children("li").each(function () {
		if (i == colorClasses.length) {
			i = 0;
		}
		$(this).children("a").addClass(colorClasses[i]);
		i++;
	});
	
	// Add scroll to anchor links
	//$('a[href*="#"]').anchorAnimate();
	
	/*$('a[href*=#]').click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
			var $target = $(this.hash);
			$target = $target.length && $target || $('[id=' + this.hash.slice(1) + ']');
			if ($target.length) {
				var targetOffset = $target.offset().top;
				$('html,body').animate({scrollTop: targetOffset}, 1000);
				return false;
			}
		}
	});*/

							
	// Add Hover to Friends links and footer links
	$("#friends li a, #social a").hover(function(){
		$('> span', this).fadeIn(500); // This should set the opacity to 100% on hover
	},function(){
		$('> span', this).fadeOut(250); // This should set the opacity back to 60% on mouseout
	});
	
	// Add AJAX to form depending on which is currently displayed
	if ($("#options").length > 0 || $("#wlpeResetForm").length > 0){
		hijaxRegLogin();
	} else if ($("#wlpeActivateForm").length > 0) {
		hijaxActivate();
	} else if ($("#wlpeUserForm").length > 0 || $("#managerUser").length > 0) {
		hijaxSignout();
	}
	
	// Newsletter Signup functionality vars
	var $newsletter = $('#newsletterContainer'),
		$newsletterFrm = $('#newsletterForm'),
		$newsletterToggle = $("#newsletter h1"),
		newsletterHeight = $newsletter.height(),
		newsletterAction = "http://www.sonaamail.co.uk/t/y/s/jkptr/",
		successMsg = "Thank you for subscribing to our newsletter";
	
	$newsletter.hide().css({ height : 0 });
	
	$newsletterFrm.validate({
		rules: {
			"cm-name": "required",
			"cm-jkptr-jkptr": {
				required: true,
				email: true
			}
		},
		messages: {
			"cm-name": "Please enter your name",
			"cm-jkptr-jkptr": "Please enter a valid email address"
		},
		submitHandler: function() { 
			var action		= $newsletterFrm.attr("action"),
				name		= $('#name').attr('value'),
				email		= $('#jkptr-jkptr').attr('value'),
				button		= $newsletterFrm.children("div.submit-container").html(),
				str 		= $newsletterFrm.serialize(),
				data 		= str + "&action=" + action;
				
			$newsletterFrm.children("div.submit-container").empty().append('<img src="/assets/images/layout/icon-loading-yellow.gif" alt="" />');
			
			submitNewsletter (data, "subscribe");
			return false;
		}
	});	
	
	// Click event for newsletter toggle
	$newsletterToggle.attr("style", "cursor:pointer;").attr("class", "closed").click(function () {
		if ($("#options").length > 0){
			if ( $signin.is(':visible') ) {
				toggleSignin(false);
			} else if ( $reset.is(':visible') ) {
				toggleReset(false);
			} else if ( $reg.is(':visible') ) {
				toggleReg(false);
			}
		}
		
		if ( $newsletter.is(':visible') ) {																			   
			toggleNewsletter (false);
		} else {
			toggleNewsletter (true);
		}
	});
	
	// variables for header form toggle
	var $reg, $regToggle, $signin, $signinToggle, $reset, $resetToggle, resetMsg, regHeight, signinHeight, resetHeight, closeBtn;
	
	// Function to toggle display of newsletter form
	function toggleNewsletter (action, callback) {
		if(action == false) {
			$("label.error").remove();
			$newsletterToggle.attr("class", "closed");
			$newsletter.animate({ height: 0 }, 
				{ duration: 250, complete: function () {
					$newsletter.hide();
				} 
			});
		} else {
			$newsletterToggle.attr("class", "open");
			$newsletter.show().animate({ height : newsletterHeight }, { duration: 250 });
		}
	}
	
	// Function to toggle display of newsletter form
	function submitNewsletter (data, response, username, pass) {
		$.ajax({  
			type: "POST",  
			url: "/proxy.php",  
			data: data,  
			success: function(html){
				if(response == "subscribe"){
					$newsletter.append("<p id=\"success\" style=\"display:none;\">"+successMsg+"</p>");
					$newsletterFrm.fadeOut("slow",function callback() {
						$newsletter.children("p").fadeIn("slow");											
					});
				} else if(response == "register") {
					regSuccess(username, pass);
				}
			}  
		});
	}
	
	// Function to toggle display of newsletter form
	function regSuccess (username, pass) {
		$user_temp = $("#username_temp");
		$pass_temp = $("#password_temp");
		
		$user_temp.hide();
		$("#username").attr("value", username).attr("tabindex",$user_temp.attr("tabindex")).show();
		$pass_temp.hide();
		$("#password").attr("value", pass).attr("tabindex",$pass_temp.attr("tabindex")).show();
		
		toggleReg(false, "complete");
	}
	
	// Register form toggle
	function toggleReg (action, next) {
		if(action == false) {
			$("label.error").remove();
			$reg.children("a.link-close").remove();
			$reg.animate({ height: 0 }, 
				{ duration: 350, complete: function () {
					$reg.hide();
					$regToggle.parent().next().removeClass("item-first");
					$regToggle.parent().removeClass("pink-bg").addClass("pink");
					if (next == "complete") {
						$regToggle.parent().remove();
						toggleSignin(true);
					} else if(next == "signin"){
						toggleSignin(true);
					}
				} 
			});
		} else {
			$regToggle.parent().next().addClass("item-first");
			$regToggle.parent().removeClass("pink").addClass("pink-bg");
			$reg.show().animate({ height : regHeight }, 
				{ duration: 350, complete: function () {
					$reg.prepend(closeBtn);
					$("#account a.link-close").click(function (e) {
						e.preventDefault();
						toggleReg(false);
					});
				}
			});
		}
	}
	
	// Login form toggle
	function toggleSignin (action, next) {
		if(action == false) {
			$("label.error").remove();
			$signin.children("a.link-close").remove();
			$signin.animate({ height: 0 }, 
				{ duration: 350, complete: function () {
					$signin.hide();
					$signinToggle.parent().removeClass("active");
					if (next == "complete") {
						$("#account").hide().load(AccountAjaxUrl, function(){
							$("#account").fadeIn("slow");
							hijaxSignout();
						});
					} else if(next == "reg"){
						toggleReg(true);
					} else if(next == "reset"){
						toggleReset(true);
					}
				} 
			});
		} else {
			$signinToggle.parent().addClass("active");
			$signin.show().animate({ height : signinHeight }, 
				{ duration: 350, complete: function () {
					$signin.prepend(closeBtn);
					$("#account a.link-close").click(function (e) {
						e.preventDefault();
						toggleSignin(false);
					});
				}
			});
		}
	}
	
	// Login form toggle
	function toggleReset (action, next) {
		if(action == false) {
			$("label.error").remove();
			$reset.children("a.link-close").remove();
			$reset.animate({ height: 0 }, 
				{ duration: 350, complete: function () {
					$reset.hide();
					$signinToggle.parent().removeClass("active");
					if (next == "complete") {
						$("#account").hide().load(AccountAjaxUrl, function(){
							$("#account").fadeIn("slow");
							hijaxSignout();
						});
					} else if(next == "reg"){
						toggleReg(true);
					} else if(next == "signin"){
						toggleSignin(true);
					}
				} 
			});
		} else {
			$signinToggle.parent().addClass("active");
			$reset.show().animate({ height : resetHeight }, 
				{ duration: 350, complete: function () {
					$reset.prepend(closeBtn);
					$("#account a.link-close").click(function (e) {
						e.preventDefault();
						toggleReset(false);
					});
				}
			});
		}
	}	
	
	// Hijax the original functionality of the register and signout forms
	function hijaxRegLogin () {
		// Login/Register Form vars
		$reg = $('#wlpeUserRegisterForm'),
		$regToggle = $('#toggle-reg'),
		$signin = $('#wlpeLoginForm'),
		$signinToggle = $('#toggle-login'),
		$reset = $('#wlpeResetForm'),
		$resetToggle = $('#account .toggle-reset'),
		resetMsg = '<p>An email has been sent to you with instructions on how to activate your <br />new password.</p><p class="resetSuccessBtn"><a id="show-login" class="submit-basic toggle-reset" href="/account">Login</a></p>',
		regHeight = $reg.height(),
		signinHeight = $signin.height(),
		resetHeight = $reset.height(),
		closeBtn = "<a href=\"#\" class=\"link-close\">Close</a>",
		clearBtn = "<a href=\"#\" class=\"link-clear\">Clear Errors</a>";
		
		//alert(signinHeight);
		
		$reg.prepend(clearBtn);
		$signin.prepend(clearBtn);
		$reset.prepend(clearBtn);
		$("#wlpeUserRegisterForm a.link-clear").click(function (e) {
			e.preventDefault();
			$("#wlpeUserRegisterForm label.error").remove();
		});
		$("#wlpeLoginForm a.link-clear").click(function (e) {
			e.preventDefault();
			$("#wlpeLoginForm label.error").remove();
		});
		$("#wlpeResetForm a.link-clear").click(function (e) {
			e.preventDefault();
			$("#wlpeResetForm label.error").remove();
		});
		
		$reg.css({ height : 0 }).validate({
			rules: {
				fullname: "required",
				reg_username: {
					required: true,
					rangelength: [2, 20]
				},
				email: {
					required: true,
					email: true
				},
				reg_password: {
					required: true,
					minlength: 6
				},
				reg_password_confirm: {
					required: true,
					minlength: 6,
					equalTo: "#reg_password"
				},
				tos: "required"
			},
			messages: {
				fullname: "Please provide a name",
				reg_username: {
					required: "Please provide a username",
					rangelength: "Your username must be between 2 and 20 characters"
				},
				email: "Please enter a valid email address",
				reg_password: {
					required: "Please provide a password",
					minlength: "Your password must be at least 6 characters long"
				},
				reg_password_confirm: {
					required: "Please provide a password",
					minlength: "Your password must be at least 6 characters long",
					equalTo: "Please enter the same password as above"
				},
				tos: "Please accept our terms of service"
			},
			submitHandler: function() { 
				var url			= AccountAjaxUrl,
					name		= $('#fullname').attr('value'),
					username	= $('#reg_username').attr('value'),
					email		= $('#email').attr('value'),
					pass		= $('#reg_password').attr('value'),
					passcon		= $('#reg_password_confirm').attr('value'),
					subscribe	= $('#is_subscribed').attr('checked'),
					tos			= $('#tos').attr('value'),
					button		= $reg.children("div.submit-container").html(),
					service		= $('#wlpeSaveRegisterButton').attr('value');//,
					data		= "fullname="+ name +"&reg_username="+ username +"&email="+ email +"&reg_password="+ pass +"&reg_password_confirm="+ passcon +"&tos="+ tos +"&service="+ service;
					
				$reg.children("label.error").remove();
				$reg.children("div.submit-container").empty().append('<img src="/assets/images/layout/icon-loading-pink.gif" alt="" />');
				
				$.ajax({  
					type: "POST",  
					url: url,  
					data: data,  
					success: function(html){  
						if (html == ""){
							if(subscribe == 1){
								var subscribeData = "cm-name="+ name +"&cm-jkptr-jkptr="+ email +"&action="+ newsletterAction;
								submitNewsletter (subscribeData, "register", username, pass);
							} else {
								regSuccess(username, pass);
							}
						} else {
							if (html.indexOf("username") != -1) {
								$("#reg_username").after("<label for=\"reg_username\" generated=\"true\" class=\"error\">"+html+"</label>");
							} else if (html.indexOf("password") != -1) {
								$("#reg_password").after("<label for=\"reg_password\" generated=\"true\" class=\"error\">"+html+"</label>");
							} else {
								var $errors = $reg.children("p.basic-errors"), errorsHeight;
								$errors.html(html);
								errorsHeight = $errors.height();
								$errors.addClass("black-bg")
										.css({ height : 0 })
										.animate({ height : errorsHeight },{ duration: 350 });
							}
							
							$reg.children("div.submit-container").html(button);
						}
					} 
				});
				return false;
			}
		});		
		
		$signin.css({ height : 0 }).validate({
			rules: {
				username: "required",
				password: "required"
			},
			messages: {
				username: "Please enter your username",
				password: "Please enter your password"
			},
			submitHandler: function() { 
				var url			= AccountAjaxUrl,
					email		= $('#username').attr('value'),
					pass		= $('#password').attr('value'),
					button		= $signin.children("div.submit-container").html(),
					service		= $('#wlpeLoginButton').attr('value'),
					data		= "username="+ email +"&password="+ pass +"&service="+ service;
				
				$signin.children("label.error").remove();
				$signin.children("div.submit-container").empty().append('<img src="/assets/images/layout/icon-loading-blk.gif" alt="" />');
				
				$.ajax({  
					type: "POST",  
					url: url,  
					data: data,  
					success: function(html){
						if (html == ""){
							toggleSignin(false, "complete");
						} else {
							if (html.indexOf("The username you entered does not exist") != -1) {
								// if username doesn't exist check against manager login functionality
								$.ajax({  
									type: "POST",  
									url: "http://www.sonaalab.co.uk/manager/processors/login.processor.php",  
									data: data+"&ajax=1",  
									success: function(response){
										if (response.indexOf("http://") != -1 || response == "") {
											//toggleSignin(false, "complete");
											window.location.reload();
										} else {
											if (response.indexOf("username") != -1) {
												$("#username").after("<label for=\"username\" generated=\"true\" class=\"error\">"+response+"</label>");
											} else if (response.indexOf("password") != -1) {
												$("#password").after("<label for=\"password\" generated=\"true\" class=\"error\">"+response+"</label>");
											} else {
												var $errors = $signin.children("p.basic-errors"), errorsHeight;
												$errors.html(response);
												errorsHeight = $errors.height();
												$errors.addClass("pink-bg")
														.css({ height : 0 })
														.animate({ height : errorsHeight },{ duration: 350 });
											}
											$signin.children("div.submit-container").html(button);
										}
									}  
								});
							} else if (html.indexOf("username") != -1) {
								$("#username").after("<label for=\"username\" generated=\"true\" class=\"error\">"+html+"</label>");
								$signin.children("div.submit-container").html(button);
							} else if (html.indexOf("password") != -1) {
								$("#password").after("<label for=\"password\" generated=\"true\" class=\"error\">"+html+"</label>");
								$signin.children("div.submit-container").html(button);
							} else {
								var $errors = $signin.children("p.basic-errors"), errorsHeight;
								$errors.html(html);
								errorsHeight = $errors.height();
								$errors.addClass("pink-bg")
										.css({ height : 0 })
										.animate({ height : errorsHeight },{ duration: 350 });
								$signin.children("div.submit-container").html(button);
							}							
						}
					}  
				});
				return false;
			}
		});
		
		$reset.css({ height : 0 }).validate({
			rules: {
				email_reset: {
					required: true,
					email: true
				}
			},
			messages: {
				email_reset: "Please enter a valid email address"
			},
			submitHandler: function() { 
				var url			= AccountAjaxUrl,
					email		= $('#email_reset').attr('value'),
					button		= $reset.children("div.submit-container").html(),
					service		= $('#wlpeResetButton').attr('value'),
					data		= "email_reset="+ email +"&service="+ service;
				
				$reset.children("label.error").remove();
				$reset.children("div.submit-container").empty().append('<img src="/assets/images/layout/icon-loading-blk.gif" alt="" />');
				
				$.ajax({  
					type: "POST",  
					url: url,  
					data: data,  
					success: function(html){
						if (html == ""){
							$reset.empty().prepend(closeBtn).append(resetMsg).children("p").hide();
							$reset.children("p").fadeIn("slow");
							$("#wlpeResetForm a.toggle-reset").click(function (e) {
								e.preventDefault();
								toggleReset(false, "signin");
							});
							$("#account a.link-close").click(function (e) {
								e.preventDefault();
								toggleReset(false);
							});
						} else {
							$("#email_reset").after("<label for=\"email_reset\" generated=\"true\" class=\"error\">"+html+"</label>");
							$reset.children("div.submit-container").html(button);
						}
					}  
				});
				return false;
			}
		});
		
		// Click event for login and register toggle
		$resetToggle.click(function (e) {
			e.preventDefault();
			$link = $(this);
			
			if ( $link.attr("id") ==  "show-reset" ) {
				if ( $signin.is(':visible') ) {
					toggleSignin(false, "reset");
				}
			} else if ( $link.attr("id") ==  "show-login" ) {
				if ( $reset.is(':visible') ) {
					toggleReset(false, "signin");
				}
			}
		});
		
		// Click event for login and register toggle
		$("#options li a").click(function (e) {
			e.preventDefault();
			$link = $(this);
			
			if ( $newsletter.is(':visible') ) {
				toggleNewsletter(false);
			}
			
			if ( $link.attr("id") ==  "toggle-reg") {
				if ( $signin.is(':visible') ) {
					toggleSignin(false, "reg");
				} else if ( $reset.is(':visible') ) {
					toggleReset(false, "reg");
				} else {
					if ( $reg.is(':visible') ) {
						toggleReg(false);
					} else {
						toggleReg(true);
					}
				}
			} else {
				if ( $reg.is(':visible') ) {
					toggleReg(false, "signin");
				} else {
					if ( $signin.is(':visible') ) {
						toggleSignin(false);
					} else if ( $reset.is(':visible') ) {
						toggleReset(false);
					} else {
						toggleSignin(true);
					}
				}
			}
		});
	}
	
	// Hijax the original functionality of the signout form
	function hijaxSignout () {
		if ($("#wlpeUserForm").length > 0) {
			$('#wlpeUserForm').submit(function() {
				var url			= AccountAjaxUrl;   
				var service		= $('#wlpeLogoutButton').attr('value');   
				var data		= "&service="+ service;
				
				$("#account").empty().append('<img src="/assets/images/layout/icon-loading-white.gif" alt="" class="loading" />');
				
				$.ajax({  
					type: "POST",  
					url: url,  
					data: data,  
					success: function(html){
						$("#account").hide().html(html).fadeIn("slow");
						label2value();
						hijaxRegLogin();
					}
				});
				return false;
			});
		} else if ($("#managerUser").length > 0) {
			$("#mgrLogout").click(function (e) {
				e.preventDefault();
				$.get($(this).attr("href"), function(response){
					window.location.reload();
				});
			});
		}
	}
	
	// Hijax the original functionality of the signout form
	function hijaxActivate () {
		var $active = $('#wlpeActivateForm'),
			activeHeight = $active.height();
			
		$active.validate({
			rules: {
				activationpassword: "required",
				newpassword: {
					required: true,
					minlength: 6
				},
				newpassword_confirm: {
					required: true,
					minlength: 6,
					equalTo: "#newpassword"
				}
			},
			messages: {
				activationpassword: "Please enter the activation code from the email",
				newpassword: {
					required: "Please provide a password",
					minlength: "Your password must be at least 6 characters long"
				},
				newpassword_confirm: {
					required: "Please provide a password",
					minlength: "Your password must be at least 6 characters long",
					equalTo: "Please enter the same password as above"
				}
			},
			submitHandler: function() { 
				var url			= AccountAjaxUrl,
					button		= $active.children("div.submit-container").html(),
					succesMsg	= '<p>Your password has been reset. <br />Visit <a href="/">Home</a> to sign in.</p>';					
					
				var data = $active.serialize();
				
				$active.children("label.error").remove();
				$active.children("div.submit-container").empty().append('<img src="/assets/images/layout/icon-loading-blk.gif" alt="" />');
				
				$.ajax({  
					type: "POST",  
					url: url,  
					data: data,  
					success: function(html){
						if (html == ""){
							$active.css({ height : activeHeight }).children("div, p").remove();
							$active.append(succesMsg).children("p").hide();
							$active.children("p").fadeIn("slow");
						} else {
							if (html.indexOf("activation key") != -1) {
								$("#activationpassword").after("<label for=\"activationpassword\" generated=\"true\" class=\"error\">"+html+"</label>");
							} else {
								var $errors = $active.children("p.basic-errors"), errorsHeight;
								$errors.html(html);
								errorsHeight = $errors.height();
								$errors.addClass("pink-bg")
										.css({ height : 0 })
										.animate({ height : errorsHeight },{ duration: 350 });
							}
							$active.children("div.submit-container").html(button);
						}
					}  
				});
				return false;
			}
		});
	}
});