#import "LoginViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "AnswersManager.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "UIConstants.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#ifdef POD_OF_Firebase
#import <Firebase/Firebase.h>
#endif
#if defined POD_OF_FBSDKCoreKit && defined POD_OF_FBSDKLoginKit
 #import <FBSDKCoreKit/FBSDKCoreKit.h>
 #import <FBSDKLoginKit/FBSDKLoginKit.h>
#endif
#ifdef POD_OF_GoogleSignIn
 #import <GoogleSignIn/GoogleSignIn.h>
#endif
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <IQKeyboardManager/IQUIView+IQKeyboardToolbar.h>
#import <PureLayout/PureLayout.h>
#import <libextobjc/EXTScope.h>
#import "Utility.h"
#import "PerlWS.h"
#import "UserApi.h"
#import "LoginResponseJsonMapper.h"
#import "FacebookLoginResponseJsonMapper.h"
#import "GoogleLoginResponseJsonMapper.h"
#import "CustomTextFieldView.h"
#import "AccountBenefitsViewController.h"
#import "BookingReviewViewController.h"
#import "JoinViewController.h"
#import "ResetPassWordViewController.h"
#import "Vars.h"
#import "UserNotificationsManager.h"

@interface LoginViewController ()
#ifdef POD_OF_GoogleSignIn
<GIDSignInDelegate,GIDSignInUIDelegate>
#endif

@property (nonatomic, weak) IBOutlet CustomTextFieldView *userView;
@property (nonatomic, weak) IBOutlet CustomTextFieldView *pwdView;
@property (nonatomic, weak) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIStackView *buttonStackView;
@property (weak, nonatomic) IBOutlet UIView *thirdLoginView;
@property (weak, nonatomic) IBOutlet UIImageView *logoImageView;
@property (weak, nonatomic) IBOutlet UIButton *forgetPasswordButton;
@property (weak, nonatomic) IBOutlet UIButton *facebookButton;
@property (weak, nonatomic) IBOutlet UIButton *googleButton;
@property (weak, nonatomic) IBOutlet UIButton *moreButton;
@property (weak, nonatomic) IBOutlet UIButton *createButton;
@property (nonatomic, strong) id segueObject;
@property (nonatomic, assign) BOOL popAnimated;
@property (nonatomic, assign) BOOL isPopGoogleLogin;
@property (nonatomic, copy) void (^destructiveBlock) (void);
@property (nonatomic, strong, readonly) JVFloatLabeledTextField *usernameField;
@property (nonatomic, strong, readonly) JVFloatLabeledTextField *passwordField;
@property (nonatomic, assign, readonly) BOOL allowsThirdPartyLogin;

- (IBAction)clickLogin:(id)sender;
- (IBAction)join:(id)sender;
- (IBAction)forgetPassword:(id)sender;

@end

@implementation LoginViewController

- (instancetype)init {
	if (self = [super init]) {
		self.title = IMLocalizedString(@"Log in");
		self.hidesBottomBarWhenPushed = YES;
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];

	self.usernameField.placeholder = IMLocalizedString(@"Email or ID");
	self.usernameField.floatingLabel.text = IMLocalizedString(@"Email or ID");
	self.usernameField.autocapitalizationType = UITextAutocapitalizationTypeNone;
	self.usernameField.autocorrectionType = UITextAutocorrectionTypeNo;
	[self.usernameField.keyboardToolbar.doneBarButton setTarget:self action:@selector(resignLogin:)];

	self.passwordField.placeholder = IMLocalizedString(@"Password");
	self.passwordField.floatingLabel.text = IMLocalizedString(@"Password");
	self.passwordField.im_textContentType = IMTextContentTypePassword;
	self.passwordField.autocapitalizationType = UITextAutocapitalizationTypeNone;
	self.passwordField.autocorrectionType = UITextAutocorrectionTypeNo;
	self.passwordField.secureTextEntry = YES;
	self.passwordField.clearsOnBeginEditing = YES;
	[self.passwordField.keyboardToolbar.doneBarButton setTarget:self action:@selector(resignLogin:)];

    [self.forgetPasswordButton setTitle:IMLocalizedString(@"Forgot Password?") forState:UIControlStateNormal];

	self.loginButton.backgroundColor = [Vars defaultTintColor];
	self.createButton.backgroundColor = [Vars defaultTintColor];
	[Utility addRoundedBorderToView:self.moreButton];
	[self.moreButton setBackgroundColor:[UIColor clearColor]];
	[self.moreButton setTitleColor:[Vars defaultTintColor] forState:UIControlStateNormal];
	[Utility addRoundedBorderToButton:self.loginButton];
	[Utility addRoundedBorderToButton:self.createButton];
	[self.loginButton setTitle:IMLocalizedString(@"Log in") forState:UIControlStateNormal];
	[self.createButton setTitle:IMLocalizedString(@"Create Account") forState:UIControlStateNormal];
	[self.moreButton setTitle:IMLocalizedString(@"Checkout as Guest") forState:UIControlStateNormal];
	
	if (self.allowsThirdPartyLogin) {
		self.thirdLoginView.hidden = NO;
		self.logoImageView.hidden = YES;
#ifdef POD_OF_GoogleSignIn
		[GIDSignIn sharedInstance].delegate = self;
		[GIDSignIn sharedInstance].uiDelegate = self;
#endif
		[DrawUtils addRoundedBorderToRect:self.facebookButton cornerRadius:kDefaultRoundedCornerRadius strokeColor:[UIColor lightGrayColor]];
		[DrawUtils addRoundedBorderToRect:self.googleButton cornerRadius:kDefaultRoundedCornerRadius strokeColor:[UIColor lightGrayColor]];
	} else {
		self.logoImageView.hidden = NO;
		self.thirdLoginView.hidden = YES;
	}
    if ([Vars is_tours_site] && [Vars is_cn_website]) {
        self.forgetPasswordButton.hidden = YES;
		self.logoImageView.image = IMLocalizedImage(@"Logo-Style1");
    }
	
	self.moreButton.hidden = !self.pushFromBook;
	
	if (self.firstLaunchV) {
		self.navigationItem.hidesBackButton = YES;
		self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:IMLocalizedString(@"Skip") style:UIBarButtonItemStylePlain target:self action:@selector(skip)];
	}
}

- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];

	[CocoaUtils proxyTopMostViewController:nil];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];

	if (self.isPopGoogleLogin) {
		[CocoaUtils showBusyIndicator:self.view];
		self.isPopGoogleLogin = NO;
	}
}

#pragma mark - Public
- (void)skip{
	[self dismissViewControllerAnimated:NO completion:nil];
	[[Vars appDelegate] dashboard];

}

- (void)performSegueWithObject:(id)object popAnimated:(BOOL)animated {
	self.segueObject = object;
	self.popAnimated = animated;
}

#pragma mark - Property

- (JVFloatLabeledTextField *)usernameField {
	return self.userView.textField;
}

- (JVFloatLabeledTextField *)passwordField {
	return self.pwdView.textField;
}

- (BOOL)allowsThirdPartyLogin {
	return ![Vars clientDomainId] && ![Vars is_cn_website];
}

#pragma mark - Action

- (IBAction)clickLogin:(id)sender {
	if (![self validateLogin:NO]) {
		return;
	}
	[self login];
}

- (IBAction)forgetPassword:(id)sender {
    ResetPassWordViewController *resetPasswordViewController = [[ResetPassWordViewController alloc] init];
    [self.navigationController pushViewController:resetPasswordViewController animated:YES];
}

- (IBAction)join:(id)sender {
	JoinViewController *viewController = [[JoinViewController alloc] init];
	[viewController performSegueWithObject:self.segueObject popAnimated:self.popAnimated];
	[viewController setDestructiveBlock:self.destructiveBlock];
	viewController.firstLaunchV = self.firstLaunchV;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)resignLogin:(UITextField *)textField {
	if ([textField isFirstResponder]) {
		[textField resignFirstResponder];
	}
	if ([self validateLogin:YES]) {
		[self login];
	}
}

- (IBAction)googleLogin:(id)sender {
#ifdef POD_OF_GoogleSignIn
	[self googleSignOut];
	[self googleSignIn];
#endif
	self.isPopGoogleLogin = YES;
}

- (IBAction)faceBookLogin:(id)sender {
#if defined POD_OF_FBSDKCoreKit && defined POD_OF_FBSDKLoginKit
	[self facebookLogout];
	[self facebookLogin];
#endif
}

- (IBAction)moreButton:(id)sender {
	AccountBenefitsViewController *viewController = [[AccountBenefitsViewController alloc]init];
	[viewController setBackBookingReviewBlock:self.destructiveBlock];
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Network

- (void)login {
	Login *login = [[Login alloc] init];
	login.username = self.usernameField.text;
	login.password = self.passwordField.text;
	login.device_identifier = [Utility deviceIdentifier];

	NSDictionary *requestDict = [Utility perlParamXml:[login innerXML] action:login.name];
	// NSLog(@"%@", requestDict);
	[Utility getXMLFromRequestWithMethod:@"GET" url:login.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		LoginResponseJsonMapper *mapper = [[LoginResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		NSError *parseError = [mapper parseWithJSONObject:jsonDict];
		if (!parseError) {
			LoginResponse *response = mapper.response;
			if (![StringUtils isEmpty:response.error]) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error];
			} else if ([StringUtils isEmpty:response.user.cookie_string]) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:[Vars responseException]];
			} else {
				User *user = response.user;
				user.uid = login.username;
				user.pass1 = login.password;
				[Vars appDelegate].loginUser = user;
				
				NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
				[userDefaults setInteger:[Vars appDelegate].loginUser.id forKey:UserDefaultsKeyUserID];
				[userDefaults setObject:[Vars appDelegate].loginUser.uid forKey:UserDefaultsKeyUserName];
				[userDefaults setObject:[Vars appDelegate].loginUser.pass1 forKey:UserDefaultsKeyUserPassword];

				NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
				[notificationCenter postNotificationName:SegueDidPerformNotification object:self.segueObject];
				[notificationCenter postNotificationName:LoginStatusDidChangeNotification object:nil];

				[AnswersManager logLoginWithMethod:@"Password" success:YES];
				[self pageSwitching];
			}
		}
	}];
}

#if defined POD_OF_FBSDKCoreKit && defined POD_OF_FBSDKLoginKit

- (void)loginWithFacebook:(FacebookLogin *)facebookLogin {
	NSDictionary *requestDict = [Utility perlParamXml:[facebookLogin innerXML] action:facebookLogin.name];
	// NSLog(@"%@", requestDict);
	[Utility getXMLFromRequestWithMethod:@"GET" url:facebookLogin.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		FacebookLoginResponseJsonMapper *mapper = [[FacebookLoginResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			FacebookLoginResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
				[self facebookLogout];
			} else if (response.shouldLink) {
				[self linkOrNewAccountWithFacebook:facebookLogin];
			} else if (response.emailExisted) {
				[self linkEmailAccountWithFacebook:facebookLogin];
			} else if ([StringUtils isEmpty:response.user.cookie_string]) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:[Vars responseException]];
				[self facebookLogout];
			} else {
				[Vars appDelegate].loginUser = response.user;
				NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
				[userDefaults setInteger:[Vars appDelegate].loginUser.id forKey:UserDefaultsKeyUserID];

				NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
				[notificationCenter postNotificationName:SegueDidPerformNotification object:self.segueObject];
				[notificationCenter postNotificationName:LoginStatusDidChangeNotification object:nil];

				[AnswersManager logLoginWithMethod:@"Facebook" success:YES];
				[self pageSwitching];
			}
		}
	}];
}

#endif

#if defined POD_OF_FBSDKCoreKit && defined POD_OF_FBSDKLoginKit

#pragma mark - facebook-ios-sdk

- (void)alertFacebookError:(NSError *)error {
	NSString *alertMessage = error.userInfo[FBSDKErrorLocalizedDescriptionKey] ?: @"There was a problem logging in. Please try again later.";
	NSString *alertTitle = error.userInfo[FBSDKErrorLocalizedTitleKey] ?: @"Oops";
	[CocoaUtils showAlertWithTitle:alertTitle message:alertMessage];
}

- (void)facebookLogin {
	[CocoaUtils proxyTopMostViewController:self];
	[CocoaUtils showBusyIndicator:self.view];
	FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
	loginManager.loginBehavior = FBSDKLoginBehaviorSystemAccount;
	[loginManager logInWithReadPermissions: @[@"public_profile", @"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
		[CocoaUtils hideBusyIndicator:self.view];
		if (error) {
			[self alertFacebookError:error];
		} else if (result.isCancelled) {
		} else if ([FBSDKAccessToken currentAccessToken]) {
			[CocoaUtils showBusyIndicator:self.view];
			FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{ @"fields" : @"id,email,first_name,last_name,gender,birthday" }];
			[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
				[CocoaUtils hideBusyIndicator:self.view];
				if (error) {
					// NSLog(@"Picker loading error:%@", error);
					[self alertFacebookError:error];
					[self facebookLogout];
				} else if (!result[@"email"]) {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please fill out your email address on Facebook"];
					[self facebookLogout];
				} else {
					// NSLog(@"%@", result);
					NSMutableDictionary *mutableResult = [NSMutableDictionary dictionaryWithDictionary:result];
					if (![Utility canBeConvertedToUrlEncodedFromString:mutableResult[@"first_name"]]) {
						mutableResult[@"first_name"] = [CocoaUtils normalizeUserGeneratedContentString:mutableResult[@"first_name"]];
					}
					if (![Utility canBeConvertedToUrlEncodedFromString:mutableResult[@"last_name"]]) {
						mutableResult[@"last_name"] = [CocoaUtils normalizeUserGeneratedContentString:mutableResult[@"last_name"]];
					}
					FacebookLogin *facebookLogin = [[FacebookLogin alloc] init];
					facebookLogin.tokenString = [FBSDKAccessToken currentAccessToken].tokenString;
					facebookLogin.userDetails = [NSDictionary dictionaryWithDictionary:mutableResult];
					facebookLogin.deviceIdentifier = [Utility deviceIdentifier];
					[self loginWithFacebook:facebookLogin];
				}
			}];
		} else {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:[Vars responseException]];
		}
	}];
}

- (void)facebookLogout {
	FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
	[loginManager logOut];
}

- (void)linkEmailAccountWithFacebook:(FacebookLogin *)facebookLogin {
	[CocoaUtils showInputBoxWithStyle:UIAlertViewStyleSecureTextInput title:IMLocalizedString(@"Information") message:[NSString stringWithFormat:@"There is already a %@ account for %@. Enter your %@ password to link Facebook with this account.", [Vars site_name], facebookLogin.userDetails[@"email"], [Vars site_name]] configurationHandler:^(NSInteger inputIndex, UITextField *textField) {
		if (inputIndex == 0) {
			textField.placeholder = IMLocalizedString(@"Password");
			textField.clearsOnBeginEditing = YES;
		}
	} cancelActionTitle:IMLocalizedString(@"Cancel") otherActionTitles:@[@"Link Account"] actionHandler:^(NSInteger buttonIndex, NSArray *textFields) {
		UITextField *textField = textFields[0];
		if (buttonIndex == 0) {
			if (textField.isFirstResponder) {
				[textField becomeFirstResponder];
			}
			if ([self validateForTextFields:@[textField] slient:YES]) {
				facebookLogin.shouldLink = YES;
				facebookLogin.username = facebookLogin.userDetails[@"email"];
				facebookLogin.password = textField.text;
				[self loginWithFacebook:facebookLogin];
			} else {
				[self linkEmailAccountWithFacebook:facebookLogin];
			}
		} else {
			[self facebookLogout];
		}
	}];
}

- (void)linkOrNewAccountWithFacebook:(FacebookLogin *)facebookLogin {
	NSString *linkAccountString = [NSString stringWithFormat:@"Link to my existing %@ account", [Vars site_name]];
	NSString *newAccountString = @"Continue with my Facebook account";
	[CocoaUtils showMessageBoxWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:@"If you already have a %@ account. We recommend that you link to it now so that all your trips are in one place.", [Vars site_name]] cancelActionTitle:@"Cancel" otherActionTitles:@[linkAccountString, newAccountString] actionHandler:^(NSInteger buttonIndex) {
		if (buttonIndex == 0) {
			[self linkMyAccountWithFacebook:facebookLogin];
		} else if (buttonIndex == 1) {
			facebookLogin.shouldLink = YES;
			[self loginWithFacebook:facebookLogin];
		} else {
			[self facebookLogout];
		}
	}];
}

- (void)linkMyAccountWithFacebook:(FacebookLogin *)facebookLogin {
	[CocoaUtils showInputBoxWithStyle:UIAlertViewStyleLoginAndPasswordInput title:IMLocalizedString(@"Log in") message:[NSString stringWithFormat:@"Have a %@ account?", [Vars site_name]] configurationHandler:^(NSInteger inputIndex, UITextField *textField) {
		if (inputIndex == 0) {
			textField.placeholder = IMLocalizedString(@"Email or ID");
			textField.clearButtonMode = UITextFieldViewModeWhileEditing;
		} else if (inputIndex == 1) {
			textField.placeholder = IMLocalizedString(@"Password");
			textField.clearsOnBeginEditing = YES;
		}
	} cancelActionTitle:IMLocalizedString(@"Cancel") otherActionTitles:@[IMLocalizedString(@"Link Account")] actionHandler:^(NSInteger buttonIndex, NSArray *textFields) {
		UITextField *loginInput = textFields[0];
		UITextField *passwordInput = textFields[1];
		if (buttonIndex == 0) {
			if (loginInput.isFirstResponder) {
				[loginInput becomeFirstResponder];
			}
			if (passwordInput.isFirstResponder) {
				[passwordInput becomeFirstResponder];
			}
			if ([self validateForTextFields:@[loginInput, passwordInput] slient:YES]) {
				facebookLogin.shouldLink = YES;
				facebookLogin.username = loginInput.text;
				facebookLogin.password = passwordInput.text;
				[self loginWithFacebook:facebookLogin];
			} else {
				[self linkOrNewAccountWithFacebook:facebookLogin];
			}
		} else {
			[self facebookLogout];
		}
	}];
}

#endif

#ifdef POD_OF_GoogleSignIn

#pragma mark - google-ios-sdk

- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error {
	if (user) {
		if ([StringUtils isEmpty:user.profile.email]) {
			[CocoaUtils hideBusyIndicator:self.view];
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please fill out your email address on Google"];
			[self googleSignOut];
			return;
		}
		GIDAuthentication *authentication = user.authentication;
		FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken accessToken:authentication.accessToken];
		[[FIRAuth auth] signInAndRetrieveDataWithCredential:credential completion:nil];
		if (YES){
			GoogleLogin *googleLogin = [[GoogleLogin alloc] init];
			googleLogin.idToken = authentication.idToken;
			googleLogin.deviceIdentifier = [Utility deviceIdentifier];
			
			NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:googleLogin];

			[Utility performRESTRequestWithMethod:@"POST" url:googleLogin.address parameters:requestDict success:^(id jsonObject) {
				GoogleLoginResponseJsonMapper *mapper = [[GoogleLoginResponseJsonMapper alloc]init];
				if (![mapper parseWithJSONObject:jsonObject]) {
					GoogleLoginResponse *response = mapper.response;
					if (response.errorCode > 0) {
						[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.errorMessage];
						[self googleSignOut];
					} else if ([StringUtils isEmpty:response.user.cookie_string]) {
						[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:[Vars responseException]];
						[self googleSignOut];
					} else {
						[Vars appDelegate].loginUser = response.user;
						
						NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
						[userDefaults setInteger:[Vars appDelegate].loginUser.id forKey:UserDefaultsKeyUserID];
						[userDefaults setObject:[Vars appDelegate].loginUser.uid forKey:UserDefaultsKeyUserName];
						
						NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
						[notificationCenter postNotificationName:SegueDidPerformNotification object:self.segueObject];
						[notificationCenter postNotificationName:LoginStatusDidChangeNotification object:nil];
						
						[AnswersManager logLoginWithMethod:@"Google" success:YES];
						[self pageSwitching];
					}
				}
			}];
		}
	} else if (error) {
		self.isPopGoogleLogin = NO;
		//[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:error.localizedDescription];
	}
}


- (void)signIn:(GIDSignIn *)signIn didDisconnectWithUser:(GIDGoogleUser *)user withError:(NSError *)error {
	// Perform any operations when the user disconnects from app here.
	if (error) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:error.localizedDescription];
	}
}

- (void)googleSignIn {
	[[GIDSignIn sharedInstance] signIn];
}

- (void)googleSignOut {
	[[GIDSignIn sharedInstance] signOut];
}

#endif

#pragma mark - Private

-(void)pageSwitching{
	if (!self.firstLaunchV) {
		[self.navigationController popViewControllerAnimated:self.popAnimated];
		if (self.destructiveBlock) {
			self.destructiveBlock();
		}
	}
	
	[[Vars appDelegate] dashboard];
}

- (BOOL)validateLogin:(BOOL)slient {
	return [self validateForTextFields:@[self.usernameField, self.passwordField] slient:slient];
}

- (BOOL)validateForTextFields:(NSArray *)textFields slient:(BOOL)slient {
	for (UITextField *textField in textFields) {
		if ([StringUtils isBlank:textField.text]) {
			if (!slient) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:IMLocalizedString(@"Please fill out %@"), textField.placeholder.lowercaseString] dismissalHandler:^{
					[textField becomeFirstResponder];
				}];
			}
			return NO;
		}
	}
	for (UITextField *textField in textFields) {
		if (![Utility canBeConvertedToUrlEncodedFromString:textField.text]) {
			if (!slient) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please enter alphabetic characters only") dismissalHandler:^{
					[textField becomeFirstResponder];
				}];
			}
			return NO;
		}
	}
	return YES;
}

@end
