

//
//  StartPage.m
//  C172 Pad
//
//  Created by Claus Richter on 10/27/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "StartPage.h"
#import "ViewController.h"
#import "checkCustomerData.h"

#import <SystemConfiguration/SCNetworkReachability.h>
#include <netinet/in.h>
#import "Reachability.h"
#import "importPerformanceData.h"

#import "NSURLSession+SynchronousTask.h"
#define NSLog(...)

@interface StartPage () {
    checkCustomerData *checkCustomerDataClass_;
    

    importPerformanceData* importPerformanceDataClass_;    
       __weak IBOutlet UIView *importPerformanceDataClassView_;
}
@end

@implementation StartPage

NSString *logInVersion = @"1";



-(void)viewDidAppear:(BOOL)animated{
    [self setUpViewForInterfaceOrientation:self.interfaceOrientation];
    //[[UIApplication sharedApplication] statusBarOrientation];
    
    _labelLoadingData.hidden = YES;
    _logInButton.hidden = NO;
    
}

- (void) setUpViewForInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation{
    if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
        [self sortForLandscape];   }
    else { [self sortForPortrait];  }
}

- (void)willAnimateRotationToInterfaceOrientation:
(UIInterfaceOrientation)toInterfaceOrientation
                                         duration:(NSTimeInterval)duration{
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
        toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        [self sortForLandscape];
    }else{ [self sortForPortrait]; }
}


-(void) sortForLandscape {
    UIImage *background = [UIImage imageNamed:@"start back blue.png"];
    [_backgroundSkyImage setImage:background];
}

-(void) sortForPortrait {
    UIImage *background = [UIImage imageNamed:@"splash portrait empty.png"];
    [_backgroundSkyImage setImage:background];
}

- (void) loaddDataAlternate {
    
    //importPerformanceData *_importPerformanceData = [[importPerformanceData alloc]init];
    //[_importPerformanceData loadACThumbsAndData];
   
}

- (void) loadACThumbsAndData {
    
    
    NSLog(@"1 loadDataSeq");
    
    
    
    //NSString *previousListVersion = [[NSUserDefaults standardUserDefaults]  stringForKey:@"listVersion"];
    int flagLoadThumbnails = 1;
    
    NSURL *URL;
    NSStringEncoding encoding;
    NSError *error;
    
    NSString *imageDataUrl;
    NSData *imageData;
    UIImage *image;
    NSData *imageDataPNG;
    
    // get list of all available aircraft from backend
    
    
    NSString *baseDataURL = @"https://www.gyronimo.online/0aaGyroData/allAvailableAircraft/";        
    NSString *urlWithConfigID =  @"https://www.gyronimoserver.com/api/flightpadaircraftlist/";
    NSURL *url = [NSURL URLWithString:urlWithConfigID];
    //NSError *error = nil;
    NSURLResponse *response = nil;
    NSData *data = [[NSURLSession sharedSession] sendSynchronousDataTaskWithURL:url returningResponse:&response error:&error];
    NSDictionary *dictionaryAll = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; 
    //NSLog(@"dictionaryAll: %@", dictionaryAll); 
    
    NSArray *dictArray = [dictionaryAll valueForKey:@"data"];
     
    NSLog(@"2 loadDataSeq");
    
    NSString *allText = @"";
    allText = [allText stringByAppendingString: @"All Available Aircraft"];
    allText = [allText stringByAppendingString: @"|version =^8"];
    
    for(int i =0; i<dictArray.count; i++) {  
        
        NSDictionary *dictHeader = [dictArray objectAtIndex:i];
        //NSLog(@"dictHeader: %@", dictHeader);  
        
        allText = [allText stringByAppendingString: @"|"];
        
        NSString *addString = [ [NSString alloc] initWithFormat:@"%@^",  [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"type"]] ];  
        
        allText = [allText stringByAppendingString: addString];
        
        NSString *headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"manufacturer"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ];                
        allText = [allText stringByAppendingString: addString];
        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"model"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];
        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"variant"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];
        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"callsign"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];
        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"unit"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];
        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"BEW"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"moment_long"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"moment_lat"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"MTOW"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"max_fuel"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"description_line1"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];
        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"description_line2"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];
        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"category"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"version"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
        allText = [allText stringByAppendingString: addString];            
        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"image_name"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ];         
        allText = [allText stringByAppendingString: addString];
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"id_backend"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ];
        allText = [allText stringByAppendingString: addString];
        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"display_manufacturer"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ];
        allText = [allText stringByAppendingString: addString];
        
        
        headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"display_name"]];
        if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
        addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ];
        allText = [allText stringByAppendingString: addString];
        
        
    }
    
    NSLog(@"3 loadDataSeq");
    NSString *importedText = allText;
    [[NSUserDefaults standardUserDefaults]  setObject:importedText  forKey:@"allAvailableAircraftText"];         
    //NSLog(@"allText: %@", allText);  
    //make array to load aircraft images:  
    NSMutableDictionary *ACthumbnailDictionary = [[NSMutableDictionary alloc] init];
    NSMutableArray *ACimages = [[NSMutableArray alloc] init];         
    NSString *allAvailText = importedText;
    NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"|"];
    NSArray *components = [allAvailText componentsSeparatedByCharactersInSet:charSet];
    //NSLog(@"components %@", components);     
    NSLog(@"4 loadDataSeq");
    
   
    for(int i =0; i<components.count; i++) {        
        NSArray* componentItems  = [[components objectAtIndex:i] componentsSeparatedByString:@"^"];        
        if (componentItems.count > 1) {  
            
            if ([[componentItems objectAtIndex:0] isEqualToString:@"Heli"] || [[componentItems objectAtIndex:0] isEqualToString:@"FixedWing"]) { 
                
                if (![ACimages containsObject:[componentItems objectAtIndex:15]  ]) {                         
                    if ([[componentItems objectAtIndex:15] length] > 1 ) {
                        [ACimages addObject: [componentItems objectAtIndex:15] ];    
                        //NSLog(@"loading  ACimage: %@", [componentItems objectAtIndex:15]);                             
                        //gyronimo.online/0aaGyroData/allAvailableAircraft/thumb_DA42.png
                        //gyronimo.online/0aaGyroData/allAvailableAircraft/thumb_C172
                        //load ac images                             
                        NSString *imageName =  [componentItems objectAtIndex:15];
                        //NSLog(@"1 imageName: %@", imageName);  
                        imageName  = [ imageName stringByReplacingOccurrencesOfString:@" " withString:@""];
                        imageName  = [ imageName stringByReplacingOccurrencesOfString:@"\n" withString:@""];   
                        //NSLog(@"2 imageName: %@", imageName);
                        NSString *imageDiskName = [ [NSString alloc] initWithFormat:@"thumb_%@.jpg", imageName]; 
                        NSString *imageDiskName2 = [ [NSString alloc] initWithFormat:@"thumb_%@", imageName];
                        //NSLog(@"3 imageName: %@", imageDiskName);
                        UIImage *tempImage;
                        NSString* myImagePath = [[NSBundle mainBundle] pathForResource:imageDiskName2 ofType:@"jpg"];                            
                        if (myImagePath != nil) {
                            tempImage = [UIImage imageNamed:imageDiskName];                                
                            //NSLog(@"i have this image on file %@", imageDiskName );                                 
                            ACthumbnailDictionary[imageDiskName] = @"onFile";
                        }else{
                            imageDataUrl = [ [NSString alloc] initWithFormat:@"%@thumb_%@.jpg", baseDataURL, imageName];                             
                            //NSLog(@"need to load imageDataUrl %@", imageDataUrl );
                            NSLog(@"pic not on file: %@", imageName );
                            NSURL *imageURL = [NSURL URLWithString: imageDataUrl ];
                            //NSLog(@"imageURL %@", imageURL );                                
                            imageData = [NSData dataWithContentsOfURL:imageURL];
                            image = [UIImage imageWithData:imageData];
                            imageDataPNG = [NSData dataWithData:UIImagePNGRepresentation(image)];                                
                            if (image) {
                                NSString *imageToSave = [NSString stringWithFormat:@"thumb_%@", imageName ];
                                ACthumbnailDictionary[imageToSave] = imageData ;
                                //NSLog(@"saving image -%@-", imageToSave);
                            }else{
                                NSString *imageToSave = [NSString stringWithFormat:@"thumb_%@", imageName ];
                                ACthumbnailDictionary[imageToSave] = imageData ;
                                //NSLog(@"!!!! NO PERF IMAGE for -%@- ", imageToSave);
                            }                                
                        }
                    }                           
                }
            }//end            
        }
    }
    NSLog(@"5 loadDataSeq");
    if (flagLoadThumbnails == 1) {
        NSLog(@"6 loadDataSeq");
        [[NSUserDefaults standardUserDefaults]  setObject: ACthumbnailDictionary  forKey:@"ACthumbnailDictionary"];
    } 
    
    
    NSLog(@"7 loadDataSeq");
    //NSLog(@"ACthumbnailDictionary %@", ACthumbnailDictionary);
    
}



- (void) checkAllServersOnline {
   
    NSLog(@"checkAllServersOnline");
    
    NSError *error;
    NSString *urlWithConfigID =  @"https://www.gyronimoserver.com/api/flightpadaircraftlist/";
    NSURL *url = [NSURL URLWithString:urlWithConfigID];
    NSURLResponse *response = nil;
    NSData *data = [[NSURLSession sharedSession] sendSynchronousDataTaskWithURL:url returningResponse:&response error:&error];  
    if (!error) {
        NSLog(@"no error"); 
        //[self loadACThumbsAndData];
    }else{     
        NSLog(@"error!!!");  
        alertFlag = 6;
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Critical Error: Can not reach server."
                              message:@"There seem to be a network issue. Can not connect to Gyronimo Server. Please contact your network administrator or try a different network, For example try connecting via a hotspot from your phone."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }
 
    NSLog(@"checkAllServersOnline done");
    
}

- (void)viewDidLoad
{
    NSLog(@"1 start sequence ---------");
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.      
    [self didLoadStartup];
     
}

- (void) didLoadStartup {
    
    NSLog(@"2 start sequence");
    
    importPerformanceDataClass_ = [[importPerformanceData alloc] init];
    [self addChildViewController:importPerformanceDataClass_];    
    [importPerformanceDataClassView_ addSubview:importPerformanceDataClass_.view];
    importPerformanceDataClass_.view.frame = importPerformanceDataClassView_.bounds;
    [importPerformanceDataClass_ didMoveToParentViewController:self];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];    
    float MBpagevisit = [defaults  floatForKey: @"MBpagevisit"];        
    NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];  
    
    NSLog(@"3 start sequence");
    
    NSString *didReadDisclaimer  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"didReadDisclaimer"];    
    //NSLog(@"didReadDisclaimer %@", didReadDisclaimer);
    if (didReadDisclaimer.length < 1) {         
        _viewStart5Disclaimer.hidden = NO;
        [_viewOne bringSubviewToFront:_viewStart5Disclaimer];
        _viewStartWithoutAccount.hidden = YES;
        [_viewOne bringSubviewToFront:_viewStart5Disclaimer];
    }else{
        _viewStartWithoutAccount.hidden = NO;
        _viewStart5Disclaimer.hidden = YES;
    }
    
    
    NSLog(@"4 start sequence");
    if (MBpagevisit < 10 ) { // first start  - wirklich      
        NSLog(@"5 start sequence");
        [[NSUserDefaults standardUserDefaults]  setObject:  @""  forKey:@"licenseKey"]; 
        //NSLog(@"start checkAllServersOnline");
        //[self checkAllServersOnline];
    }
    
    NSLog(@"6 start sequence");
    _viewStart3.hidden = YES;
    
    [_startSpinner startAnimating];
    [_startSpinner2 startAnimating];
    
    arrayCustomerName   = [[NSMutableArray alloc] init];
    arrayUserName   = [[NSMutableArray alloc] init];
    arrayUserPassword   = [[NSMutableArray alloc] init];
    arrayUserFleetControlID   = [[NSMutableArray alloc] init];
    arrayUserExtras   = [[NSMutableArray alloc] init];
    usernameAndPasswordMatch = 0;
    
    _labelLoadingData.hidden = YES;
    _logInButton.hidden = NO;
    
    _viewStart4License.hidden = YES;
    
    [_viewOne bringSubviewToFront:_viewStart1];
    [_viewOne bringSubviewToFront:_viewStart2];
    [_viewOne bringSubviewToFront:_viewStart3];
    [_viewOne bringSubviewToFront:_viewStart5Disclaimer];
    
    _labelWelcome.text = @"";
    
    _inputPassword.text  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"_inputPassword"];
    _inputUserName.text  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"_inputUserName"];
    activeCustomerName = [[NSUserDefaults standardUserDefaults]  stringForKey: @"activeCustomerName"];
    activeFleetControlID= [[NSUserDefaults standardUserDefaults]  stringForKey: @"activeFleetControlID"];
    
    NSLog(@"7 start sequence");
    //NSLog(@"1 activeCustomerName = %@", activeCustomerName);
    
    if ([activeCustomerName length] < 1) {
        NSLog(@"8  start sequence");
        _viewStart1.hidden = YES;
        _viewStart2.hidden = NO;
        //[_logInButton setTitle: @"Log In" forState:UIControlStateNormal];
        
    }else{
        NSLog(@"9 start sequence");
        //NSLog(@"1 activeCustomerName = %@", activeCustomerName);       
        if ([activeCustomerName isEqualToString:@"Tester"] || [activeCustomerName isEqualToString:@"Test User"]  || [activeCustomerName isEqualToString:@"noAccount"] ) {
            _labelWelcome.text = @"Welcome to Flight Pad!";
            NSLog(@"10 start sequence");
            usernameAndPasswordMatch = 1;
        }else{
            NSLog(@"11 start sequence");
            if (([self is_online])) {  
                NSLog(@"12 start sequence");
                [self checkCredentials];
                NSLog(@"13 start sequence");
                //NSLog(@"usernameAndPasswordMatch %d", usernameAndPasswordMatch);                                
            }            
            _labelWelcome.text = [ [NSString alloc] initWithFormat:@"Welcome %@ !", activeCustomerName ];
            
            NSLog(@"14 start sequence");
        } 
        
        //NSLog(@"1 usernameAndPasswordMatch %d", usernameAndPasswordMatch); 
        
        NSLog(@"15 start sequence");
        
        if (usernameAndPasswordMatch < 1 && ![customerFolderName isEqualToString:@"noAccount"] && [self is_online]) {    
            NSLog(@"16 start sequence");
            _viewStart1.hidden = YES;
            _viewStart2.hidden = NO;
            
            _inputUserName.text = @""; _inputPassword.text = @"";
            
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Username or Password Change"
                                  message:@"The username and password did change. Please log in again."
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles: nil];
            [alert show]; 
            
        }else{
            NSLog(@"17 start sequence");
            _viewStart1.hidden = NO;
            _viewStart2.hidden = YES;
            
        }
        
        NSLog(@"18 start sequence");
        NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
        if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
        
        NSLog(@"19 start sequence");
        //NSLog(@"1 userExtraCheck %@", userExtraCheck); 
        
        if ([userExtraCheck rangeOfString:@"licensing"].location != NSNotFound  ) {  
            //NSLog(@"this user needs licensing, so we need to check if license is still active or revoked");
            NSLog(@"20 start sequence");
            NSString *licenseCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"licenseKey"];
            //NSLog(@"licenseCheck %@", licenseCheck); 
            
            if (licenseCheck.length < 4) {
                NSLog(@"21 start sequence");
                //NSLog(@"this user needs licensing, but no license entered, so we start from scratch");
                
                _viewStart1.hidden = YES;
                _viewStart3.hidden = YES;
                _viewStart4License.hidden = YES;
                _viewStart2.hidden = NO;
                
                _inputUserName.text = @""; _inputPassword.text = @"";
                
                UIAlertView *alert = [[UIAlertView alloc]
                                      initWithTitle:@"License Required"
                                      message:@"This App requires a license, please enter your username and password,then enter your licence key."
                                      delegate:self
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles: nil];
                [alert show]; 
            }else{
                NSLog(@"22 start sequence");
                //NSLog(@"ok, there is a license entered, but is it still valid?");
                
                if (([self is_online])) { 
                    NSLog(@"23 start sequence");
                    NSString *url = [ [NSString alloc] initWithFormat:@"%@%@", @"https://gyronimo.kulanaserver.com/api/default/check_license/1.0/still_active/?key=", licenseCheck ];
                    NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: url]];
                    __autoreleasing NSError* error = nil;        
                    id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
                    
                    NSArray *allItems = [result objectForKey:@"check"];   
                    NSDictionary *item = [allItems objectAtIndex:0];  
                    NSString *resultText = [item objectForKey:@"resultText"];
                    
                    //NSLog(@"resultText: %@", resultText);
                    
                    if ([resultText isEqualToString:@"licenseKey still active"] ) {                        
                        //NSLog(@"all good, still active");       
                        NSLog(@"24 start sequence");
                    }else{      
                        NSLog(@"25 start sequence");
                        //NSLog(@"ALARM !! license not active!");
                        _viewStart1.hidden = YES;
                        _viewStart3.hidden = YES;
                        _viewStart4License.hidden = YES;
                        _viewStart2.hidden = NO;
                        
                        _inputUserName.text = @""; _inputPassword.text = @"";                        
                        _inputLicense1.text = @"";
                        _inputLicense2.text = @"";
                        _inputLicense3.text = @"";
                        
                        [[NSUserDefaults standardUserDefaults]  setObject:  @""  forKey:@"licenseKey"]; 
                        
                        UIAlertView *alert = [[UIAlertView alloc]
                                              initWithTitle:@"License Invalid"
                                              message:@"The license key is invalid. Please enter username and password, then enter a new license key."
                                              delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles: nil];
                        [alert show]; 
                    }
                }
            }
        }
    }
    NSLog(@"26 start sequence  ----------------");
}


- (bool)is_online {
    
    NSLog(@"1 check is_online");
    
    int serverOnline = 0;
    
    //check if server is reachable / device is online
    //Reachability *r = [Reachability reachabilityWithHostName:@"gyronimo.kulanaserver.com"];
    Reachability *r = [Reachability reachabilityWithHostName:@"gyronimo.online"]; 
    NetworkStatus internetStatus = [r currentReachabilityStatus];
    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
        NSLog(@"1 check is_online false");
        
    } else {
        NSLog(@"1 check is_online true");       
        serverOnline = serverOnline + 1;
    }    
    r = [Reachability reachabilityWithHostName:@"gyronimo.kulanaserver.com"];    
    internetStatus = [r currentReachabilityStatus];
    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
        NSLog(@"2 check is_online false");        
    } else {
        NSLog(@"2 check is_online true");      
        serverOnline = serverOnline + 1;
    }
    
    //sdf
    //serverOnline = 2;
    
    if (serverOnline == 2) {
        NSLog(@"3 check is_online true");
        return true;
    }else{
        NSLog(@"3 check is_online false");
        return false;
    }
    
   
    
}

- (void) dismissKeyboard {
    [self.view endEditing:YES];
}


- (void) checkCredentials {
    
    //NSLog(@"checkCredentials");
    
    checkCustomerData *_checkCustomerData = [[checkCustomerData alloc]init];
    [_checkCustomerData checkCustomerDataFiles:_inputUserName.text];
    NSString *key = @"userData_";
    [arrayCustomerName setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayCustomerName"]] mutableCopy]];
    [arrayUserName setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserName"]] mutableCopy]];
    [arrayUserPassword setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserPassword"]] mutableCopy]];
    [arrayUserFleetControlID setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserFleetControlID"]] mutableCopy]];
    [arrayUserExtras setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserExtras"]] mutableCopy]];
    // check if username and password do match
    usernameAndPasswordMatch = 0;
    
    for(int i =0; i<arrayUserName.count; i++) {
        
        if ([_inputUserName.text isEqualToString:[arrayUserName objectAtIndex:i]] ) {                    
            //NSLog(@"checking _inputUserName.text  %@", _inputUserName.text);
            //NSLog(@"checking against  %@", [arrayUserPassword objectAtIndex:i]);
            if ([_inputPassword.text isEqualToString:[arrayUserPassword objectAtIndex:i]] ) {
                usernameAndPasswordMatch = i;                       
                break;
            }
        }
    }
    
}



- (void) actionLogIn {
    
    [self dismissKeyboard];
    //NSLog(@"buttonActionLogIn");
    
    
    if ([_inputUserName.text isEqualToString:@"demo"] && [_inputPassword.text isEqualToString:@"freeac"]) {
        [[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
         [self logInWithoutAccount];
        return;
    }
    
    if ([_inputUserName.text isEqualToString:@"demo"] && [_inputPassword.text isEqualToString:@"noac"]) {
        //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
        [self logInWithoutAccount];
        return;
    }
    if ([_inputUserName.text isEqualToString:@"demo"] && [_inputPassword.text isEqualToString:@"noacfree"]) {
        //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
        [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightPadCategory3"        forKey:@"purchasedProductID"];  
         [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFleetIncrease5"        forKey:@"purchasedIncreaseID"]; 
        [self logInWithoutAccount];
        return;
    }
    
    if ([_inputUserName.text isEqualToString:@"demo"] && [_inputPassword.text isEqualToString:@"allacfree"]) {
        //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
        [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightPadCategory5"        forKey:@"purchasedProductID"];  
        [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFleetIncrease5"        forKey:@"purchasedIncreaseID"]; 
        [self logInWithoutAccount];
        return;
    }
    
    if ([_inputUserName.text isEqualToString:@"Apple912"] && [_inputPassword.text isEqualToString:@"test"]) {
        //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
        [self logInWithoutAccount];
        return;
    }
    
    
    
    if ([_inputUserName.text length] >= 1 & [_inputPassword.text length] >= 1) {
        
        if (!([self is_online])) {
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Error"
                                  message:@"Cannot reach server. Please check if this device is online."
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
        }else{
            
            
            //NSLog(@"arrayUserName %@", arrayUserName); 
                   
                   
                   
            checkCustomerData *_checkCustomerData = [[checkCustomerData alloc]init];
            [_checkCustomerData checkCustomerDataFiles:_inputUserName.text];
            NSString *key = @"userData_";
            [arrayCustomerName setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayCustomerName"]] mutableCopy]];
            [arrayUserName setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserName"]] mutableCopy]];
            [arrayUserPassword setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserPassword"]] mutableCopy]];
            [arrayUserFleetControlID setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserFleetControlID"]] mutableCopy]];
            [arrayUserExtras setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserExtras"]] mutableCopy]];
            // check if username and password do match
            usernameAndPasswordMatch = 0;
            int foundCorrectCredentials= 0;
            
            for(int i =0; i<arrayUserName.count; i++) {
                
                if ([_inputUserName.text isEqualToString:[arrayUserName objectAtIndex:i]] ) {
                    
                    
                    if ([_inputPassword.text isEqualToString:[arrayUserPassword objectAtIndex:i]] ) {
                        
                       
                        
                        foundCorrectCredentials = 1;
                        usernameAndPasswordMatch = i;
                        activeFleetControlID =  [arrayUserFleetControlID objectAtIndex:i];
                        activeCustomerName = [arrayCustomerName objectAtIndex:i]  ;
                        // save active credentials
                        [[NSUserDefaults standardUserDefaults]  setObject: _inputUserName.text    forKey:@"_inputUserName"];
                        [[NSUserDefaults standardUserDefaults]  setObject: _inputPassword.text    forKey:@"_inputPassword"];
                        [[NSUserDefaults standardUserDefaults]  setObject: activeCustomerName   forKey:@"activeCustomerName"];
                        [[NSUserDefaults standardUserDefaults]  setObject: activeFleetControlID   forKey:@"activeFleetControlID"];
                        
                        [[NSUserDefaults standardUserDefaults]  setObject:  [arrayUserExtras objectAtIndex:i]   forKey:@"userExtras"];                        
                        //NSLog(@"saving userExtras %@",  [arrayUserExtras objectAtIndex:i]  );
                        
                        //NSLog(@"saving activeFleetControlID %@", [arrayUserFleetControlID objectAtIndex:i]);
                        break;
                    }
                }
            }
            
            //NSLog(@"found ok!  usernameAndPasswordMatch %d", usernameAndPasswordMatch );
            
            if (foundCorrectCredentials ==  1) {
                
                //here if we log in first time and password is OK:
                
           
                
                NSString *licenseCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"licenseKey"];   
                
                //NSLog(@"licenseCheck %@", licenseCheck  );
                
                NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"]; 
                if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
       
                 //NSLog(@"userExtraCheck %@", userExtraCheck  );
                
                
                if ([userExtraCheck rangeOfString:@"licensing"].location != NSNotFound  && licenseCheck.length < 1 ) {  
              
                    _viewStart2.hidden = YES;                    
                    _inputLicense1.text = @"";
                    _inputLicense2.text = @"";
                    _inputLicense3.text = @"";
                    
                    _viewStart4License.hidden = NO;
                    [_viewOne bringSubviewToFront:_viewStart4License];
                  
                    
                }else{           
                
                    [self startLoadingApp];
                                        
                }  
                
               
           
                
               
                
            }else{
                
          
                
                alertFlag = 0;
                UIAlertView *alert = [[UIAlertView alloc]
                                      
                                      initWithTitle:@"Not found."
                                      message:@"We could not find your account. \nPlease contact us: info@gyronimo.com"
                                      delegate:self
                                      cancelButtonTitle:nil
                                      otherButtonTitles: @"TRY AGAIN" ,nil];
                
                [alert show];
            }
        }
    }
    
}

- (void) startLoadingApp {
    
    NSString *titleText  = [arrayCustomerName objectAtIndex:usernameAndPasswordMatch]; 
    if ([titleText isEqualToString:@"Tester"]  || [activeCustomerName isEqualToString:@"Test User"]  ) {
        _welcomeTextLabel.text = @"Welcome to Flight Pad!";
    }else{
        _welcomeTextLabel.text = [ [NSString alloc] initWithFormat:@"Welcome %@ !", activeCustomerName ];
    }                     
    _viewStart1.hidden = YES;
    _viewStart2.hidden = YES;
    _viewStart4License.hidden = YES;
    _viewStart3.hidden = NO;                    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:90.0];                    
    _viewProgress.frame = CGRectMake(_viewProgress.frame.origin.x, _viewProgress.frame.origin.y, 280, _viewProgress.frame.size.height);                    
    //_backgroundSkyImage.frame = CGRectMake(_backgroundSkyImage.frame.origin.x-500, _backgroundSkyImage.frame.origin.y-500, _backgroundSkyImage.frame.size.width + 1000, _backgroundSkyImage.frame.size.height + 1000);                    
    [UIView commitAnimations];                    
    [self performSelector: @selector (logInWithNewName) withObject:nil afterDelay: 0.1f];
    
    
}

- (IBAction)actionActivateLicense:(id)sender {
   [self dismissKeyboard];
    
     //NSLog(@"actionActivateLicense");
 
    //1. Aktivierung bei erster Benutzung in App
    //NSString *url= @"https://gyronimo.kulanaserver.com/api/default/check_license/1.0/first_time/?key=EHK-BDM-EQW";  
    
    NSString *enteredLicenseKey = [ [NSString alloc] initWithFormat:@"%@-%@-%@", _inputLicense1.text, _inputLicense2.text, _inputLicense3.text ];    
    NSString *url = [ [NSString alloc] initWithFormat:@"%@%@", @"https://gyronimo.kulanaserver.com/api/default/check_license/1.0/first_time/?key=", enteredLicenseKey ];
    
    //2. Check beim Starten der App, wenn App bereits aktiviert wurde
    //NSString *url= @"https://gyronimo.kulanaserver.com/api/default/check_license/1.0/still_active/?key=EYT-SMF-KQE";  
    
    /*
    a) Antwort, wenn licenseKey found und noch nicht aktiviert
    
    {"check": [{
        "resultCode":"OK",
        "resultText":"licenseKey is now in use",
        "customerName":"Demo Account",
        "customer":"kulana"
    }]}
    b) Antwort, wenn licensKey found aber bereits "in use" (nur bei kunden mit aktiviertem licensing)
    
    {"check": [{
        "resultCode":"NOK",
        "resultText":"licenseKey already in use",
        "customerName":"Demo Account",
        "customer":"kulana"
    }]}
    c) Antwort, wenn licenseKey not found
    
    {"check": [{
        "resultCode":"NOK",
        "resultText":"licenseKey invalid",
        "customerName":"",
        "customer":""
    }]}
     */
    
  
    NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: url]];
    __autoreleasing NSError* error = nil;        
    id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
    
    NSArray *allItems = [result objectForKey:@"check"];   
    NSDictionary *item = [allItems objectAtIndex:0];  
    //NSLog(@"allItems %@", allItems); 
    //NSLog(@"resultCode: %@", [item objectForKey:@"resultCode"]);
    
    NSString *resultText = [item objectForKey:@"resultText"];
    
    //NSLog(@"resultText: %@", resultText);
    
    if ([resultText isEqualToString:@"licenseKey is now in use"] ) {
        //NSLog(@"activation successful saaving key: %@", enteredLicenseKey);
        [[NSUserDefaults standardUserDefaults] setObject:enteredLicenseKey forKey:@"licenseKey"];
        
        //NSLog(@"_inputUserName.text: %@", _inputUserName.text);
        //NSLog(@"_inputPassword: %@", _inputPassword.text);
        
        if ([_inputUserName.text isEqualToString:@"redeem21"] && [_inputPassword.text isEqualToString:@"redeem21"]) {            
            //NSLog(@"logInWithoutAccount");            
            //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightPadCategory2"        forKey:@"purchasedProductID"];              
            [self logInWithoutAccount];
            return;
        }
        
        if ([_inputUserName.text isEqualToString:@"redeem31"] && [_inputPassword.text isEqualToString:@"redeem31"]) {            
            //NSLog(@"logInWithoutAccount");            
            //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightPadCategory3"        forKey:@"purchasedProductID"];             
            [self logInWithoutAccount];
            return;
        }
        
        if ([_inputUserName.text isEqualToString:@"redeem41"] && [_inputPassword.text isEqualToString:@"redeem41"]) {            
            //NSLog(@"logInWithoutAccount");            
            //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightPadCategory4"        forKey:@"purchasedProductID"];
            [self logInWithoutAccount];
            return;
        }
        
        if ([_inputUserName.text isEqualToString:@"redeem51"] && [_inputPassword.text isEqualToString:@"redeem51"]) {            
            //NSLog(@"logInWithoutAccount");            
            //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightPadCategory5"        forKey:@"purchasedProductID"];           
            [self logInWithoutAccount];
            return;
        }
        
        if ([_inputUserName.text isEqualToString:@"redeem23"] && [_inputPassword.text isEqualToString:@"redeem23"]) {            
            //NSLog(@"logInWithoutAccount");            
            //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightPadCategory2"        forKey:@"purchasedProductID"];  
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFleetIncrease3"        forKey:@"purchasedIncreaseID"]; 
            [self logInWithoutAccount];
            return;
        }
        
        if ([_inputUserName.text isEqualToString:@"redeem33"] && [_inputPassword.text isEqualToString:@"redeem33"]) {            
            //NSLog(@"logInWithoutAccount");            
            //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightPadCategory3"        forKey:@"purchasedProductID"];  
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFleetIncrease3"        forKey:@"purchasedIncreaseID"]; 
            [self logInWithoutAccount];
            return;
        }
        
        if ([_inputUserName.text isEqualToString:@"redeem43"] && [_inputPassword.text isEqualToString:@"redeem43"]) {            
            //NSLog(@"logInWithoutAccount");            
            //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightPadCategory4"        forKey:@"purchasedProductID"];  
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFleetIncrease3"        forKey:@"purchasedIncreaseID"]; 
            [self logInWithoutAccount];
            return;
        }
        
        if ([_inputUserName.text isEqualToString:@"redeem53"] && [_inputPassword.text isEqualToString:@"redeem53"]) {            
            //NSLog(@"logInWithoutAccount");            
            //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightPadCategory5"        forKey:@"purchasedProductID"];  
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFleetIncrease3"        forKey:@"purchasedIncreaseID"]; 
            [self logInWithoutAccount];
            return;
        }
        if ([_inputUserName.text isEqualToString:@"redeem55"] && [_inputPassword.text isEqualToString:@"redeem55"]) {            
            //NSLog(@"logInWithoutAccount");            
            //[[NSUserDefaults standardUserDefaults]  setObject: @"demoMode"   forKey:@"demoMode"];
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightPadCategory5"        forKey:@"purchasedProductID"];  
            [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFleetIncrease3"        forKey:@"purchasedIncreaseID"]; 
            [self logInWithoutAccount];
            return;
        }
        
        
        
        
        
        [self startLoadingApp];
    }
    
    if ([resultText isEqualToString:@"licenseKey already in use"] ) {
        //NSLog(@"activation NOT successful");
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"licenseKey"];
        
        UIAlertView *alert = [[UIAlertView alloc]
                              
                              initWithTitle:@"Key Already In Use"
                              message:@"The license key you entered is already in use. Please enter an unused key."
                              delegate:self
                              cancelButtonTitle:nil
                              otherButtonTitles: @"OK" ,nil];
        
        [alert show];
        
    }
    
    if ([resultText isEqualToString:@"licenseKey invalid"] ) {
        //NSLog(@"licenseKey invalid");
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"licenseKey"];
        
        UIAlertView *alert = [[UIAlertView alloc]
                              
                              initWithTitle:@"LicenseKey Invalid"
                              message:@"The license key you entered is invalid."
                              delegate:self
                              cancelButtonTitle:nil
                              otherButtonTitles: @"OK" ,nil];
        
        [alert show];
        
    }
    
    //NSLog(@"item %@", item);    
    //NSLog(@"customer %@", [item objectForKey:@"customer"]);
    //NSLog(@"customerName %@", [item objectForKey:@"customerName"]);
    
    
}

- (IBAction)actionAcceptDisclaimer:(id)sender {
 
    _viewStart5Disclaimer.hidden = YES; 
    _viewStartWithoutAccount.hidden = NO;    
    [[NSUserDefaults standardUserDefaults]  setObject: @"yes"   forKey:@"didReadDisclaimer"];    
    [self performSelector: @selector (loadACThumbsAndData) withObject:nil afterDelay: 0.1f];
}



- (IBAction)actionAccountInfo:(id)sender {
    alertFlag = 5;
    
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Gyronimo Account"
                          message:@"You do not need an account to use the app for weight & balance and performance. However, if you operate a larger fleet an account enables you to manage your aircraft-, crew- and equipment data. \n\nAlso, if you require custom aircraft interior configurations, performance charts or other features please contact us via info@gyronimo.com. \nThank you."
                          delegate:self
                          cancelButtonTitle:@"Close"
                          otherButtonTitles: @"Contact Gyronimo via Email" ,nil];
    [alert show];
    
}

- (IBAction)actionOpenWebsite:(id)sender {
    [self openWebsite];
}

- (void) openWebsite {
    
    [[UIApplication sharedApplication]
     
     openURL:[NSURL URLWithString:@"http://www.gyronimo.com"]];   
    
}


- (IBAction)closeKeyboardEnterUsername:(id)sender {
    [self actionLogIn];
    
}


- (IBAction)buttonActionLogIn:(id)sender {
    [self actionLogIn];
    
}

- (IBAction)logInOptions:(id)sender {
    
    //NSLog(@"logInOptions");
    //NSLog(@"activeCustomerName %@", activeCustomerName);
    
    if ([activeCustomerName length] < 1) {
       // we are not logged in
        _viewStart1.hidden = YES;
        _viewStart2.hidden = NO;
    }else{
        // we are logged in! - so log out!
        
        if (!([self is_online])) {
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Device Offline"
                                  message:@"Cannot reach server. Please check if this device is online."
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            
        }else{
            alertFlag = 3;
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Log Out!"
                                  message:@"This will reset the app and all data. Are you sure?"
                                  delegate:self
                                  cancelButtonTitle:@"CANCEL"
                                  otherButtonTitles: @"LOG OUT!" ,nil];
            [alert show];            
            
        }
        
        

        
        
        
      }
}

- (IBAction)actionButtonStartWhenLoggedIn:(id)sender {
    
    //NSLog(@"actionButtonStartWhenLoggedIn");
    
    NSString *serverURLforTest  = [[NSUserDefaults standardUserDefaults]  stringForKey:@"serverUrl"];
    if (serverURLforTest.length < 1) {
        //NSLog(@"1");
        //NSLog(@"no serverURLforTest");
        [self performSelector: @selector (resetAppToFactorySettings) withObject:nil afterDelay: 0.1f];
    }else{
         //NSLog(@"2");
        
        
        ViewController *second = [[ViewController alloc] initWithNibName:nil bundle:nil];
        second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        second.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:second animated:YES completion:nil];
        
        
    }
}

- (IBAction)actionButtonStartWithResetWhenLoggedIn:(id)sender {
    
    if (!([self is_online])) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Error"
                              message:@"Cannot reach server. Please check if this device is online."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];

        
    }else{
        alertFlag = 2;
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Reset!"
                              message:@"This will reset the app and all data. Are you sure?"
                              delegate:self
                              cancelButtonTitle:@"CANCEL"
                              otherButtonTitles: @"RESET!" ,nil];
        [alert show];
        
    }
    
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    // log in with new name
    if (alertFlag == 1) {
        // log in ok
        if (buttonIndex == 0) {
            [self logInWithNewName];
        }
    }
    //**************
    
    // reset when logged in
    if (alertFlag == 2) {
        //cancel
        if (buttonIndex == 0) {
        }
        if (buttonIndex == 1) {
            [self resetAppToActiveUserSettings];
        }
    }
    
    //**************
    
    // log out
    if (alertFlag == 3) {
        //cancel
        if (buttonIndex == 0) {
        }
        if (buttonIndex == 1) {
            _viewStart1.hidden = YES;
            _viewStart2.hidden = NO;
            [self resetAppToFactorySettings];
        }
    }
    
    // force log out - wrong username after username change
    
    if (alertFlag == 4) {
        //cancel
        if (buttonIndex == 0) {
            _viewStart1.hidden = YES;
            _viewStart2.hidden = NO;
            [self resetAppToFactorySettings];
        }
       
    }
    
    
    if (alertFlag == 5) {
        //cancel
        if (buttonIndex == 0) {           
        }
        
        if (buttonIndex == 1) {
            
            MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];            
            [composer setMailComposeDelegate: self];            
            if ([MFMailComposeViewController canSendMail]) {                
                [composer setToRecipients:[NSArray arrayWithObjects:@"info@gyronimo.com", nil]];                
                [composer setSubject:@"Flight Pad"];                
                [composer setMessageBody: @"" isHTML:NO];                
                [composer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];                
                [self presentModalViewController:composer animated:YES];               
            }           
        }        
    }
    
    
    if (alertFlag == 6) {
        //no connection on initial start
        if (buttonIndex == 0) {   
            //goes back to checkAllServersOnline
            [self checkAllServersOnline];
        }
        
    }
    
}



- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            //NSLog(@"Mail cancelled");
            break;
        case MFMailComposeResultSaved:
            //NSLog(@"Mail saved");
            break;
        case MFMailComposeResultSent:
            //NSLog(@"Mail sent");
            break;
        case MFMailComposeResultFailed:
            //NSLog(@"Mail sent failure: %@", [error localizedDescription]);            
            break;
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"error"
                                  
                                                            message:[NSString stringWithFormat:@"error %@", [error description]]
                                  
                                                           delegate:nil cancelButtonTitle:@"dismiss" otherButtonTitles:nil, nil];
            
            [alert show];            
            [self dismissModalViewControllerAnimated:YES];            
    }    
    // Close the Mail Interface
    [controller dismissViewControllerAnimated:YES completion:nil];
}


- (void) logInWithNewName {
    
    //NSLog(@"logInWithNewName ");
    
    _viewStart1.hidden = YES;
    _viewStart2.hidden = YES;
    _viewStart3.hidden = NO;
    
    
    _labelLoadingData.hidden = NO;
    _logInButton.hidden = YES;
    
    //NSLog(@"logInWithNewName activeFleetControlID %@", activeFleetControlID);
    //NSLog(@"logInWithNewName activeCustomerName %@", activeCustomerName);
    
    [[NSUserDefaults standardUserDefaults]  setObject:activeFleetControlID         forKey:@"_inputCommunicationKey"];
    [[NSUserDefaults standardUserDefaults]  setObject:activeCustomerName         forKey:@"customerFolderName"];
    //NSLog(@"setting customerFolderName 1 %@", activeCustomerName);
    
    NSString *customerFolderName  = [activeCustomerName stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *baseUrl = @"https://www.gyronimo.online/0aaGyroData/";
    NSString *serverUrl = [ [NSString alloc] initWithFormat:@"%@%@/", baseUrl, customerFolderName ];
    [[NSUserDefaults standardUserDefaults]  setObject:baseUrl                       forKey:@"baseUrl"];
    [[NSUserDefaults standardUserDefaults]  setObject:serverUrl                     forKey:@"serverUrl"];
    [[NSUserDefaults standardUserDefaults]  setObject:baseUrl                       forKey:@"baseDataURL"];
    [[NSUserDefaults standardUserDefaults]  setObject:serverUrl                     forKey:@"customerDataURL"];
    
  
    
    ViewController *second = [[ViewController alloc] initWithNibName:nil bundle:nil];
    second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    second.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:second animated:YES completion:nil];

    
}


- (IBAction)StartWithoutAccount:(id)sender {
    [self logInWithoutAccount];
}

- (void) logInWithoutAccount {
    
    NSLog(@"1 logInWithoutAccount ");
    
    _viewStart1.hidden = YES;
    _viewStart2.hidden = YES;
    _viewStart3.hidden = NO;
    
    
    _labelLoadingData.hidden = NO;
    _logInButton.hidden = YES;
    
    //NSLog(@"logInWithNewName activeFleetControlID %@", activeFleetControlID);
    //NSLog(@"logInWithNewName activeCustomerName %@", activeCustomerName);
    
    activeFleetControlID = @"noID";
    activeCustomerName = @"noAccount";
    
    [[NSUserDefaults standardUserDefaults]  setObject:activeFleetControlID         forKey:@"_inputCommunicationKey"];
    [[NSUserDefaults standardUserDefaults]  setObject:activeCustomerName         forKey:@"customerFolderName"];
    [[NSUserDefaults standardUserDefaults]  setObject: @"noAccount"   forKey:@"activeCustomerName"];
    
     
    
    
    NSString *baseUrl = @"https://www.gyronimo.online/0aaGyroData/";
    NSString *serverUrl = [ [NSString alloc] initWithFormat:@"%@%@/", baseUrl, activeCustomerName ];
    [[NSUserDefaults standardUserDefaults]  setObject:baseUrl                       forKey:@"baseUrl"];
    [[NSUserDefaults standardUserDefaults]  setObject:serverUrl                     forKey:@"serverUrl"];
    [[NSUserDefaults standardUserDefaults]  setObject:baseUrl                       forKey:@"baseDataURL"];
    [[NSUserDefaults standardUserDefaults]  setObject:serverUrl                     forKey:@"customerDataURL"];
    
    

    
     ViewController *second = [[ViewController alloc] initWithNibName:nil bundle:nil];
     second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
     second.modalPresentationStyle = UIModalPresentationFullScreen;
     [self presentViewController:second animated:YES completion:nil];
    
    
}



- (void) resetAppToFactorySettings {
    
   // check if we have a license key, if so make the key available!      
    
    NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
    if (userExtraCheck.length < 1) { userExtraCheck = @"";   }
    
    if ([userExtraCheck rangeOfString:@"licensing"].location != NSNotFound  ) {  
        //NSLog(@"this user needs licensing, so we need to check if license is still active or revoked");        
        NSString *licenseCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"licenseKey"];
        //NSLog(@"licenseCheck %@", licenseCheck);  
        if (licenseCheck.length > 4) {
            //NSLog(@"this user has license and loggs out, so we need to make license available); 
            NSString *url = [ [NSString alloc] initWithFormat:@"%@%@", @"https://gyronimo.kulanaserver.com/api/default/check_license/1.0/disconnect/?key=", licenseCheck ];
            NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: url]];
            __autoreleasing NSError* error = nil;        
            id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
            
            NSArray *allItems = [result objectForKey:@"check"];   
            NSDictionary *item = [allItems objectAtIndex:0];  
            NSString *resultText = [item objectForKey:@"resultText"];
            
            //NSLog(@"resultText: %@", resultText);            
            
        }
    }
    
    
    //NSLog(@"resetAppToFactorySettings !!!!!");    
    // rescue the com key before total recall
    arrayCustomerName   = [[NSMutableArray alloc] init];
    arrayUserName   = [[NSMutableArray alloc] init];
    arrayUserPassword   = [[NSMutableArray alloc] init];
    arrayUserFleetControlID   = [[NSMutableArray alloc] init];
    arrayUserExtras   = [[NSMutableArray alloc] init];
    NSString *key = @"userData_";
    [arrayCustomerName setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayCustomerName"]] mutableCopy]];
    [arrayUserName setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserName"]] mutableCopy]];
    [arrayUserPassword setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserPassword"]] mutableCopy]];
    [arrayUserFleetControlID setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserFleetControlID"]] mutableCopy]];
    [arrayUserExtras setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserExtras"]] mutableCopy]];
    
    [[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
    NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *mainPath    = [myPathList  objectAtIndex:0];
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSArray *fileArray = [fileMgr contentsOfDirectoryAtPath:mainPath error:nil];
    for (NSString *filename in fileArray)  {
        [fileMgr removeItemAtPath:[mainPath stringByAppendingPathComponent:filename] error:NULL];
    }
     //save again
    [[NSUserDefaults standardUserDefaults]  setObject:arrayCustomerName     forKey:[key stringByAppendingString:@"arrayCustomerName"]];
    [[NSUserDefaults standardUserDefaults]  setObject:arrayUserName     forKey:[key stringByAppendingString:@"arrayUserName"]];
    [[NSUserDefaults standardUserDefaults]  setObject:arrayUserPassword     forKey:[key stringByAppendingString:@"arrayUserPassword"]];
    [[NSUserDefaults standardUserDefaults]  setObject:arrayUserFleetControlID     forKey:[key stringByAppendingString:@"arrayUserFleetControlID"]];
    [[NSUserDefaults standardUserDefaults]  setObject:arrayUserExtras     forKey:[key stringByAppendingString:@"arrayUserExtras"]];
    
    _inputUserName.text = @"";
    _inputPassword.text = @"";
    [[NSUserDefaults standardUserDefaults]  setObject: _inputUserName.text    forKey:@"_inputUserName"];
    [[NSUserDefaults standardUserDefaults]  setObject: _inputPassword.text    forKey:@"_inputPassword"];
    [[NSUserDefaults standardUserDefaults]  setObject: @""   forKey:@"activeCustomerName"];
    [[NSUserDefaults standardUserDefaults]  setObject: @""   forKey:@"activeFleetControlID"];
    
    [[NSUserDefaults standardUserDefaults]  setObject: @"yes"   forKey:@"didReadDisclaimer"]; 
    
    
    
    
    
    selectedUnitForItems=@"";
    selectedUnitForFuel=@"";
    triggerCopySliderSettingsWithFlightID=@"";
    specialdata1=@"";
    specialdata2=@"";
    formatString1=@"";
    formatString2=@"";
    formatString3=@"";
    formatString4=@"";
    fuelEnterMode=@"";
    calcMode=@"plan";
    unitsDistance=@"";
    unitsElevation=@"";
    unitsAltimeter=@"";
    
   
    triggerSetDefaultsForPerformanceCharts = 0;
    triggerDoNotShowPerfChart = 0;
    flagDoNotCreateFlightNow = 0;
    flagClimbEndMustBeHigherThanElevation = 0;
    flagTriggerSpecialCreateFlight = 0;
    flagCheckForAvailableAircrafts = 0;
    flagCopyFlight = 0;
    [self loadACThumbsAndData];
    //_viewStart5Disclaimer.hidden = NO;
    //[_viewOne bringSubviewToFront:_viewStart5Disclaimer];
    
    
    
    
}

- (void) resetAppToActiveUserSettings {
    
    _labelLoadingData.hidden = NO;
    _logInButton.hidden = YES;
    
    // rescue key before total recall
    arrayCustomerName   = [[NSMutableArray alloc] init];
    arrayUserName   = [[NSMutableArray alloc] init];
    arrayUserPassword   = [[NSMutableArray alloc] init];
    arrayUserFleetControlID   = [[NSMutableArray alloc] init];
    arrayUserExtras   = [[NSMutableArray alloc] init];
    
    NSString *username = _inputUserName.text;
    NSString *password = _inputPassword.text;
    NSString *customerName = activeCustomerName;
    NSString *fleetControlID = activeFleetControlID;
    

    
    NSString *key = @"userData_";
    [arrayCustomerName setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayCustomerName"]] mutableCopy]];
    [arrayUserName setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserName"]] mutableCopy]];
    [arrayUserPassword setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserPassword"]] mutableCopy]];
    [arrayUserFleetControlID setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserFleetControlID"]] mutableCopy]];
    [arrayUserExtras setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayUserExtras"]] mutableCopy]];

    
    //delete all data / clear memory (this does not work!)
    [[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
    NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *mainPath    = [myPathList  objectAtIndex:0];
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSArray *fileArray = [fileMgr contentsOfDirectoryAtPath:mainPath error:nil];
    for (NSString *filename in fileArray)  {
        [fileMgr removeItemAtPath:[mainPath stringByAppendingPathComponent:filename] error:NULL];
    }
    
    
    //save again
    [[NSUserDefaults standardUserDefaults]  setObject:arrayCustomerName     forKey:[key stringByAppendingString:@"arrayCustomerName"]];
    [[NSUserDefaults standardUserDefaults]  setObject:arrayUserName     forKey:[key stringByAppendingString:@"arrayUserName"]];
    [[NSUserDefaults standardUserDefaults]  setObject:arrayUserPassword     forKey:[key stringByAppendingString:@"arrayUserPassword"]];
    [[NSUserDefaults standardUserDefaults]  setObject:arrayUserFleetControlID     forKey:[key stringByAppendingString:@"arrayUserFleetControlID"]];
    [[NSUserDefaults standardUserDefaults]  setObject:arrayUserExtras     forKey:[key stringByAppendingString:@"arrayUserExtras"]];
    
    activeFleetControlID = fleetControlID;
    activeCustomerName = customerName;
    _inputUserName.text = username;
    _inputPassword.text = password;
    [[NSUserDefaults standardUserDefaults]  setObject: _inputUserName.text      forKey:@"_inputUserName"];
    [[NSUserDefaults standardUserDefaults]  setObject: _inputPassword.text      forKey:@"_inputPassword"];
    [[NSUserDefaults standardUserDefaults]  setObject: activeCustomerName       forKey:@"activeCustomerName"];
    [[NSUserDefaults standardUserDefaults]  setObject: activeFleetControlID     forKey:@"activeFleetControlID"];
    [[NSUserDefaults standardUserDefaults]  setObject: activeFleetControlID     forKey:@"_inputCommunicationKey"];
    [[NSUserDefaults standardUserDefaults]  setObject: activeCustomerName       forKey:@"customerFolderName"];
     NSLog(@"setting customerFolderName 3 %@", activeCustomerName);

    NSString *customerFolderName  = [activeCustomerName stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *baseUrl = @"https://www.gyronimo.online/0aaGyroData/";
    NSString *serverUrl = [ [NSString alloc] initWithFormat:@"%@%@/", baseUrl, customerFolderName ];
    [[NSUserDefaults standardUserDefaults]  setObject:baseUrl                       forKey:@"baseUrl"];
    [[NSUserDefaults standardUserDefaults]  setObject:serverUrl                     forKey:@"serverUrl"];
    [[NSUserDefaults standardUserDefaults]  setObject:baseUrl                       forKey:@"baseDataURL"];
    [[NSUserDefaults standardUserDefaults]  setObject:serverUrl                     forKey:@"customerDataURL"];
    
    NSNotification *myNotification = [NSNotification notificationWithName:@"resetHelicopterData"
                                                                   object:self //object is usually the object posting the notification
                                                                 userInfo:nil]; //userInfo is an optional dictionary
    
    //Post it to the default notification center
    [[NSNotificationCenter defaultCenter] postNotification:myNotification];
    [self dismissModalViewControllerAnimated:YES];
    
    
    
}




@end

