//######
//## Jumpsite.net
//## Login Scripts
//######
;(function($){
	signin = function(){
		var regemail    	= $("#regemail");
		var regpassword 	= $("#regpwd");
		var bValid          = true;
			
		bValid = bValid && checkLength(regemail, "email", 6, 80);
		bValid = bValid && checkLength(regpassword, "password", 5, 16);
			
		bValid = bValid && checkRegexp(regemail, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Email field only allow: username@email.com");
		if (bValid) {
			$.ajax({
				type: "POST",
				url: baseurl+"index/login",
				data: $("#signin").serialize(),
				dataType: "json",
				beforeSend: function(){displayProcess("Authenticating...")},
				success: function(msg){
					if(msg.attemp>=10){
						removeProcessDisplay();
						window.location.href = window.location.href;
					}else{
						if (msg.success == true) {
							removeProcessDisplay();
							if(msg.p_reset)
								window.location.href = baseurl+"Index/Passwordreset";
							else
								(parseInt(msg.acct_id)>0)?window.location.href = baseurl+"Account":window.location.href = "http://"+msg.reason+"."+this_site;
							
						}else
							displayError("Error","<div class='faceboxError'>"+msg.reason+"</div>");
						
					}
					
				},
				error: function(){removeProcessDisplay();}
			});		
		}   
	}
	
	fbLogin = function(){
		displayProcess("Talking with facebook...")
		FB.init({ apiKey: token_key });
		FB.getLoginStatus(function(D){
			if (D.authResponse){
				FB.api('/me', function(D) {
					$.ajax({
						type: "POST",
						url: baseurl+"Index/Fblogin",
						data: 'id='+D.id,
						dataType: "json",
						beforeSend: function(){removeProcessDisplay();displayProcess("Fetching information...")},
						success: function(msg){
							if (msg.success == true) {
								removeProcessDisplay();
								if(msg.p_reset)
									window.location.href = baseurl+"Index/Passwordreset";
								else
									(parseInt(msg.acct_id)>0)?window.location.href = baseurl+"Account":window.location.href = "http://"+msg.reason+"."+this_site;
							}else
								processFBLogin(D);
							
						},
						error: function(t,x,p){
							removeProcessDisplay();
							ajaxErrorDisplay(t,x,p);
						}
					});	
				});
			}else{
				FB.login(function(D){
					if (D.authResponse){
						removeProcessDisplay();
						displayProcess("Fetching information...")
						FB.api('/me', function(D) {
							$.ajax({
								type: "POST",
								url: baseurl+"Index/Fblogin",
								data: 'id='+D.id,
								dataType: "json",
								beforeSend: function(){removeProcessDisplay();displayProcess("Fetching information...")},
								success: function(msg){
									if (msg.success == true) {
										removeProcessDisplay();
										if(msg.p_reset)
											window.location.href = baseurl+"Index/Passwordreset";
										else
											(parseInt(msg.acct_id)>0)?window.location.href = baseurl+"Account":window.location.href = "http://"+msg.reason+"."+this_site;
									}else
										processFBLogin(D);
								},
								error: function(t,x,p){
									removeProcessDisplay();
									ajaxErrorDisplay(t,x,p);
								}
							});
						});
					}else{
						removeProcessDisplay();
						displayError("Error","<div class='faceboxError'>User cancelled login or did not fully authorize.</div>");
					}
				},{scope: 'email,read_stream'});
			}
		});
	}
	
	processFBLogin = function(D){
		removeProcessDisplay();
		box = "<p class='jumpsite_log_type' id='advisor' style='color:#0F62AF;font-weight:bold;margin-left:10px;cursor:pointer;'><span style='color:#000000;position:relative;top:-1px'>&raquo</span> Advisor</p><div class='agent-login-details'></div>\
			   <p class='jumpsite_log_type' id='client' style='color:#0F62AF;font-weight:bold;margin-left:10px;cursor:pointer;'><span style='color:#000000;position:relative;top:-1px'>&raquo</span> Client</p><div class='client-login-details'></div>";
		$.prompt(box,{
			title: "Please choose login type",
			promptspeed: "fast",
			loaded: function(){
				$(document).find("p.jumpsite_log_type").bind('click',function(){
					switch($(this).attr('id')){
						case 'advisor':
							$(this).next().html("<form style='margin:0 0 10px 30px'>\
												<p style='font-weight:bold'>Jumpsite Username/Email:</p> \
												<p><input type='text' id='agent_email' name='u[name]' style='width:300px;font-size:10px;padding:2px;font-weight:bold;color:#565656'/></p>\
												</form>").show();
							$(document).find(".client-login-details").html("").hide();
							break;
						case 'client':
							$(this).next().html("<div style='margin:0 0 10px 30px'>\
												<p style='font-weight:bold'><input type='checkbox' class='new-client-checkbx' style='position:relative;top:2px;'/> New User</p> \
												<div class='new-client' style='display:none'><form>\
													<p style='font-weight:bold'>Choose an Agent:</p> \
													<p><select style='margin-bottom:5px;font-size:10px;padding:2px;font-weight:bold;color:#565656' id='agentlist' name='u[agent]'></select></p>\
													<p style='font-weight:bold'>Email:</p> \
													<p><input type='text' value='"+D.email+"' style='width:300px;margin-bottom:5px;font-size:10px;padding:2px;font-weight:bold;color:#565656' name='u[email]'/></p>\
													<p style='font-weight:bold'>Firstname:</p> \
													<p><input type='text' value='"+D.first_name+"' style='width:300px;margin-bottom:5px;font-size:10px;padding:2px;font-weight:bold;color:#565656' name='u[fname]'/></p>\
													<p style='font-weight:bold'>Lastname:</p> \
													<p><input type='text' value='"+D.last_name+"' style='width:300px;margin-bottom:5px;font-size:10px;padding:2px;font-weight:bold;color:#565656' name='u[lname]'/></p>\
													<p style='font-weight:bold'>Birthdate:</p> \
													<p><input type='text' value='' style='width:200px;margin-bottom:5px;font-size:10px;padding:2px;font-weight:bold;color:#565656' name='u[bdate]'/> <i>(dd/mm/yyyy)</i></p>\
													<p style='font-weight:bold'>NRIC:</p> \
													<p><input type='text' value='' style='width:200px;margin-bottom:5px;font-size:10px;padding:2px;font-weight:bold;color:#565656' name='u[nric]'/></p>\
													<input type='hidden' value='"+D.id+"' style='width:300px;margin-bottom:5px;font-size:10px;padding:2px;font-weight:bold;color:#565656' name='u[fbid]'/>\
												</form></div>\
												<div class='old-client'><form>\
													<p style='font-weight:bold'>Jumpsite Username/Email:</p> \
													<p><input type='text'  name='u[name]' style='width:300px;margin-bottom:5px;font-size:10px;padding:2px;font-weight:bold;color:#565656'/></p>\
												</form></div>\
												</div>").show();
							$(document).find("input.new-client-checkbx").bind('click',function(){
								if($(this).is(':checked')){
									$(document).find("div.new-client").show();
									$(document).find("div.old-client").hide(); 
									$.ajax({
										type: "POST",
										url: baseurl+"Index/Agentlist",
										dataType: "json",
										success: function(C){
											$(document).find("select#agentlist").html(C.data);
										},
										error: function(){removeProcessDisplay();}
									});		
								}else{
									$(document).find("div.new-client").hide();
									$(document).find("div.old-client").show();
								}
							});
							$(document).find(".agent-login-details").html("").hide();
							break;
					}
				});
			},
			buttons:{Login:true,Cancel:false},
			submit: function(v,m,f){
				if(v){
					removeProcessDisplay();
					if($(document).find(".agent-login-details").is(':visible')){
						$.ajax({
							type: "POST",
							url: baseurl+"Index/Fbid",
							data: $(document).find(".agent-login-details").find("form").serialize()+"&fbid="+D.id,
							dataType: "json",
							beforeSend: function(){displayProcess("Authenticating...")},
							success: function(msg){
								if (msg.success == true) {
									removeProcessDisplay();
									$.ajax({
										type: "POST",
										url: baseurl+"Index/Fblogin",
										data: 'id='+msg.id,
										dataType: "json",
										beforeSend: function(){removeProcessDisplay();displayProcess("Fetching information...")},
										success: function(msg){
											if (msg.success == true) {
												removeProcessDisplay();
												if(msg.p_reset)
													window.location.href = baseurl+"Index/Passwordreset";
												else
													(parseInt(msg.acct_id)>0)?window.location.href = baseurl+"Account":window.location.href = "http://"+msg.reason+"."+this_site;
												
											}else
												displayError("Error","<div class='faceboxError'>"+msg.reason+"</div>");
										},
										error: function(t,x,p){
											removeProcessDisplay();
											ajaxErrorDisplay(t,x,p);
										}
									});
								}else{
									removeProcessDisplay();
									displayError("Error","<div class='faceboxError'>"+msg.reason+"</div>");
								}
									
							},
							error: function(){removeProcessDisplay();}
						});
					}else if($(document).find(".client-login-details").is(':visible')){
						if($(document).find(".new-client").is(':visible'))
							$.ajax({
								type: "POST",
								url: baseurl+"Index/Addclient",
								data: $(document).find(".new-client").find("form").serialize(),
								dataType: "json",
								success: function(C){
									if(C.e){
										$.ajax({
											type: "POST",
											url: baseurl+"Index/Fblogin",
											data: 'id='+C.d,
											dataType: "json",
											beforeSend: function(){removeProcessDisplay();displayProcess("Fetching information...")},
											success: function(msg){
												if (msg.success == true) {
													removeProcessDisplay();
													if(msg.p_reset)
														window.location.href = baseurl+"Index/Passwordreset";
													else
														(parseInt(msg.acct_id)>0)?window.location.href = baseurl+"Account":window.location.href = "http://"+msg.reason+"."+this_site;
													
												}else
													displayError("Error","<div class='faceboxError'>"+msg.reason+"</div>");
											},
											error: function(t,x,p){
												removeProcessDisplay();
												ajaxErrorDisplay(t,x,p);
											}
										});
									}
								},
								error: function(){removeProcessDisplay();}
							});		
						else{
							$.ajax({
								type: "POST",
								url: baseurl+"Index/Fbid",
								data: $(document).find(".old-client").find("form").serialize()+"&fbid="+D.id,
								dataType: "json",
								beforeSend: function(){displayProcess("Authenticating...")},
								success: function(msg){
									if (msg.success == true) {
										removeProcessDisplay();
										$.ajax({
											type: "POST",
											url: baseurl+"Index/Fblogin",
											data: 'id='+msg.id,
											dataType: "json",
											beforeSend: function(){removeProcessDisplay();displayProcess("Fetching information...")},
											success: function(msg){
												if (msg.success == true) {
													removeProcessDisplay();
													if(msg.p_reset)
														window.location.href = baseurl+"Index/Passwordreset";
													else
														(parseInt(msg.acct_id)>0)?window.location.href = baseurl+"Account":window.location.href = "http://"+msg.reason+"."+this_site;
													
												}else
													displayError("Error","<div class='faceboxError'>"+msg.reason+"</div>");
											},
											error: function(t,x,p){
												removeProcessDisplay();
												ajaxErrorDisplay(t,x,p);
											}
										});
									}else{
										removeProcessDisplay();
										displayError("Error","<div class='faceboxError'>"+msg.reason+"</div>");
									}
										
								},
								error: function(){removeProcessDisplay();}
							});
						}
					}
					return false;
				}
				return true;
			}
		});
	}	
	
	p_reset = function(){
		var D 	= $('#for_password_reset');
		var isEmpty = false;
		var isValid = true;
		D.find('input[type=password]').each(function(){
			if($.trim($(this).val())==''){
				$(this).css('border-color','red')
				isEmpty = true;
			}
		});
		if(isEmpty)
			updateTips('Please fill-up all fields.');
		else{
			isValid = isValid && checkLength(D.find('input#old_password'), "password", 5, 16);
			isValid = isValid && checkLength(D.find('input#new_password'), "password", 5, 16);
			isValid = isValid && checkLength(D.find('input#confirm_password'), "password", 5, 16);
			if(isValid){
				op = $.trim(D.find('input#old_password').val());
				np = $.trim(D.find('input#new_password').val());
				cp = $.trim(D.find('input#confirm_password').val());
				if(np==cp){
					if(op!=np){
						$.ajax({
							type: "POST",
							url: baseurl+"Index/Passwordreset",
							data: $("form#reset").serialize(),
							dataType: "json",
							beforeSend: function(){displayProcess("Processing...")},
							success: function(msg){
								if(msg.success) {
									removeProcessDisplay();
									window.location.href = baseurl+"Account";
								}else
									displayError("Error","<div class='faceboxError'>"+msg.mssg+"</div>");
							},
							error: function(){removeProcessDisplay();}
						});
					}else
						updateTips('Your new and old password should not be the same.');
				}else
					updateTips('New password does not match.');
			}
		}
	}
	
	forgot_pw = function(){
		$("#forgot_password").slideToggle("slow");
		$("#for_login").slideToggle("slow");
	}
	
	back_login = function(){
		$("#forgot_password").slideToggle("slow");
		$("#for_login").slideToggle("slow");
	}
	
	request_pw = function(){
		var getemail = $("#email");
		var str=getemail.val();
		var filter=/^.+@.+\..{2,3}$/;
		$.ajax({
			type: "POST",
			url: baseurl+"index/forget",
			data: "getEmail="+getemail.val(),
			success: function(msg){
				var returnsuccess =  msg.substr(11,4);
				if (returnsuccess == 'true') {
					displayInfo("Successful","<div class='confirm'>"+msg.substr(23,42)+"</div>");
					back_login();
				}else if (!filter.test(str) || getemail.val() == ''){
					displayError("Error","<div class='faceboxError'>"+msg.substr(23,19)+"</div>");
				}else{
					displayError("Error","<div class='faceboxError'>"+msg.substr(23,21)+"</div>");
				}
			}
		});
		return false;
	}
	
	logout = function(){	
		$.ajax({
			type: "POST",
			url: baseurl + "/index/logout",
			success: function(msg) {
				window.location.href = baseurl;
			}
		});			   
	}
	
	updateTips = function(t){
		displayError("Oops","<div class='faceboxError'>"+t+"</div>");
		
	}
	
	checkLength = function(o, n, min, max) {
		if (o.val().length > max || o.val().length < min) {
			o.addClass('ui-state-error');
			updateTips("The " + n + " field must be between " + min + " and " + max + ".");
			return false;
		} else {
			return true;
		}
	}
	
	checkRegexp = function(o, regexp, n) {
		if (! (regexp.test(o.val()))) {
			o.addClass('ui-state-error');
			updateTips(n);
			return false;
		} else {
			return true;
		}
	}
	
})(jQuery);






