//
//  FleetManager.m
//  FlightPad
//
//  Created by Claus Richter on 2/9/19.
//

#import "FleetManager.h"
#import "ViewController.h"

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

#define IAPproductID1 @"GyronimoFlightPadCategory1"
#define IAPproductID2 @"GyronimoFlightPadCategory2"
#define IAPproductID3 @"GyronimoFlightPadCategory3"
#define IAPproductID4 @"GyronimoFlightPadCategory4"
#define IAPproductID5 @"GyronimoFlightPadCategory5"
#define IAPproductID6 @"GyronimoFlightSchoolPackHelicopter" // was FlightPadCategory6  is now GyronimoFlightSchoolPackHelicopter
#define IAPproductID7 @"GyronimoFlightSchoolPackFixedWing" // was FlightPadCategory6  is now GyronimoFlightSchoolPackHelicopter
#define IAPproductID8 @"GyronimoFlightSchoolPackALL" // was FlightPadCategory6  is now GyronimoFlightSchoolPackHelicopter
#define IAPproductIDIncrease3 @"GyronimoFleetIncrease3"
#define IAPproductIDIncrease5 @"GyronimoFleetIncrease5"


int maxNumberOfAircraftInFleet = 1;
int maxNumberOfAircraftCopies = 5;
int formatIsLandscape = 1;
int flagRestoreDone = 0;
@interface FleetManager () {
    
 importConfigurations *importConfigurationsClass_;   
    
}
@end

@implementation FleetManager{
    ViewController* mainControllerClass_;    
}

int purchaseType = 0;

#define blueButtonColor [UIColor colorWithRed: 79.0/255.0 green: 105.0/255.0 blue: 144.0/255.0 alpha: 1.0] // this is red
#define GreenColor [UIColor colorWithRed: 33.0/255.0 green: 176.0/255.0 blue: 21.0/255.0 alpha: 1.0] // this is green
#define yellowSpecialColor [UIColor colorWithRed: 265.0/255.0 green: 216.0/255.0 blue: 0.0/255.0 alpha: 1.0] // this is yellow
#define orangeSpecialColor [UIColor colorWithRed: 265.0/255.0 green: 150.0/255.0 blue: 0.0/255.0 alpha: 1.0] // this is yellow
#define mediumGrayColor [UIColor colorWithRed: 90.0/255.0 green: 90.0/255.0 blue: 90.0/255.0 alpha: 1.0] // this is medium gray
#define verydarkGrayColor [UIColor colorWithRed: 60.0/255.0 green: 60.0/255.0 blue: 60.0/255.0 alpha: 1.0] // this is dark gray
#define lightBlueColor [UIColor colorWithRed: 83.0/255.0 green: 148.0/255.0 blue: 255.0/255.0 alpha: 1.0] // this is dark gray
#define verylightBlueColor [UIColor colorWithRed: 179.0/255.0 green: 202/255.0 blue: 238/255.0 alpha: 1.0] // this is dark gray
#define lightOrangeColor [UIColor colorWithRed: 265.0/255.0 green: 150.0/255.0 blue: 0.0/255.0 alpha: 1.0] // this is orange



-(void)viewDidAppear:(BOOL)animated
{
   
    [self createAllAvailableAircraftList]; 
    [self mainRoutine];
    
}


- (void)didMoveToParentViewController:(UIViewController *)parent {
    [super didMoveToParentViewController:parent];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.    
    mainControllerClass_ = [[ViewController alloc] init];  
    
    //hide views  
    
    if ( [_dropDownFilterAircraftAllAvailable.text isEqualToString:@""]) {
        _dropDownFilterAircraftAllAvailable.text = @"Show All Aircraft";
    }  
  
    if ( [_dropDownFilterAircraftOnSetup.text isEqualToString:@""]) {
        _dropDownFilterAircraftOnSetup.text = @"Show All Aircraft";
    }
    
    
   
    _viewAircraftSetup.hidden = YES;
    _viewInAppPurchases.hidden = YES;
    _viewAllAvailList.hidden = NO;
    [_viewOne bringSubviewToFront:_viewAllAvailList];
    
    
    [_scrollViewAllAvailableAircraft setScrollEnabled:YES];
    [_scrollViewForViewMyFleet setScrollEnabled:YES];    
    [_scrollViewAircraftSetup setScrollEnabled:YES];
    [_scrollViewIAPlist setScrollEnabled:YES];
      
    uploadedAircraft = [[NSMutableArray alloc] init];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(actionNotificationViewAllAvailAircraft:) //note the ":" - should take an NSNotification as parameter
                                                 name:@"notificationViewAllAvailAircraft"
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(actionNotificationViewAircraftManager:) //note the ":" - should take an NSNotification as parameter
                                                 name:@"notificationViewAircraftManager"
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(actionNotificationViewPurchase:) //note the ":" - should take an NSNotification as parameter
                                                 name:@"notificationViewPurchase"
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(actionNotificationSetPortrait:) //note the ":" - should take an NSNotification as parameter
                                                 name:@"notificationSetPortrait"
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(actionNotificationSetLandscape:) //note the ":" - should take an NSNotification as parameter
                                                 name:@"notificationSetLandscape"
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(actionNotificationLoadedAllAircraftList:) //note the ":" - should take an NSNotification as parameter
                                                 name:@"notificationLoadedAllAircraftList"
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(actionNotificationCreateMyFleetList:) //note the ":" - should take an NSNotification as parameter
                                                 name:@"notificationCreateMyFleetList"
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(actionNotificationLoadFleetForFlightSchool:) //note the ":" - should take an NSNotification as parameter
                                                 name:@"notificationLoadFleetForFlightSchool"
                                               object:nil];


    
}


- (void)actionNotificationLoadFleetForFlightSchool:(NSNotification *)notification {
    
    //NSLog(@"actionNotificationLoadFleetForFlightSchool");   
    
   
    //[self loadFleetFromFC];
    //[self loadFleetFromFC];
     //[self createMyFleetList];
    //[self createAircraftSetupList];
   
    
  /*
    //start loading
    flagDoNotCreateFlightNow = 1; 
    //NSLog(@"actionLoadAircraftData flagDoNotCreateFlightNow = 1");
    
    
    NSString *note = [[NSString alloc] initWithFormat:@"%f", 0.0];
    //NSLog(@"noting 3");
    [[NSNotificationCenter defaultCenter] postNotificationName: @"noteCreateFakeFlight" object: note];   
    triggerSetDefaultsForPerformanceCharts = 0; 
    [self createAircraftSetupList];    
    //showAircraftSetup    
    _viewAllAvailList.hidden = YES;
    _viewInAppPurchases.hidden = YES;        
    _viewAircraftSetup.hidden = NO;
    [_viewOne bringSubviewToFront:_viewAircraftSetup];
    flagFleetWasChanged = 0;
    ViewController *parent = (ViewController *)self.parentViewController;
    [parent showLoadDataFM];    
    [self performSelector: @selector (startLoadingData) withObject:nil afterDelay: 0.1f]; 
    
     //NSLog(@"end actionNotificationLoadFleetForFlightSchool");   
*/

}

- (void)actionNotificationCreateMyFleetList:(NSNotification *)notification {
    //NSLog(@"triggerCreateMyFleetList ");   
    arrayDictAllAircraft = [[NSMutableArray alloc] init];
    [arrayDictAllAircraft setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"]  mutableCopy]];
    [self createMyFleetList];    
}
    
- (void)actionNotificationViewAllAvailAircraft:(NSNotification *)notification {

    //NSLog(@"actionNotificationViewAllAvailAircraft");
    _viewAircraftSetup.hidden = YES;
    _viewInAppPurchases.hidden = YES;    
    
    _viewAllAvailList.hidden = NO;
    [_viewOne bringSubviewToFront:_viewAllAvailList];
    
    [self createAircraftSetupList];
    [self createAllAvailableAircraftList];
    
}

- (void)actionNotificationViewAircraftManager:(NSNotification *)notification {
    
    //NSLog(@"actionNotificationViewAircraftManager");
    _viewAllAvailList.hidden = YES;
    _viewInAppPurchases.hidden = YES;    
    
    _viewAircraftSetup.hidden = NO;
    [_viewOne bringSubviewToFront:_viewAircraftSetup];
    
    [self createAircraftSetupList];
    [self createAllAvailableAircraftList];
    
    
}

- (void)actionNotificationViewPurchase:(NSNotification *)notification {
    
    
    
    _viewAllAvailList.hidden = YES;
    _viewAircraftSetup.hidden = YES;    
    _viewInAppPurchases.hidden = NO;
    [_viewOne bringSubviewToFront:_viewInAppPurchases];
    [self startInAppPurchase];    
    
    
    
}



- (void)actionNotificationSetLandscape:(NSNotification *)notification {
    
    formatIsLandscape = 1;
    _viewAllAvailList.frame = CGRectMake(128, 62, 768, 706);
    _viewInAppPurchases.frame = CGRectMake(0, 62, 1024, 706);
    _viewAircraftSetup.frame = CGRectMake(0, 62, 1024, 706);
    
}

- (void)actionNotificationSetPortrait:(NSNotification *)notification {
    float xLeft = 129;
    
    formatIsLandscape = 0;
    _viewAllAvailList.frame = CGRectMake(0, 62, 768, 706);
    _viewInAppPurchases.frame = CGRectMake(0 - xLeft, 62, 1024, 706);
    _viewAircraftSetup.frame = CGRectMake(0 - xLeft, 62, 1024, 706);
    
}

    

- (void)createAllAvailableAircraftList {
    
   //NSLog(@"createAllAvailableAircraftList !!!!!!!!");
    
    NSMutableArray *arrayManufacturers = [[NSMutableArray alloc] init];
    [arrayManufacturers addObject:@"Show All Aircraft"];
    [arrayManufacturers addObject:@"Show My Category Only"];
    [arrayManufacturers addObject:@"Show Helicopters Only"];
    [arrayManufacturers addObject:@"Show Fixed Wing Only"];
    
    
    
    _buttonIncreaseFleet.hidden = NO;
    
    
    
    
    _labelMyAircraftFleet.text =  [NSString stringWithFormat:@"My Aircraft (max %d)" , maxNumberOfAircraftInFleet];
    
    
    arrayDictAllAircraft= [[NSMutableArray alloc] init];
    [arrayDictAllAircraft setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"]  mutableCopy]];    
    //NSLog(@"arrayDictAllAircraft %@", arrayDictAllAircraft);  
    int weHaveAFleetLoaded = 0;
    if (arrayDictAllAircraft.count > 0) {
        weHaveAFleetLoaded = 1;
        _buttonForceReload.hidden = NO;
        _labelDownloadSIze.hidden = NO;
        _buttonLoadAircraftData.hidden = NO;
    }else{
        _buttonForceReload.hidden = YES;
        _labelDownloadSIze.hidden = YES;
        _buttonLoadAircraftData.hidden = YES;
        
    }
    
    
    NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
    if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
    //NSLog(@"userExtraCheck %@", userExtraCheck);
    
    if ([userExtraCheck rangeOfString:@"flightSchoolPackage1"].location != NSNotFound  ) {  
     
        _buttonUpdateFleetControlACdata.hidden = NO;   
        _buttonForceReload.hidden = YES;
        _buttonIncreaseFleet.hidden = YES;
    }else{
       
        _buttonUpdateFleetControlACdata.hidden = YES;
        _buttonForceReload.hidden = NO;
    }
    
    //NSLog(@"weHaveAFleetLoaded %d", weHaveAFleetLoaded);  
    
    [self checkCategories];
 
    for(UIView *subview in [_viewAllAvailableAircraft subviews]) {
        [subview removeFromSuperview];
    }
    
    NSString *allAvailText = [[NSUserDefaults standardUserDefaults]  stringForKey: @"allAvailableAircraftText"];
    NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"|"];
    NSArray *components = [allAvailText componentsSeparatedByCharactersInSet:charSet];   
    //NSLog(@"loading allAvailText %@", allAvailText);
    
    arrayAllCallsigns= [[NSMutableArray alloc] init]; 
    NSMutableDictionary *myACsDictionary = [[NSMutableDictionary alloc] init]; 
    
  
    
    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"]) {     
                
                myACsDictionary = [[NSMutableDictionary alloc] init];                 
                myACsDictionary[@"fleetACCategory"] =  [componentItems objectAtIndex:0];  // HEli 
                myACsDictionary[@"Manufacturer"] =  [componentItems objectAtIndex:1]; //Airbus               
                myACsDictionary[@"fleetAC_Type"] =  [componentItems objectAtIndex:2]; //H145 
                myACsDictionary[@"Variant"] =  [componentItems objectAtIndex:3];
                myACsDictionary[@"Callsign"] =  [componentItems objectAtIndex:4];
                myACsDictionary[@"Units"] =  [componentItems objectAtIndex:5];
                myACsDictionary[@"BEW"] =  [componentItems objectAtIndex:6];
                myACsDictionary[@"MomLong"] =  [componentItems objectAtIndex:7];
                myACsDictionary[@"MomLat"] =  [componentItems objectAtIndex:8];
                myACsDictionary[@"MTOW"] =  [componentItems objectAtIndex:9];
                myACsDictionary[@"maxFuel"] =  [componentItems objectAtIndex:10];
                myACsDictionary[@"description1"] =  [componentItems objectAtIndex:11];               
                myACsDictionary[@"description2"] =  [componentItems objectAtIndex:12];                
                myACsDictionary[@"priceCategory"] =  [componentItems objectAtIndex:13];
                myACsDictionary[@"Version"] =  [componentItems objectAtIndex:14];                
                myACsDictionary[@"imageName"] =  [componentItems objectAtIndex:15];
                myACsDictionary[@"backendID"] =  [componentItems objectAtIndex:16];
                myACsDictionary[@"DisplayNameManufacturer"] =  [componentItems objectAtIndex:17];
                myACsDictionary[@"DisplayNamefleetAC_Type"] =  [componentItems objectAtIndex:18];
                
                [arrayAllCallsigns addObject:myACsDictionary]; 
                //NSLog(@"adding myACsDictionary %@", myACsDictionary);                
            }            
        }
    }
    
   
    
    
    
    
    
    
    int triggerNeedToUpdateAircrafts = 0;
    arrayLoadedAircraft = [[NSMutableArray alloc] init];
    arrayLoadedAircraft = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayLoadedAircraft"] mutableCopy];
    //NSLog(@"1 arrayLoadedAircraft %@", arrayLoadedAircraft);
    
    stringACtoUpdate = @"";
    
    arrayReplaceMyFleetID = [[NSMutableArray alloc] init];
    arrayReplaceMyFleetIDVersion = [[NSMutableArray alloc] init];
    
    
    if (weHaveAFleetLoaded == 1) {
        //check my fleet for updates
        
        for(int fleetID =0; fleetID<arrayDictAllAircraft.count; fleetID++) {     
            
            //NSLog(@"arrayAllCallsigns %@", [arrayAllCallsigns objectAtIndex:i]); 
            NSString *textACcategory = [[arrayDictAllAircraft objectAtIndex:fleetID] objectForKey:@"fleetACCategory"];
            NSString *textManu = [[arrayDictAllAircraft objectAtIndex:fleetID] objectForKey:@"DisplayNameManufacturer"];
            NSString *textModel = [[arrayDictAllAircraft objectAtIndex:fleetID] objectForKey:@"DisplayNamefleetAC_Type"];
            NSString *textdescription1 = [[arrayDictAllAircraft objectAtIndex:fleetID] objectForKey:@"description1"];
            NSString *textdescription2 = [[arrayDictAllAircraft objectAtIndex:fleetID] objectForKey:@"description2"];
            NSString *versionOfLoadedAircraft = [[arrayDictAllAircraft objectAtIndex:fleetID] objectForKey:@"Version"];
            
           
            
            
            
            for(int i =0; i<arrayAllCallsigns.count; i++) { 
                //NSLog(@"i %d", i);
                //NSLog(@"arrayAllCallsigns %@", [arrayAllCallsigns objectAtIndex:i]);     
                
               
                NSString *loadedManufacturer = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"DisplayNameManufacturer"];
                NSString *loadedModel = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"DisplayNamefleetAC_Type"];
                NSString *loadeddescription1 = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"description1"];
                NSString *loadeddescription2 = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"description2"];
                NSString *versionShouldBe = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"Version"];
                
                if ([loadedManufacturer isEqualToString:textManu] && [loadedModel isEqualToString:textModel] && [loadeddescription1 isEqualToString:textdescription1] && [loadeddescription2 isEqualToString:textdescription2]  ) {                     
                    //NSLog(@"this is in the fleet %@", textModel); 
                    if ([versionShouldBe isEqualToString:versionOfLoadedAircraft]) {
                        //NSLog(@"version is OK"); 
                    }else{
                        //NSLog(@"version is not OK"); 
                        NSString *textForarrayLoadedAircraft = [ [NSString alloc] initWithFormat:@"%@%@%@", textACcategory, textManu, textModel];
                        
                         if ([arrayLoadedAircraft containsObject:textForarrayLoadedAircraft]) {                             
                             //NSLog(@"1 arrayLoadedAircraft %@", arrayLoadedAircraft);                             
                             //NSLog(@"we need to remove this: %@", textForarrayLoadedAircraft);                              
                             NSInteger index = [arrayLoadedAircraft indexOfObject:textForarrayLoadedAircraft];                             
                             [arrayLoadedAircraft removeObjectAtIndex:index];                             
                             //NSLog(@"2 arrayLoadedAircraft %@", arrayLoadedAircraft);                             
                             //[[NSUserDefaults standardUserDefaults]  setObject:arrayLoadedAircraft  forKey:@"arrayLoadedAircraft" ];                             
                             //NSLog(@"1 arrayDictAllAircraft %@", arrayDictAllAircraft);                                 
                             [arrayReplaceMyFleetID  addObject:[ [NSString alloc] initWithFormat:@"%d", fleetID]];
                             [arrayReplaceMyFleetIDVersion  addObject:[ [NSString alloc] initWithFormat:@"%@", versionShouldBe]];
                         }
                        stringACtoUpdate = [stringACtoUpdate stringByAppendingString:textManu];
                        stringACtoUpdate = [stringACtoUpdate stringByAppendingString:@", "];
                        stringACtoUpdate = [stringACtoUpdate stringByAppendingString:textModel];
                        stringACtoUpdate = [stringACtoUpdate stringByAppendingString:@"\n"];

                        triggerNeedToUpdateAircrafts = 1;
                    }
                }
            }
        }
    }
    
    
    
    //NSLog(@"1 arrayAllCallsigns %@", arrayAllCallsigns);
    
    NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"DisplayNameManufacturer"  ascending:YES]; 
    NSArray *sortDescriptors = @[nameDescriptor];
    NSArray *ordered = [arrayAllCallsigns sortedArrayUsingDescriptors:sortDescriptors];    
    arrayAllCallsigns= [[NSMutableArray alloc] init];
    [arrayAllCallsigns addObjectsFromArray:ordered]; 
    //NSLog(@"saving arrayAllCallsigns");
     [[NSUserDefaults standardUserDefaults]  setObject: arrayAllCallsigns forKey:@"arrayAllCallsigns"];
    
    float yStart = 20;
    float xPos1 = 0;
    float yGap = 95; 
    float cellWidth = _scrollViewAllAvailableAircraft.frame.size.width;
    float cellHeight = 25;
    float yPos = 0;
    
    float acImageWidth = 120;
    
     
    
    NSMutableDictionary *ACthumbnailDictionary = [[NSMutableDictionary alloc] init];
    ACthumbnailDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"ACthumbnailDictionary"] mutableCopy];

   
    int countAConList = 0;  
    
    for(int i =0; i<arrayAllCallsigns.count; i++) { 
        //NSLog(@"i %d", i);
        //NSLog(@"arrayAllCallsigns %@", [arrayAllCallsigns objectAtIndex:i]);     
        
        NSString *priceCategory = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"priceCategory"];        
        NSString *MTOM = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"MTOW"];
        NSString *maxFuel = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"maxFuel"];
        NSString *description1 = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"description1"];
        NSString *description2 = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"description2"];
        NSString *units = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"Units"];
        NSString *imageName = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"imageName"];        
        imageName  = [ imageName stringByReplacingOccurrencesOfString:@" " withString:@""];
        imageName  = [ imageName stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        
        NSString *textACcategory = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"fleetACCategory"];
        NSString *textManu = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"DisplayNameManufacturer"];
        
        
        if (![arrayManufacturers containsObject: textManu]) {
            [arrayManufacturers addObject:textManu];
        }
        
        if (![_dropDownFilterAircraftAllAvailable.text isEqualToString:@"Show All Aircraft"]) {
            
             [_scrollViewAllAvailableAircraft scrollRectToVisible:CGRectMake( 1,1,1,1 ) animated:NO];   
            
            if ([_dropDownFilterAircraftAllAvailable.text isEqualToString:@"Show Helicopters Only"]) {
                if (![textACcategory isEqualToString:@"Heli"]) {
                    continue;
                }
            }else  if ([_dropDownFilterAircraftAllAvailable.text isEqualToString:@"Show Fixed Wing Only"]) {
                if (![textACcategory isEqualToString:@"FixedWing"]) {
                    continue;
                }
            }else  if ([_dropDownFilterAircraftAllAvailable.text isEqualToString:@"Show All Aircraft"]) {
                
            }else  if ([_dropDownFilterAircraftAllAvailable.text isEqualToString:@"Show My Category Only"]) {
                
                if ([priceCategory integerValue] <= maxAvailableCategory   ) {  
                    // you can have this
                }else{
                    continue;
                }
                
            }else if (![textManu isEqualToString:_dropDownFilterAircraftAllAvailable.text]) {
                continue;
            }
        }
        
        countAConList = countAConList + 1;
        //NSLog(@"countAConList %d", countAConList);
        
        _viewAllAvailableAircraft.frame = CGRectMake(_viewAllAvailableAircraft.frame.origin.x, _viewAllAvailableAircraft.frame.origin.y, _scrollViewAllAvailableAircraft.frame.size.width, (countAConList * yGap) + yGap);
        [_scrollViewAllAvailableAircraft setContentSize:CGSizeMake(_scrollViewAllAvailableAircraft.frame.size.width, _viewAllAvailableAircraft.frame.size.height)];
        
        
        NSString *fuelUnits =@"Gal";
        if ([units isEqualToString:@"kg"]) {
            fuelUnits =@"Ltr";
        }
        
        //NSLog(@"1 imageName %@", imageName);
       
        if ([priceCategory integerValue] <= maxAvailableCategory   ) {   
            
            // you can have this
            
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake( xPos1, yStart + yPos , cellWidth, yGap - 10 )];
            lineView.backgroundColor = [UIColor darkGrayColor];
            [_viewAllAvailableAircraft addSubview:lineView]; 
                       
            // set thumbnails
            NSString *imageToLoad = [NSString stringWithFormat:@"thumb_%@.jpg", imageName ]; 
            
            //NSLog(@"ACthumbnailDictionary %@", ACthumbnailDictionary);
            
            if ([[ACthumbnailDictionary objectForKey: imageToLoad] isEqualToString:@"onFile"]) { 
                //NSLog(@"onFile %@", imageToLoad);
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake( cellWidth - acImageWidth - 10, yStart + yPos + 10, acImageWidth, acImageWidth/2 )];
                UIImage *imageOnFile = [UIImage imageNamed:imageToLoad];                
                [imageView setImage: imageOnFile];
                [_viewAllAvailableAircraft addSubview: imageView];
            }else{  
                
                //NSLog(@" not onFile %@", imageToLoad);
                // neet to load this
                if (imageName.length > 1) {                
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake( cellWidth - acImageWidth - 10, yStart + yPos + 10, acImageWidth, acImageWidth/2 )]; 
                    NSString *imageToLoadFromData = [NSString stringWithFormat:@"thumb_%@", imageName ];
                    [imageView setImage: [UIImage imageWithData:[ACthumbnailDictionary objectForKey: imageToLoadFromData]]];
                    [_viewAllAvailableAircraft addSubview: imageView];
                }else{
                    // use standard image
                    UIImage *exampleIAPImage = [UIImage imageNamed:@"BlueBoxNoImage.png"];
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake( cellWidth - acImageWidth - 10, yStart + yPos + 10, acImageWidth, acImageWidth/2 )];
                    [imageView setImage: exampleIAPImage];
                    [_viewAllAvailableAircraft addSubview: imageView]; 
                }
            }
            
            
            // Make and Model
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1  + 10, yStart + yPos + 5, cellWidth, cellHeight )];
            label.font = [UIFont boldSystemFontOfSize:17];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor whiteColor];
            [label  setText: [[NSString alloc] initWithFormat:@"%@ %@ ", [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"DisplayNameManufacturer"], [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"DisplayNamefleetAC_Type"] ] ];
            [_viewAllAvailableAircraft addSubview: label];
           
            
            //category
            label = [[UILabel alloc] initWithFrame:CGRectMake( cellWidth - acImageWidth - 10, yStart + yPos + acImageWidth/2 + 5 , acImageWidth, 15 )];
            label.font = [UIFont boldSystemFontOfSize:13];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor blackColor];
            label.backgroundColor = [UIColor greenColor];
            [label  setText: [[NSString alloc] initWithFormat:@"Category: %@ ", priceCategory ] ];   
            [_viewAllAvailableAircraft addSubview: label];
            
            //info
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 10, yStart + yPos + 25, cellWidth, cellHeight )];
            label.font = [UIFont boldSystemFontOfSize:13];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];
            [label  setText: [[NSString alloc] initWithFormat:@"MTOM: %@ %@, Fuel Capacity: %@ %@", MTOM, units, maxFuel, fuelUnits   ] ];
            [_viewAllAvailableAircraft addSubview: label];
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1  + 10, yStart + yPos + 25 + 15, cellWidth, cellHeight )];
            label.font = [UIFont boldSystemFontOfSize:13];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];
            [label  setText: [[NSString alloc] initWithFormat:@"%@ ", description1   ] ];   
            [_viewAllAvailableAircraft addSubview: label];
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 10, yStart + yPos + 25 + 15 + 15, cellWidth, cellHeight )];
            label.font = [UIFont boldSystemFontOfSize:13];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];
            [label  setText: [[NSString alloc] initWithFormat:@"%@ ", description2   ] ];            
            [_viewAllAvailableAircraft addSubview: label];  
            
            
            UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            aButton.frame     = CGRectMake(xPos1, yStart + yPos, cellWidth, 80 );                    
            aButton.showsTouchWhenHighlighted = YES;           
            [aButton setTag:i];
            [aButton addTarget:self action:@selector(actionSelectMyFleetAircraft:) forControlEvents:UIControlEventTouchUpInside];
            [_viewAllAvailableAircraft addSubview:aButton];  
            
            
            yPos = yPos +  yGap; 
            
            
            
            
        }else{         
            // you can not have this
            
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake( xPos1, yStart + yPos , cellWidth, yGap - 10 )];
            lineView.backgroundColor = [UIColor darkGrayColor];
            [_viewAllAvailableAircraft addSubview:lineView]; 
            
            
            // set thumbnails
            NSString *imageToLoad = [NSString stringWithFormat:@"thumb_%@.jpg", imageName ]; 
            
            //NSLog(@"ACthumbnailDictionary %@", ACthumbnailDictionary);
            
            if ([[ACthumbnailDictionary objectForKey: imageToLoad] isEqualToString:@"onFile"]) { 
                //NSLog(@"onFile %@", imageToLoad);
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake( cellWidth - acImageWidth - 10, yStart + yPos + 10, acImageWidth, acImageWidth/2 )];
                UIImage *imageOnFile = [UIImage imageNamed:imageToLoad];                
                [imageView setImage: imageOnFile];
                [_viewAllAvailableAircraft addSubview: imageView];
            }else{  
                
                //NSLog(@" not onFile %@", imageToLoad);
                // neet to load this
                if (imageName.length > 1) {                
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake( cellWidth - acImageWidth - 10, yStart + yPos + 10, acImageWidth, acImageWidth/2 )]; 
                    NSString *imageToLoadFromData = [NSString stringWithFormat:@"thumb_%@", imageName ];
                    [imageView setImage: [UIImage imageWithData:[ACthumbnailDictionary objectForKey: imageToLoadFromData]]];
                    [_viewAllAvailableAircraft addSubview: imageView];
                }else{
                    // use standard image
                    UIImage *exampleIAPImage = [UIImage imageNamed:@"BlueBoxNoImage.png"];
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake( cellWidth - acImageWidth - 10, yStart + yPos + 10, acImageWidth, acImageWidth/2 )];
                    [imageView setImage: exampleIAPImage];
                    [_viewAllAvailableAircraft addSubview: imageView]; 
                }
            }
            
           
            
            // Make and Model
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 10, yStart + yPos + 5, cellWidth, cellHeight )];
            label.font = [UIFont boldSystemFontOfSize:17];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];
            [label  setText: [[NSString alloc] initWithFormat:@"%@ %@ ", [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"DisplayNameManufacturer"], [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"DisplayNamefleetAC_Type"] ] ];
            [_viewAllAvailableAircraft addSubview: label];
            
            
            //category
            label = [[UILabel alloc] initWithFrame:CGRectMake( cellWidth - acImageWidth - 10, yStart + yPos + acImageWidth/2 + 5 , acImageWidth, 15 )];
            label.font = [UIFont boldSystemFontOfSize:13];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor lightGrayColor];
            label.backgroundColor = [UIColor blackColor];
            [label  setText: [[NSString alloc] initWithFormat:@"Category: %@ ", priceCategory ] ];   
            [_viewAllAvailableAircraft addSubview: label];
            
            //info
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 10, yStart + yPos + 25, cellWidth, cellHeight )];
            label.font = [UIFont boldSystemFontOfSize:13];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];
            [label  setText: [[NSString alloc] initWithFormat:@"MTOM: %@%@, Fuel Capacity: %@%@", MTOM, units, maxFuel, fuelUnits   ] ];
            [_viewAllAvailableAircraft addSubview: label];
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1  + 10, yStart + yPos + 25 + 15, cellWidth, cellHeight )];
            label.font = [UIFont boldSystemFontOfSize:13];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];
            [label  setText: [[NSString alloc] initWithFormat:@"%@ ", description1   ] ];   
            [_viewAllAvailableAircraft addSubview: label];
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 10, yStart + yPos + 25 + 15 + 15, cellWidth, cellHeight )];
            label.font = [UIFont boldSystemFontOfSize:13];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];
            [label  setText: [[NSString alloc] initWithFormat:@"%@ ", description2   ] ];            
            [_viewAllAvailableAircraft addSubview: label];   
            
            
            UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            aButton.frame     = CGRectMake(xPos1, yStart + yPos, cellWidth, 80 );                    
            aButton.showsTouchWhenHighlighted = YES;           
            [aButton setTag:i];
            [aButton addTarget:self action:@selector(actionSelectMyFleetAircraft:) forControlEvents:UIControlEventTouchUpInside];
            [_viewAllAvailableAircraft addSubview:aButton];           
            yPos = yPos +  yGap; 
            
        }
    }
    
     
    
    
    if (arrayDictAllAircraft.count > 0) {
        [self createMyFleetList];
    }
    
    
    if (triggerNeedToUpdateAircrafts == 1) {
        alertFlag = 3;        
        
        NSString *messageString = [ [NSString alloc] initWithFormat:@"The following aircraft files need to be updated: \n%@", stringACtoUpdate];
        
        UIAlertView *alert = [[UIAlertView alloc]
                              
                              initWithTitle:@"Aircraft Update"                              
                              message:messageString                              
                              delegate:self                              
                              cancelButtonTitle:@"Skip"                              
                              otherButtonTitles:@"Update Now (recommended)",  nil];        
        [alert show];
    }else{
     
        if (triggerCheckForACupdates == 1) {
            triggerCheckForACupdates = 0;
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Aircraft list is up to date."
                                                                                     message:nil
                                                                              preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:actionOk];
            [self presentViewController:alertController animated:YES completion:nil];            
        }
        
    }
    

   
    _dropDownFilterAircraftAllAvailable.items = arrayManufacturers;
    
    //NSLog(@"arrayManufacturers %@", arrayManufacturers);
      
}

- (IBAction)actionSelectMyFleetAircraft:(id)sender{
    
    UIButton *btn = (UIButton*)sender;
    float i = btn.tag;
    alertTransferValue = i; 
    
    // check number of copies    
    float acID = btn.tag; 
    float numberOfCount = 1;
    int flagACalreadyOnList = 0;
    NSString *textManu = [[arrayAllCallsigns objectAtIndex:acID] objectForKey:@"Manufacturer"];   
    NSString *priceCategory = [[arrayAllCallsigns objectAtIndex:acID] objectForKey:@"priceCategory"];  
    NSString *fleetAC_Type = [[arrayAllCallsigns objectAtIndex:acID] objectForKey:@"fleetAC_Type"];  
    NSString *fleetACCategory = [[arrayAllCallsigns objectAtIndex:acID] objectForKey:@"fleetACCategory"];  
    NSString *Version = [[arrayAllCallsigns objectAtIndex:acID] objectForKey:@"Version"]; 
    NSString *checkString = [NSString stringWithFormat:@"%@_%@_%@_%@_%@" , fleetACCategory, textManu, fleetAC_Type, Version, priceCategory];
    //NSLog(@"checkString %@", checkString);
    
    for(int ac =0; ac<arrayDictAllAircraft.count; ac++) { 
        NSString *fleetACCategory2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"fleetACCategory"];
        NSString *textManu2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"Manufacturer"];
        NSString *fleetAC_Type2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"fleetAC_Type"];
        NSString *Version2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"Version"];
        NSString *priceCategory2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"priceCategory"];            
        NSString *checkString2 = [NSString stringWithFormat:@"%@_%@_%@_%@_%@" , fleetACCategory2, textManu2, fleetAC_Type2, Version2, priceCategory2];
        //NSLog(@"checkString2 %@", checkString2);
        if ([checkString2 isEqualToString:checkString]) {           
            numberOfCount = numberOfCount + 1;
            
        }
    }
    //NSLog(@"numberOfCount %.0f", numberOfCount);
    
    if (numberOfCount > 1) {
        
        /*
        NSString *messageString = [ [NSString alloc] initWithFormat:@"Max number of aircraft copies is %d. If you have a larger fleet or operate a flight school, please contact us via email: info@gyronimo.com.", maxNumberOfAircraftCopies];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Max Aircraft Copies"
                                                                                 message:messageString
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil]; 
        */
        
        NSString *messageString = @"The selected aircraft model is already in your fleet. If you require multiple aircraft callsigns of the same model you can make up to five copies. First load the aircraft, then select 'Copy' in the setup list";
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Aircraft Already In Fleet"
                                                                                 message:messageString
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil]; 
        
        return;
    }
    
    
    if ([priceCategory integerValue] <= maxAvailableCategory   ) { 
        //you can have this
        //NSLog(@"you can have this");
        
        if (numberOfStandardAircraftInMyFleet >= maxNumberOfAircraftInFleet) { 
            
            NSString *messageString = [ [NSString alloc] initWithFormat:@"Max number of aircraft in your fleet is %d. You can increase the number via In-App-Purchase. Alternatively, if you have a larger fleet or operate a flight school, please contact us via email: info@gyronimo.com.", maxNumberOfAircraftInFleet];
            alertFlag = 5; 
            UIAlertView *alert = [[UIAlertView alloc]
                                  
                                  initWithTitle:@"Increase Number of Aircraft?"                              
                                  message:messageString                            
                                  delegate:self                              
                                  cancelButtonTitle:@"Cancel"                              
                                  otherButtonTitles:@"Increase Now", @"Add Locked Aircraft To My Fleet", nil];        
            [alert show];
            return;
        }
        
        
    }else{
          //NSLog(@"NOOOOO you can NOT have this");
        
        
        if (numberOfStandardAircraftInMyFleet >= maxNumberOfAircraftInFleet) { 
            
             alertFlag = 22;
            
            UIAlertView *alert = [[UIAlertView alloc]
                                  
                                  initWithTitle:@"Upgrade?"                              
                                  message:@"The category of the selected aircraft is higher than the category you purchased.\nYou can work with all aircraft in the Weight & Balance section, however, basic empty weight data, registration and performance are locked. To unlock, please purchase the category of your desired aircraft. Lower categories are included."                              
                                  delegate:self                              
                                  cancelButtonTitle:@"Cancel"                              
                                  otherButtonTitles:@"Purchase Category", @"Add Locked Aircraft To My Fleet",  nil];        
            [alert show];
             return;
        }
        
        
    }
    
    
   
    
    
   
    
    NSString *category = [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"priceCategory"]; 
    
    if ([category intValue] > maxAvailableCategory) {
        
        alertFlag = 2;        
               
        UIAlertView *alert = [[UIAlertView alloc]
                              
                              initWithTitle:@"Upgrade?"                              
                              message:@"The category of the selected aircraft is higher than the category you purchased.\nYou can work with all aircraft in the Weight & Balance section, however, basic empty weight data, registration and performance are locked. To unlock, please purchase the category of your desired aircraft. Lower categories are included."                              
                              delegate:self                              
                              cancelButtonTitle:@"Cancel"                              
                              otherButtonTitles:@"Purchase Category", @"Add Locked Aircraft To My Fleet",  nil];        
        [alert show];
        
    }else{
        
        [self addAircraftToMyFleetDictionary];
        
        
        
    }
    
}

- (IBAction)actionLoadFleet:(id)sender {
    
     if (([self is_online])) {
         
          alertFlag = 7;
         
         UIAlertView *alert = [[UIAlertView alloc]                              
                               initWithTitle:@"Update Fleet?"                              
                               message:@"This will reload all aircraft and might take 1-2 minutes. Are you sure?"                              
                               delegate:self                              
                               cancelButtonTitle:@"CANCEL"                              
                               otherButtonTitles:@"UPDATE", nil];        
         [alert show];   
     }else{
         UIAlertView *alert = [[UIAlertView alloc]                              
                               initWithTitle:@"Offline"                              
                               message:@"Updating required internet connection."                              
                               delegate:self                              
                               cancelButtonTitle:@"OK"                              
                               otherButtonTitles: nil];        
         [alert show];   
         
     }
    
    
 
   
   
  
   
}

- (void) loadFleetFromFC {
    
    //achtung  ******  
    availableACTypes = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"] mutableCopy]; 
    if (availableACTypes.count < 1) {
        availableACTypes = [[NSMutableArray alloc] init];
    }
    
    NSString * activeFleetControlID= [[NSUserDefaults standardUserDefaults]  stringForKey: @"activeFleetControlID"];
    //NSLog(@"activeFleetControlID >%@<", activeFleetControlID);
    //@"$S19Universal" 
    [[NSUserDefaults standardUserDefaults]  setObject:activeFleetControlID         forKey:@"_inputCommunicationKey"];
    ViewController *parent = (ViewController *)self.parentViewController;  
    flagCheckForAvailableAircrafts = 1;
    [parent loadHelicoptersFromServerVoid]; 
   
  
    _dropDownFilterAircraftOnSetup.text = @"Show All Aircraft";    
    [_scrollViewAllAvailableAircraft scrollRectToVisible:CGRectMake( 1,1,1,1 ) animated:NO];   
    [self createAircraftSetupList];
    
   
    
}



- (void) addAircraftToMyFleetDictionary {
    
    //NSLog(@"addAircraftToMyFleetDictionary");
    
    int i = alertTransferValue;
    arrayDictAllAircraft = [[NSMutableArray alloc] init]; 
    arrayDictAllAircraft = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"] mutableCopy];  
    if (arrayDictAllAircraft.count < 1) {
        arrayDictAllAircraft = [[NSMutableArray alloc] init];
    } 
    NSMutableDictionary *myACsDictionary = [[NSMutableDictionary alloc] init];
    myACsDictionary[@"Callsign"]        =  @"N-GYRO";
    myACsDictionary[@"fleetACCategory"]          =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"fleetACCategory"];  // HEli 
    myACsDictionary[@"Manufacturer"]    =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"Manufacturer"]; //Airbus 
    myACsDictionary[@"fleetAC_Type"]           =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"fleetAC_Type"]; //H145
    myACsDictionary[@"Variant"]         =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"Variant"];  
    myACsDictionary[@"Units"]         =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"Units"];
    myACsDictionary[@"BEW"]         =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"BEW"];
    myACsDictionary[@"MomLong"]         =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"MomLong"];
    myACsDictionary[@"MomLat"]         =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"MomLat"];
    myACsDictionary[@"SelectedUnits"]         =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"Units"];
    myACsDictionary[@"priceCategory"]         =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"priceCategory"];
    myACsDictionary[@"downloadStatus"]         =  @"notLoaded";
    myACsDictionary[@"Version"]         =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"Version"];
    myACsDictionary[@"imageName"]         =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"imageName"];
    myACsDictionary[@"backendID"]         =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"backendID"];
    myACsDictionary[@"description1"]         =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"description1"];
    myACsDictionary[@"description2"]         =  [[arrayAllCallsigns objectAtIndex:i] objectForKey:@"description2"];
    myACsDictionary[@"ACdataSource"]         =  @"backend";
    
    
    //NSLog(@"flagAddAircraftAsTrial %d", flagAddAircraftAsTrial);
    
    
    myACsDictionary[@"isATrial"]         =  @"isPurchased";
    if (flagAddAircraftAsTrial == 1) {
        flagAddAircraftAsTrial = 0;
         myACsDictionary[@"isATrial"]         =  @"isATrial";
        //NSLog(@"adding is a trial");
    }

    [arrayDictAllAircraft addObject:myACsDictionary]; 
    [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft  forKey:@"arrayDictAllAircraft"];
    
    
    [self createMyFleetList];
    //NSLog(@"adding myACsDictionary %@", myACsDictionary);
    
}


- (void) createMyFleetList {    
    
   
    //NSLog(@"createMyFleetList ");   
      
    //NSLog(@"createMyFleetList %@", arrayDictAllAircraft);
    
    _labelMyAircraftFleet.text =  [NSString stringWithFormat:@"My Aircraft (max %d)" , maxNumberOfAircraftInFleet];
   
    
    for(UIView *subview in [_viewMyFleet subviews]) {
        [subview removeFromSuperview];
    }
    
      
    
    [_scrollViewForViewMyFleet setContentOffset:CGPointZero animated:YES];
    
    float yStart = 20;
    float xPos1 = 10;
    float yGap = 70; 
    float cellWidth = _scrollViewForViewMyFleet.frame.size.width;
    float cellHeight = 25;
    float yPos = 0;
    
    _viewMyFleet.frame = CGRectMake(_viewMyFleet.frame.origin.x, _viewMyFleet.frame.origin.y, _viewMyFleet.frame.size.width, (arrayDictAllAircraft.count * yGap) + yGap );
    [_scrollViewForViewMyFleet setContentSize:CGSizeMake(_scrollViewForViewMyFleet.frame.size.width, _viewMyFleet.frame.size.height)];
    
    
    [_scrollViewForViewMyFleet setContentOffset:CGPointZero animated:YES];
    
    
    flagNeedToLoadAircraft = 0;
    numberOfStandardAircraftInMyFleet = 0;
    
    
    NSMutableArray *tempCheckArray = [[NSMutableArray alloc] init];
    
    checkArrayForCounting = [[NSMutableArray alloc] init];
    
    //NSLog(@"arrayDictAllAircraft  %@", arrayDictAllAircraft ); 
    
    
    for(int i =0; i<arrayDictAllAircraft.count; i++) { 
        
        if (![[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"ACdataSource"] isEqualToString:@"backend"] ) {              
            continue;
        }
        
        
        
        //NSLog(@"arrayAllCallsigns %@", [arrayAllCallsigns objectAtIndex:i]);        
        NSString *textManu = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Manufacturer"];
        NSString *textModel = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"];
        NSString *downloadStatus = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"downloadStatus"];
        NSString *priceCategory = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"priceCategory"];  
        NSString *fleetAC_Type = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"];  
        NSString *fleetACCategory = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetACCategory"];  
        NSString *Version = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Version"]; 
        
        NSString *checkTrial = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"isATrial"]; 
        
        //NSLog(@"checkTrial %@", checkTrial);
        
        //check if the selected aircraft is already on the list
        
        NSString *checkString = [NSString stringWithFormat:@"%@_%@_%@_%@_%@" , fleetACCategory, textManu, fleetAC_Type, Version, priceCategory];
       
        [checkArrayForCounting addObject:checkString];
        //NSLog(@"checkString  %@", checkString ); 
        
        
        int doubleCounter = 0;
        int flagACalreadyOnList = 0;
        
        if ([tempCheckArray containsObject:checkString]) {
            flagACalreadyOnList = 1;
        }else{
             [tempCheckArray addObject:checkString];
        }
        
        //NSLog(@"flagACalreadyOnList  %d", flagACalreadyOnList ); 
        
        for(int ac =0; ac<arrayDictAllAircraft.count; ac++) { 
            
              NSString *fleetACCategory2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"fleetACCategory"];
              NSString *textManu2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"Manufacturer"];
              NSString *fleetAC_Type2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"fleetAC_Type"];
              NSString *Version2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"Version"];
              NSString *priceCategory2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"priceCategory"];            
              NSString *checkString2 = [NSString stringWithFormat:@"%@_%@_%@_%@_%@" , fleetACCategory2, textManu2, fleetAC_Type2, Version2, priceCategory2];
              //NSLog(@"checkString2 %@", checkString2 );            
            
            if ([checkString isEqualToString:checkString2]) {
                doubleCounter = doubleCounter + 1;                
            }
            
        }
        
  
        if (flagACalreadyOnList > 0) {
            //NSLog(@"ac %@ already on list  doubleCounter: %d", textModel, doubleCounter );             
                       
            
        }else{   
            //NSLog(@"ac not on list" );          
            numberOfStandardAircraftInMyFleet = numberOfStandardAircraftInMyFleet + 1;
            
            //NSLog(@"priceCategory %@", priceCategory);      
            //NSLog(@"maxAvailableCategory %d", maxAvailableCategory); 
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake( xPos1 - 10, yStart + yPos - 5 , cellWidth, yGap - 15 )];
            lineView.backgroundColor = [UIColor darkGrayColor];
            [_viewMyFleet addSubview:lineView]; 
            
            // callsign
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1, yStart + yPos, cellWidth, cellHeight )];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textAlignment = NSTextAlignmentLeft;
            if ([priceCategory integerValue] <= maxAvailableCategory   ) { 
                //you can have this
                //NSLog(@"1");
                label.textColor = [UIColor greenColor];
                
                
            }else{
                //NSLog(@"2");
                label.textColor = [UIColor lightGrayColor];
            }
            
            if ([checkTrial isEqualToString:@"isATrial"]) {
                label.textColor = [UIColor lightGrayColor];
            }
            
            [label  setText: [NSString stringWithFormat:@"%@, %@",  textManu, textModel]  ];
            [_viewMyFleet addSubview: label];
            
           
            
            UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            aButton.frame     = CGRectMake(xPos1, yStart + yPos, cellWidth - 55, 40 );
            //buttonBack = [UIImage imageNamed:@"delete Icon 100x100.png"];
            //[aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];        
            [aButton setTag:i+1000];
            [aButton addTarget:self action:@selector(actionSetupAC:) forControlEvents:UIControlEventTouchUpInside];            
            [_viewMyFleet addSubview:aButton];
            
           
            if (![downloadStatus isEqualToString:@"acdownloaded"] ) {            
                label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 , yStart + yPos + 19, cellWidth, cellHeight )];
                label.font = [UIFont boldSystemFontOfSize:14];
                label.textAlignment = NSTextAlignmentLeft;
                label.textColor = [UIColor lightGrayColor];
                label.tag = 100;
                [label  setText: [[NSString alloc] initWithFormat:@"Copies: %d, not loaded", doubleCounter  ] ];    
                
                if ([checkTrial isEqualToString:@"isATrial"]) {
                     [label  setText: [[NSString alloc] initWithFormat:@"LOCKED, not loaded"  ] ];    
                }
                
                
                flagNeedToLoadAircraft = 1;
                //NSLog(@"doubleCounter %d", doubleCounter);
                [_viewMyFleet addSubview: label];    
                aButton.enabled = NO;
                
                UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                aButton.frame     = CGRectMake(cellWidth - 50, yStart + yPos + 4, 40, 40 );
                UIImage *buttonBack = [UIImage imageNamed:@"delete Icon 100x100.png"];
                [aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];        
                [aButton setTag:i];
                [aButton addTarget:self action:@selector(actionDeleteACfromMyFleet:) forControlEvents:UIControlEventTouchUpInside];            
                [_viewMyFleet addSubview:aButton];
                
                
            }else{    
                // already downloaded
                
                label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 , yStart + yPos + 19, cellWidth, cellHeight )];
                label.font = [UIFont boldSystemFontOfSize:14];
                label.textAlignment = NSTextAlignmentLeft;
                label.textColor = [UIColor lightGrayColor]; 
                label.tag = 100;
                [label  setText: [[NSString alloc] initWithFormat:@"Copies: %d", doubleCounter  ] ];  
                if ([checkTrial isEqualToString:@"isATrial"]) {
                    [label  setText: [[NSString alloc] initWithFormat:@"LOCKED, loaded"  ] ];    
                }
                [_viewMyFleet addSubview: label];
                aButton.enabled = YES;
                
                if ([priceCategory integerValue] <= maxAvailableCategory   ) { 
                    //you can have this
                    
                    // this is in your category so you can not delete it anymore
                    
                    
                    if ([checkTrial isEqualToString:@"isATrial"]) {
                        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                        aButton.frame     = CGRectMake(cellWidth - 50, yStart + yPos + 4, 40, 40 );
                        UIImage *buttonBack = [UIImage imageNamed:@"delete Icon 100x100.png"];
                        [aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];        
                        [aButton setTag:i];
                        [aButton addTarget:self action:@selector(actionDeleteACfromMyFleet:) forControlEvents:UIControlEventTouchUpInside];            
                        [_viewMyFleet addSubview:aButton];
                        
                        
                    }else{
                        
                        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                        aButton.frame     = CGRectMake(cellWidth - 50, yStart + yPos + 4, 40, 40 );
                        UIImage *buttonBack = [UIImage imageNamed:@"delete Icon 100x100.png"];
                        [aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];        
                        [aButton setTag:i];
                        aButton.alpha = 0.5;
                        [aButton addTarget:self action:@selector(actionDeleteACfromMyFleet:) forControlEvents:UIControlEventTouchUpInside];            
                        [_viewMyFleet addSubview:aButton];
                        
                        
                    }
                    
                }else{
                  // this is not your category so you can delete it - it was just a trial
                    
                    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                    aButton.frame     = CGRectMake(cellWidth - 50, yStart + yPos + 4, 40, 40 );
                    UIImage *buttonBack = [UIImage imageNamed:@"delete Icon 100x100.png"];
                    [aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];        
                    [aButton setTag:i];
                    [aButton addTarget:self action:@selector(actionDeleteACfromMyFleet:) forControlEvents:UIControlEventTouchUpInside];            
                    [_viewMyFleet addSubview:aButton];
                    
                    
                }
                
                
                
                
            }        
            yPos = yPos +  yGap;
        }
        
        }
        
        
       
        
    
    _labelDownloadSIze.text = [NSString stringWithFormat:@"Download Size Approx: %.1f MB" , numberOfStandardAircraftInMyFleet * 0.5];
    
    if (arrayDictAllAircraft.count < 1) {
        _buttonLoadAircraftData.hidden = YES;
        _labelDownloadSIze.hidden = YES;
    }else{
         _buttonLoadAircraftData.hidden = NO;
        _labelDownloadSIze.hidden = NO;
    }
    
    //NSLog(@"flagNeedToLoadAircraft %d", flagNeedToLoadAircraft);
    //NSLog(@"flagFleetWasChanged %d", flagFleetWasChanged);
    //NSLog(@"flagReduceNumberOfAircraft %d", flagReduceNumberOfAircraft);
    
    
    if ( (flagNeedToLoadAircraft == 0 & flagFleetWasChanged == 0) || flagReduceNumberOfAircraft == 1) {
       
        UIImage *buttonBack = [UIImage imageNamed:@"button generic green.png"];
        [_buttonLoadAircraftData setBackgroundImage:buttonBack forState:UIControlStateNormal];
         //[_buttonLoadAircraftData setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
         [_buttonLoadAircraftData setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_buttonLoadAircraftData setTitle:@"START" forState:(UIControlStateNormal)]; 
        
     
        for(int i =0; i<arrayDictAllAircraft.count; i++) {        
            NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
            NSDictionary *oldDict = (NSDictionary *)[arrayDictAllAircraft objectAtIndex:i];
            [newDict addEntriesFromDictionary:oldDict];        
            [newDict setObject:@"acdownloaded" forKey:@"downloadStatus"]; 
            [arrayDictAllAircraft replaceObjectAtIndex:i withObject:newDict];         
        }
        
        [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft  forKey:@"arrayDictAllAircraft"]; 
       
        
    }else{
        UIImage *buttonBack = [UIImage imageNamed:@"button strong yellow.png"];
        [_buttonLoadAircraftData setBackgroundImage:buttonBack forState:UIControlStateNormal];
        [_buttonLoadAircraftData setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_buttonLoadAircraftData setTitle:@"Load Aircraft (Start)" forState:(UIControlStateNormal)]; 
    }
    
   

    [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft  forKey:@"arrayDictAllAircraft"];
    
    //NSLog(@"createMyFleetList arrayDictAllAircraft %@", arrayDictAllAircraft);
     [self mainRoutine];      
    
}
    
    
- (IBAction)actionSetupAC:(id)sender{
    
    UIButton *btn = (UIButton*)sender;
    float acID = btn.tag; 
    
    _viewAllAvailList.hidden = YES;
    _viewInAppPurchases.hidden = YES;        
    _viewAircraftSetup.hidden = NO;
    [_viewOne bringSubviewToFront:_viewAircraftSetup]; 
    
}

    
- (IBAction)actionDeleteACfromMyFleetNotPossible:(id)sender{
    
    UIAlertView *alert = [[UIAlertView alloc]                              
                          initWithTitle:@"Aircraft Already Loaded"                              
                          message:@"This aircraft is already downloaded. You can not delete it. If you loaded a wrong aircraft, please log out or re-install the app. You can then load the correct one."                              
                          delegate:self                              
                          cancelButtonTitle:@"OK"                              
                          otherButtonTitles: nil];        
    [alert show];
    
}

- (IBAction)actionDeleteACfromMyFleet:(id)sender{
    
    UIButton *btn = (UIButton*)sender;
    float acID = btn.tag; 
    NSString *downloadStatus = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"downloadStatus"];  
    
    //NSLog(@"downloadStatus %@", downloadStatus);
    
    //NSLog(@"checkArrayForCounting %@", checkArrayForCounting);
    
    
    //check if we have multiple, if so then we just reduce the number!
    float numberOfCount = 0;
    int flagACalreadyOnList = 0;
    for(int ac =0; ac<checkArrayForCounting.count; ac++) { 
        NSString *fleetACCategory2 = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"fleetACCategory"];
        NSString *textManu2 = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"Manufacturer"];
        NSString *fleetAC_Type2 = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"fleetAC_Type"];
        NSString *Version2 = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"Version"];
        NSString *priceCategory2 = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"priceCategory"];            
        NSString *checkString2 = [NSString stringWithFormat:@"%@_%@_%@_%@_%@" , fleetACCategory2, textManu2, fleetAC_Type2, Version2, priceCategory2];
        //NSLog(@"checkString2 %@", checkString2);
        if ([checkString2 isEqualToString:[checkArrayForCounting objectAtIndex:ac]]) {
            flagACalreadyOnList = 1;
            numberOfCount = numberOfCount + 1;
            //NSLog(@" add numberOfCount %.0f", numberOfCount);
        }
    }
    
    //NSLog(@"numberOfCount %.0f", numberOfCount);
    
    if (numberOfCount > 1) {
        
        alertFlag = 1;
        alertTransfer = acID; 
        flagReduceNumberOfAircraft = 1;
        if ([downloadStatus isEqualToString:@"notLoaded"]) {  
           flagReduceNumberOfAircraft = 0; 
        }
        UIAlertView *alert = [[UIAlertView alloc]                              
                              initWithTitle:@"Reduce Number of Aircraft?"                              
                              message:@"Are you sure?"                              
                              delegate:self                              
                              cancelButtonTitle:@"CANCEL"                              
                              otherButtonTitles:@"REDUCE", nil];        
        [alert show];
        
    }else{
        if (![downloadStatus isEqualToString:@"downloaded"]) {       
            
            alertFlag = 1;
            alertTransfer = acID; 
            flagReduceNumberOfAircraft = 1;
            UIAlertView *alert = [[UIAlertView alloc]                              
                                  initWithTitle:@"Delete Aircraft?"                              
                                  message:@"Are you sure?"                              
                                  delegate:self                              
                                  cancelButtonTitle:@"CANCEL"                              
                                  otherButtonTitles:@"DELETE", nil];        
            [alert show];
        }else{
            // we delete a purchased aircraft! 
            alertFlag = 1;
            alertTransfer = acID;        
            UIAlertView *alert = [[UIAlertView alloc]
                                  
                                  initWithTitle:@"Delete Aircraft?"                              
                                  message:@"You have downloaded this aircraft. If you delete it, all flights created with this aircraft will be deleted as well."                              
                                  delegate:self                              
                                  cancelButtonTitle:@"CANCEL"                              
                                  otherButtonTitles:@"DELETE", nil];        
            [alert show];
        }
        
        
    }
    
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    //NSLog(@"button index %ld", (long)buttonIndex);    
    // 0 ist der LINKE button   1 ist der RECHTE BUTTON (KG)   
    
    //NSLog(@"alertFlag %f", alertFlag);
    
    
    if (alertFlag == 1) {
        if (buttonIndex == 1) {            
            [arrayDictAllAircraft removeObjectAtIndex:alertTransfer];  
            flagFleetWasChanged = 1;
            if (flagReduceNumberOfAircraft == 1) {  
                flagReduceNumberOfAircraft = 0;
                flagFleetWasChanged = 0;
            }
            [self createMyFleetList];
        }
    } 
    
    
    
    
    
    if (alertFlag == 2) {
        
        if (buttonIndex == 0) {             
        }        
        if (buttonIndex == 1) { 
            _viewAllAvailList.hidden = YES;
            _viewAircraftSetup.hidden = YES;    
            _viewInAppPurchases.hidden = NO;
            [_viewOne bringSubviewToFront:_viewInAppPurchases];
            [self startInAppPurchase];                
        }
        if (buttonIndex == 2) {    
            flagAddAircraftAsTrial = 1;
            [self addAircraftToMyFleetDictionary];              
        }
    } 
    
    if (alertFlag == 22) {
        
        if (buttonIndex == 0) {             
        }        
        if (buttonIndex == 1) {       
            _viewAllAvailList.hidden = YES;
            _viewAircraftSetup.hidden = YES;    
            _viewInAppPurchases.hidden = NO;
            [_viewOne bringSubviewToFront:_viewInAppPurchases];
            [self startInAppPurchase];                
        }
        if (buttonIndex == 2) {            
            flagAddAircraftAsTrial = 1;
            [self addAircraftToMyFleetDictionary];              
        }
    } 
    
    
    
    if (alertFlag == 3) {
        if (buttonIndex == 1) {            
            [self updateAircraftData];
        }
    } 
    
    if (alertFlag == 4) {
        if (buttonIndex == 1) {            
            [arrayDictAllAircraft removeObjectAtIndex:alertTransfer];  
            flagFleetWasChanged = 1;
            [self createMyFleetList];
        }
    } 
    
    
    if (alertFlag == 5) {
        
        if (buttonIndex == 0) {             
        }        
        if (buttonIndex == 1) { 
            _viewAllAvailList.hidden = YES;
            _viewAircraftSetup.hidden = YES;    
            _viewInAppPurchases.hidden = NO;
            [_viewOne bringSubviewToFront:_viewInAppPurchases];
            flagShowOnlyFleetIncrease = 1;
            [self startInAppPurchase]; 
            
        }  
        if (buttonIndex == 2) {  
            flagAddAircraftAsTrial = 1;
            [self addAircraftToMyFleetDictionary];              
        }
    } 
    
    
    if (alertFlag == 6) {
        
        //NSLog(@"22222 is flightSchoolPackageflightSchoolPackage now load it");        
        [self loadFleetFromFC];      
        //start loading
        flagDoNotCreateFlightNow = 1; 
        //NSLog(@"actionLoadAircraftData flagDoNotCreateFlightNow = 1");      
        NSString *note = [[NSString alloc] initWithFormat:@"%f", 0.0];
        //NSLog(@"noting 4");
        [[NSNotificationCenter defaultCenter] postNotificationName: @"noteCreateFakeFlight" object: note];   
        triggerSetDefaultsForPerformanceCharts = 0; 
        [self createAircraftSetupList];  
  
        //showAircraftSetup    
        _viewAllAvailList.hidden = YES;
        _viewInAppPurchases.hidden = YES;        
        _viewAircraftSetup.hidden = NO;
        [_viewOne bringSubviewToFront:_viewAircraftSetup];
        flagFleetWasChanged = 0;
        ViewController *parent = (ViewController *)self.parentViewController;      
        [parent showLoadDataFM]; 
        [self performSelector: @selector (startLoadingData) withObject:nil afterDelay: 0.1f]; 
        //NSLog(@"all clear %@", userExtraCheck); 
         
    } 
    
    
    if (alertFlag == 7) {
        
        if (buttonIndex == 0) {             
        }        
        if (buttonIndex == 1) { 
            [self loadFleetFromFC];
            
            flagDoNotCreateFlightNow = 1; 
            //NSLog(@"actionLoadAircraftData flagDoNotCreateFlightNow = 1");
            
            NSString *note = [[NSString alloc] initWithFormat:@"%f", 0.0];
            //NSLog(@"noting 1");
            [[NSNotificationCenter defaultCenter] postNotificationName: @"noteCreateFakeFlight" object: note];   
            triggerSetDefaultsForPerformanceCharts = 0; 
            [self createAircraftSetupList];    
            //showAircraftSetup    
            _viewAllAvailList.hidden = YES;
            _viewInAppPurchases.hidden = YES;        
            _viewAircraftSetup.hidden = NO;
            [_viewOne bringSubviewToFront:_viewAircraftSetup];
            flagFleetWasChanged = 0;
            ViewController *parent = (ViewController *)self.parentViewController;
            [parent showLoadDataFM];    
            [self performSelector: @selector (startLoadingData) withObject:nil afterDelay: 0.1f]; 
            
        }  
       
    } 
    
    if (alertFlag == 8) {
        
        if (buttonIndex == 0) {             
        }        
        if (buttonIndex == 1) { 
            flagDoNotCreateFlightNow = 1;    
            //NSLog(@"actionForceReloadAircraftData flagDoNotCreateFlightNow = 1");
            
            NSString *note = [[NSString alloc] initWithFormat:@"%f", 0.0];
            //NSLog(@"noting 2");
            [[NSNotificationCenter defaultCenter] postNotificationName: @"noteCreateFakeFlight" object: note];
            
            [self setDownloadStatus];    
            triggerSetDefaultsForPerformanceCharts = 0; 
            [self createAircraftSetupList];    
            //showAircraftSetup    
            _viewAllAvailList.hidden = YES;
            _viewInAppPurchases.hidden = YES;        
            _viewAircraftSetup.hidden = NO;
            [_viewOne bringSubviewToFront:_viewAircraftSetup];
            flagFleetWasChanged = 0;
            ViewController *parent = (ViewController *)self.parentViewController;
            [parent showLoadDataFM];    
            [self performSelector: @selector (startLoadingData) withObject:nil afterDelay: 0.1f]; 
            
        }  
        
    } 
    
    
}

- (void) checkCategories {
    
    
    //NSLog(@"checkCategories");
    
    _labelAvailableCategory.text = @"None";
    
    maxAvailableCategory = 0;
    
    maxNumberOfAircraftInFleet = 1;
    maxNumberOfAircraftCopies = 5;
    
    NSString *demoModeTest = [[NSUserDefaults standardUserDefaults]   stringForKey:@"demoMode"];
    if ([demoModeTest isEqualToString:@"demoMode"]) {
         maxNumberOfAircraftInFleet = 5;
    }
    
    NSString *availableCategory = [[NSUserDefaults standardUserDefaults]  stringForKey:@"purchasedProductID"];  
    
    //NSLog(@"checking availableCategory %@", availableCategory);
    
    NSString *availableCategoryIncreaseGroup = [[NSUserDefaults standardUserDefaults]  stringForKey:@"purchasedIncreaseID"]; 
    
    //NSLog(@"availableCategoryIncreaseGroup %@", availableCategoryIncreaseGroup);
    
    
    if ([availableCategory isEqualToString:@"GyronimoFlightPadCategory1"]) {
        _labelAvailableCategory.text = @"1";
        maxAvailableCategory = 1;
    }
    if ([availableCategory isEqualToString:@"GyronimoFlightPadCategory2"]) {
        _labelAvailableCategory.text = @"1 and 2";
        maxAvailableCategory = 2;
    }
    if ([availableCategory isEqualToString:@"GyronimoFlightPadCategory3"]) {
        _labelAvailableCategory.text = @"1,2 and 3";
        maxAvailableCategory = 3;
    }
    if ([availableCategory isEqualToString:@"GyronimoFlightPadCategory4"]) {
        _labelAvailableCategory.text = @"1,2,3 and 4";
        maxAvailableCategory = 4;
    }
    if ([availableCategory isEqualToString:@"GyronimoFlightPadCategory5"]) {
        _labelAvailableCategory.text = @"1,2,3,4 and 5";
        maxAvailableCategory = 5;
    }
    if ([availableCategory isEqualToString:@"GyronimoFlightSchoolPackHelicopter"]) {
        _labelAvailableCategory.text = @"1,2 and 3";
        maxAvailableCategory = 3;
        maxNumberOfAircraftInFleet = 10;
        maxNumberOfAircraftCopies = 40;
    }
    
    if ([availableCategory isEqualToString:@"GyronimoFlightSchoolPackFixedWing"]) {
        _labelAvailableCategory.text = @"1,2 and 3";
        maxAvailableCategory = 3;
        maxNumberOfAircraftInFleet = 10;
        maxNumberOfAircraftCopies = 40;
    }
    
    
    if ([availableCategory isEqualToString:@"GyronimoFlightSchoolPackALL"]) {
        _labelAvailableCategory.text = @"1,2 and 3";
        maxAvailableCategory = 3;
        maxNumberOfAircraftInFleet = 10;
        maxNumberOfAircraftCopies = 40;
    }
    
    
    
    if ([availableCategoryIncreaseGroup isEqualToString:@"GyronimoFleetIncrease3"]) {
        maxNumberOfAircraftInFleet = 3;
    }
    
    if ([availableCategoryIncreaseGroup isEqualToString:@"GyronimoFleetIncrease5"]) {   
        maxNumberOfAircraftInFleet = 5;
    }
    
 
   //NSLog(@"maxNumberOfAircraftInFleet %d", maxNumberOfAircraftInFleet);
   _labelMyAircraftFleet.text =  [NSString stringWithFormat:@"My Aircraft (max %d)" , maxNumberOfAircraftInFleet];
    
    
    if (maxAvailableCategory == 0) {
        _labelAvailableCategory.textColor = [UIColor yellowColor];       
    }else{
        _labelAvailableCategory.textColor = [UIColor greenColor];
       
    }
    
    NSString *maxCat = [NSString stringWithFormat:@"%d", maxAvailableCategory  ];    
    [[NSUserDefaults standardUserDefaults]   setObject: maxCat forKey:@"maxAvailableCategory"];
    
    
    //NSLog(@"maxCat = %@", maxCat);
    //NSLog(@"found maxAvailableCategory = %d", maxAvailableCategory);
    
    
}

- (void)mainRoutine {
    
    // update credits
    [self checkCategories];
    NSString *checkIfThisIsFirstFlight = [[NSUserDefaults standardUserDefaults]  stringForKey:@"checkIfThisIsFirstFlight"];    
    if ( checkIfThisIsFirstFlight.length < 1) {
        _buttonStartFlightPad.hidden = YES;       
    }else{
         _buttonStartFlightPad.hidden = NO;       
    }    
}




- (IBAction)actionLoadAircraftData:(id)sender {
    
    NSString *checkIfThisIsFirstFlight = [[NSUserDefaults standardUserDefaults]  stringForKey:@"checkIfThisIsFirstFlight"];    
    
    for(int i =0; i<arrayDictAllAircraft.count; i++) {
        
        if (![[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"ACdataSource"] isEqualToString:@"backend"] ) {
            continue;
        }
        NSString *category = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetACCategory"]; // heli/fixedWing
        NSString *manufacturer = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Manufacturer"]; //Airbus
        NSString *aircraftType = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"]; //H145
        NSString *priceCategory = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"priceCategory"]; //H145
        NSString *checkTrialforUpload = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"isATrial"];
        if ([checkTrialforUpload isEqualToString:@"isATrial"]) {               
            checkTrialforUpload = @"free"; 
        }else{
            checkTrialforUpload = @"purchased"; 
        }
        
        if (![uploadedAircraft containsObject:[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"]]) {
            [uploadedAircraft addObject:[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"]];
            NSMutableDictionary *airCraftDict = [NSMutableDictionary dictionary];
            [airCraftDict setObject:category forKey:@"fleetACCategory"];
            [airCraftDict setObject:manufacturer forKey:@"Manufacturer"];
            [airCraftDict setObject:aircraftType forKey:@"fleetAC_Type"];
            [airCraftDict setObject:priceCategory forKey:@"priceCategory"];
            [airCraftDict setObject:checkTrialforUpload forKey:@"checkTrial"]; 
           
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self uploadAirCraftData:airCraftDict];
            });
        }
        
        //upload this to backend
        //NSLog(@"Category: %@ , \nManufacturer: %@, \nAircraftType: %@, \nPriceCategory: %@",category, manufacturer, aircraftType, priceCategory);
    }
    
    
    
    if (numberOfStandardAircraftInMyFleet < 1) {
        flagReduceNumberOfAircraft = 0;
        // go direct to W&B page
        ViewController *parent = (ViewController *)self.parentViewController;    
        [parent closeFleetManagerAndOpenWBpage]; 
    }else if (flagNeedToLoadAircraft == 0 & flagFleetWasChanged == 0 || flagReduceNumberOfAircraft == 1) {   
        //NSLog(@"case 1");
        flagReduceNumberOfAircraft = 0;
        if ( checkIfThisIsFirstFlight.length < 1) {  
           //NSLog(@"case 2");
            //open aircraft setup
            _viewAllAvailList.hidden = YES;
            _viewInAppPurchases.hidden = YES;        
            _viewAircraftSetup.hidden = NO;
            [_viewOne bringSubviewToFront:_viewAircraftSetup]; 
            
        }else{
            //NSLog(@"case 3");
            // go direct to W&B page
            ViewController *parent = (ViewController *)self.parentViewController;    
            [parent closeFleetManagerAndOpenWBpage];            
        }
        
    }else{   
        //NSLog(@"case 4");
        // fleet was changed, we need to load        
        if (!([self is_online])) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Offline"
                                                                                     message:@"Your device is offline, please check internet connection."
                                                                              preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:actionOk];
            [self presentViewController:alertController animated:YES completion:nil];            
        }else{   
            //NSLog(@"case 5");
            flagDoNotCreateFlightNow = 1; 
            //NSLog(@"actionLoadAircraftData flagDoNotCreateFlightNow = 1");
            
            NSString *note = [[NSString alloc] initWithFormat:@"%f", 0.0];
            //NSLog(@"noting 1");
            [[NSNotificationCenter defaultCenter] postNotificationName: @"noteCreateFakeFlight" object: note];   
            triggerSetDefaultsForPerformanceCharts = 0; 
            [self createAircraftSetupList];    
            //showAircraftSetup    
            _viewAllAvailList.hidden = YES;
            _viewInAppPurchases.hidden = YES;        
            _viewAircraftSetup.hidden = NO;
            [_viewOne bringSubviewToFront:_viewAircraftSetup];
            flagFleetWasChanged = 0;
            ViewController *parent = (ViewController *)self.parentViewController;
            [parent showLoadDataFM];    
            [self performSelector: @selector (startLoadingData) withObject:nil afterDelay: 0.1f]; 
        }
    }
}



-(void)uploadAirCraftData:(NSMutableDictionary *)airCraftDict
{
    __block NSMutableDictionary *resultsDictionary;
        
    //NSLog(@"uploadAirCraftData");
    
    if ([NSJSONSerialization isValidJSONObject:airCraftDict]) {
        //NSLog(@"Params: %@", airCraftDict);
        NSError* error;
        NSData* jsonData = [NSJSONSerialization dataWithJSONObject:airCraftDict options:NSJSONWritingPrettyPrinted error: &error];
        NSURL* url = [NSURL URLWithString:@"https://gyronimoserver.com/api/addAircraft"];
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
        //NSLog(@"airCraftDict %@", airCraftDict);
        [request setHTTPMethod:@"POST"];//use POST
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-length"];
        [request setHTTPBody:jsonData];
        __block NSError *error1 = [[NSError alloc] init];
        
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse* response,NSData* data,NSError* error)
         {
             if ([data length] > 0 && error == nil) {
                 resultsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
                 //NSLog(@"resultsDictionary is %@",resultsDictionary);
             } else if ([data length]==0 && error ==nil) {
                //NSLog(@"download data is null");
             } else if( error!=nil) {
                 //NSLog(@"error is %@",error);
             }
         }];
    }
}



- (IBAction)actionForceReloadAircraftData:(id)sender {
    
    arrayLoadedAircraft = [[NSMutableArray alloc] init];    
    [[NSUserDefaults standardUserDefaults]  setObject:arrayLoadedAircraft  forKey:@"arrayLoadedAircraft" ];    
    [[NSUserDefaults standardUserDefaults]  setObject:arrayLoadedAircraft       forKey:@"arrayACtypesToLoad" ];
    
    
    if (!([self is_online])) {        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Offline"
                                                                                 message:@"Your device is offline, please check internet connection."
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{  
        
        alertFlag = 8;
        
        UIAlertView *alert = [[UIAlertView alloc]                              
                              initWithTitle:@"Reload Data?"                              
                              message:@"This will reload all aircraftand might take some time. Are you sure?"                              
                              delegate:self                              
                              cancelButtonTitle:@"CANCEL"                              
                              otherButtonTitles:@"RELOAD", nil];        
        [alert show];   
        
    }
    
}


- (void) startLoadingData {
    //NSLog(@"startLoadingData");
    ViewController *parent = (ViewController *)self.parentViewController;
    [parent combineACinArrayDictAllAircraft];   
    [parent startLoadingACsFromFleetControl]; 
  
    
}



- (void) setDownloadStatus {  
    
    //NSLog(@"1 arrayDictAllAircraft %@", arrayDictAllAircraft);
    for(int i =0; i<arrayDictAllAircraft.count; i++) {        
        NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
        NSDictionary *oldDict = (NSDictionary *)[arrayDictAllAircraft objectAtIndex:i];
        [newDict addEntriesFromDictionary:oldDict];        
        [newDict setObject:@"notLoaded" forKey:@"downloadStatus"]; 
        [arrayDictAllAircraft replaceObjectAtIndex:i withObject:newDict];         
    }
    
   [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft  forKey:@"arrayDictAllAircraft"];     
    [self createMyFleetList];
    
}
    










- (void) createAircraftSetupList {
    
    //NSLog(@"createAircraftSetupList");
      
    [arrayDictAllAircraft setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"]  mutableCopy]]; 
    
    //NSLog(@"arrayDictAllAircraft %@", arrayDictAllAircraft);
    
          
    for(UIView *subview in [_viewAircraftSetupList subviews]) {
        [subview removeFromSuperview];
    }
    
    [self checkCategories];
    
    float yStart = 0;
    float xPos1 = 0;
    float yGap = 290; 
    float yPos = 0;
   
    _viewAircraftSetupList.frame = CGRectMake(_scrollViewAircraftSetup.frame.origin.x + 128, _viewAircraftSetupList.frame.origin.y, _viewAircraftSetupList.frame.size.width, (arrayDictAllAircraft.count * yGap) + yGap + yGap);
    [_scrollViewAircraftSetup setContentSize:CGSizeMake(_scrollViewAircraftSetup.frame.size.width, _viewAircraftSetupList.frame.size.height)];
        
    NSMutableDictionary *ACthumbnailDictionary = [[NSMutableDictionary alloc] init];
    ACthumbnailDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"ACthumbnailDictionary"] mutableCopy];

    int lockBEWSettings = 0;   
    
    
     NSMutableArray *arrayAircraftTypes = [[NSMutableArray alloc] init];
    [arrayAircraftTypes addObject:@"Show All Aircraft"];
    [arrayAircraftTypes addObject:@"Show Helicopters Only"];
    [arrayAircraftTypes addObject:@"Show Fixed Wing Only"];
    
    
    for(int i =0; i<arrayDictAllAircraft.count; i++) { 
     
        
        //NSLog(@"arrayDictAllAircraft %@", [arrayDictAllAircraft objectAtIndex:i]);        
        NSString *downloadStatus = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"downloadStatus"];
        
         //NSLog(@"downloadStatus %@", downloadStatus); 
        
        
         if (![downloadStatus isEqualToString:@"acdownloaded"] ) { 
             continue;
         }
      
        
        if (![[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"ACdataSource"] isEqualToString:@"backend"] ) {  
            continue;
        }
        
        if ([[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Callsign"] rangeOfString:@"dummy"].location != NSNotFound || [[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Callsign"] rangeOfString:@"Dummy"].location != NSNotFound) { 
           continue;
        }
        // check number count
        
        float numberOfCount = 0;
        int flagACalreadyOnList = 0;
        int acID = i;
        
        for(int ac =0; ac<checkArrayForCounting.count; ac++) { 
            NSString *fleetACCategory2 = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"fleetACCategory"];
            NSString *textManu2 = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"Manufacturer"];
            NSString *fleetAC_Type2 = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"fleetAC_Type"];
            NSString *Version2 = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"Version"];
            NSString *priceCategory2 = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"priceCategory"];            
            NSString *checkString2 = [NSString stringWithFormat:@"%@_%@_%@_%@_%@" , fleetACCategory2, textManu2, fleetAC_Type2, Version2, priceCategory2];
            //NSLog(@"checkString2 %@", checkString2);
            //NSLog(@"checkArrayForCounting %@", checkArrayForCounting);
            if ([checkString2 isEqualToString:[checkArrayForCounting objectAtIndex:ac]]) {
                flagACalreadyOnList = 1;
                numberOfCount = numberOfCount + 1;
                //NSLog(@" add numberOfCount %.0f", numberOfCount);
            }
        }
        
        //NSLog(@"numberOfCount %.0f", numberOfCount);
        
        
        NSString *textManu = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Manufacturer"];
        NSString *textModel = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"];
        NSString *callsign = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Callsign"];
        NSString *BEW = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"BEW"];
        NSString *MomLong = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"MomLong"];
        NSString *MomLat = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"MomLat"];
        NSString *Units = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Units"];
        NSString *SelectedUnits = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"SelectedUnits"];
        NSString *priceCategory = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"priceCategory"];
        NSString *ArmLong = [NSString stringWithFormat:@"%.2f",  [MomLong floatValue] / [BEW floatValue]];
        NSString *ArmLat = [NSString stringWithFormat:@"%.2f",  [MomLat floatValue] / [BEW floatValue]];
        NSString *imageName = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"imageName"];  
        NSString *description1 = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"description1"]; 
        NSString *fleetACCategory = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetACCategory"];
        imageName  = [ imageName stringByReplacingOccurrencesOfString:@" " withString:@""];
        imageName  = [ imageName stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        
        NSString *checkTrial = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"isATrial"];
        
      
        
        if (![arrayAircraftTypes containsObject: textModel]) {
            [arrayAircraftTypes addObject:textModel];
        }
        
        _dropDownFilterAircraftOnSetup.items = arrayAircraftTypes;
        
        if (![_dropDownFilterAircraftOnSetup.text isEqualToString:@"Show All Aircraft"]) {
            
            if ([_dropDownFilterAircraftOnSetup.text isEqualToString:@"Show Helicopters Only"]) {
                if (![fleetACCategory isEqualToString:@"Heli"]) {
                     continue;
                }
            }else  if ([_dropDownFilterAircraftOnSetup.text isEqualToString:@"Show Fixed Wing Only"]) {
                    if (![fleetACCategory isEqualToString:@"FixedWing"]) {
                        continue;
                    }
            }else  if ([_dropDownFilterAircraftOnSetup.text isEqualToString:@"Show All Aircraft"]) {
                
            }else if (![textModel isEqualToString:_dropDownFilterAircraftOnSetup.text]) {
                continue;
            }
        }
        
        //NSLog(@"_dropDownFilterAircraftOnSetup %@", _dropDownFilterAircraftOnSetup.text);
        
        //NSLog(@"priceCategory %@", priceCategory);
        //NSLog(@"maxAvailableCategory %d", maxAvailableCategory);
                
        if ([priceCategory integerValue] <= maxAvailableCategory   ) { 
            lockBEWSettings = 0;            
        }else{
            lockBEWSettings = 1;
        }
        
        int loadedFromFC = 0;
        yGap = 290;
        if ([description1 isEqualToString:@"lockedFromFleetControl"]) {
             lockBEWSettings = 1;
             loadedFromFC = 1;
            yGap = 200;
        }
        
        if ([checkTrial isEqualToString:@"isATrial"]) {
            
            lockBEWSettings = 1; 
        }
        
        //NSLog(@"lockBEWSettings %d", lockBEWSettings);        
        // callsign 
        
        float xP =0, yP = 0, xW = 0, xH = 0;
        
        xP = _lImage.frame.origin.x; yP = _lImage.frame.origin.y; xW = _lImage.frame.size.width; xH = _lImage.frame.size.height;
        
        
        NSString *imageToLoad = [NSString stringWithFormat:@"thumb_%@.jpg", imageName ];         
        //NSLog(@"ACthumbnailDictionary %@", ACthumbnailDictionary);        
        if ([[ACthumbnailDictionary objectForKey: imageToLoad] isEqualToString:@"onFile"]) { 
            //NSLog(@"onFile %@", imageToLoad);
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];  
            UIImage *imageOnFile = [UIImage imageNamed:imageToLoad];                
            [imageView setImage: imageOnFile];
            [_viewAircraftSetupList addSubview: imageView];
        }else{              
            //NSLog(@" not onFile %@", imageToLoad);
            // neet to load this
            if (imageName.length > 1) {                
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];   
                NSString *imageToLoadFromData = [NSString stringWithFormat:@"thumb_%@", imageName ];
                [imageView setImage: [UIImage imageWithData:[ACthumbnailDictionary objectForKey: imageToLoadFromData]]];
                [_viewAircraftSetupList addSubview: imageView];
            }else{
                // use standard image
                UIImage *exampleIAPImage = [UIImage imageNamed:@"BlueBoxNoImage.png"];
                 UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];  
                [imageView setImage: exampleIAPImage];
                [_viewAircraftSetupList addSubview: imageView]; 
            }
        }
        
        
        
        
        xP = _lcallsign.frame.origin.x; yP = _lcallsign.frame.origin.y; xW = _lcallsign.frame.size.width; xH = _lcallsign.frame.size.height;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor lightGrayColor];    
        [label  setText: @"Callsign"];
        [_viewAircraftSetupList addSubview: label];        
        
        xP = _tfCallsign.frame.origin.x; yP = _tfCallsign.frame.origin.y; xW = _tfCallsign.frame.size.width; xH = _tfCallsign.frame.size.height;
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont boldSystemFontOfSize:16];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.textAlignment = NSTextAlignmentCenter;
        
        if (lockBEWSettings == 1) {
            textField.enabled = NO;
            textField.backgroundColor = [UIColor darkGrayColor];
            textField.textColor = [UIColor whiteColor];
        }else{         
            textField.enabled = YES;
            textField.backgroundColor = [UIColor whiteColor];
            textField.textColor = [UIColor blackColor];
        }
        
        
        
        [textField addTarget:self
                      action:@selector(textfieldAction:)
            forControlEvents:UIControlEventEditingDidEndOnExit];     
        [textField addTarget:self
                      action:@selector(textfieldActionUpdate:)
            forControlEvents:UIControlEventEditingDidEnd]; 
        [textField  setText: [[NSString alloc] initWithFormat:@"%@", callsign ] ];  
        textField.tag = i+1000;
        [_viewAircraftSetupList addSubview:textField];  
        
        xP = _lManufact.frame.origin.x; yP = _lManufact.frame.origin.y; xW = _lManufact.frame.size.width; xH = _lManufact.frame.size.height;
        // manufacturer         
        label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor lightGrayColor];
        [label  setText: @"Manufacturer, Type"];
        [_viewAircraftSetupList addSubview: label];        
        
        xP = _tfManufact.frame.origin.x; yP = _tfManufact.frame.origin.y; xW = _tfManufact.frame.size.width; xH = _tfManufact.frame.size.height;
        label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        label.font = [UIFont boldSystemFontOfSize:16];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor whiteColor];
        [label  setText:  [[NSString alloc] initWithFormat:@"%@, %@", textManu, textModel ] ];  
        [_viewAircraftSetupList addSubview: label];  
        
        if (loadedFromFC == 1) {
            NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"]; 
            if (![customerFolderName isEqualToString:@"noAccount"]) {
                xP = _tfManufact.frame.origin.x; yP = _tfManufact.frame.origin.y; xW = _tfManufact.frame.size.width; xH = _tfManufact.frame.size.height;
                label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP + 25, xW, xH )];
                label.font = [UIFont boldSystemFontOfSize:16];
                label.textAlignment = NSTextAlignmentLeft;
                label.textColor = [UIColor yellowColor];
                [label  setText:  customerFolderName ];  
                [_viewAircraftSetupList addSubview: label]; 
            }
        }
          
        
        if (loadedFromFC == 0) {
            // original units  
            xP = _lOrigUNits.frame.origin.x; yP = _lOrigUNits.frame.origin.y; xW = _lOrigUNits.frame.size.width; xH = _lOrigUNits.frame.size.height;
            label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1 + xP, yStart + yPos + yP, xW, xH )];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];
            [label  setText: @"Original Units"];
            [_viewAircraftSetupList addSubview: label];        
            
            xP = _tfOrigun.frame.origin.x; yP = _tfOrigun.frame.origin.y; xW = _tfOrigun.frame.size.width; xH = _tfOrigun.frame.size.height;
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
            label.font = [UIFont boldSystemFontOfSize:16];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor lightGrayColor];;
            [label  setText:  [[NSString alloc] initWithFormat:@"%@", Units ] ];  
            [_viewAircraftSetupList addSubview: label]; 
            
            //units
            xP = _lUnits.frame.origin.x; yP = _lUnits.frame.origin.y; xW = _lUnits.frame.size.width; xH = _lUnits.frame.size.height;
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor lightGrayColor];
            [label  setText: @"Units"];
            [_viewAircraftSetupList addSubview: label];  
            
            xP = _segmentOrigUnits.frame.origin.x; yP = _segmentOrigUnits.frame.origin.y; xW = _segmentOrigUnits.frame.size.width; xH = _segmentOrigUnits.frame.size.height;
            NSArray *itemArray = [NSArray arrayWithObjects: @"kg"   , @"lbs" ,  nil];
            UISegmentedControl *segmentUnit = [[UISegmentedControl alloc] initWithItems:itemArray];
            segmentUnit.frame = CGRectMake(xPos1 + xP, yStart + yPos + yP, xW, xH );
            [segmentUnit addTarget:self action:@selector(segmentAction:) forControlEvents: UIControlEventValueChanged];
            segmentUnit.tag = i + 7000;  
            segmentUnit.tintColor = [UIColor darkGrayColor];
            segmentUnit.backgroundColor = [UIColor lightGrayColor]; 
            //NSLog(@"doing");
            
            if ([SelectedUnits isEqualToString:@"kg"]) {
                segmentUnit.selectedSegmentIndex = 0;
            }else{
                segmentUnit.selectedSegmentIndex = 1;
            }        
            [_viewAircraftSetupList addSubview: segmentUnit];  
        }
            
        
               
        
        //BEW
        xP = _lBew.frame.origin.x; yP = _lBew.frame.origin.y; xW = _lBew.frame.size.width; xH = _lBew.frame.size.height;
        label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor lightGrayColor];
        [label  setText: @"BEW"];
        [_viewAircraftSetupList addSubview: label];          
        
        xP = _tfBEW.frame.origin.x; yP = _tfBEW.frame.origin.y; xW = _tfBEW.frame.size.width; xH = _tfBEW.frame.size.height;
        textField = [[UITextField alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:14];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.textAlignment = NSTextAlignmentCenter;
        
        if (lockBEWSettings == 1) {
            textField.enabled = NO;
            textField.backgroundColor = [UIColor darkGrayColor];
        }else{
            textField.enabled = YES;
            textField.backgroundColor = [UIColor whiteColor];
        }
            
       
        textField.textColor = [UIColor blackColor];
        [textField addTarget:self
                      action:@selector(textfieldAction:)
            forControlEvents:UIControlEventEditingDidEndOnExit];  
        [textField addTarget:self
                      action:@selector(textfieldActionUpdate:)
            forControlEvents:UIControlEventEditingDidEnd];
        [textField  setText: [[NSString alloc] initWithFormat:@"%@", BEW ] ];  
        textField.tag = i+2000;
        [_viewAircraftSetupList addSubview:textField]; 
        
       
        
                
        //longitudinal
         xP = _lLongitu.frame.origin.x; yP = _lLongitu.frame.origin.y; xW = _lLongitu.frame.size.width; xH = _lLongitu.frame.size.height;
        label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor lightGrayColor];
        [label  setText: @"Longitudinal"];
        [_viewAircraftSetupList addSubview: label];
        
        //lateral
        xP = _lLateral.frame.origin.x; yP = _lLateral.frame.origin.y; xW = _lLateral.frame.size.width; xH = _lLateral.frame.size.height;
        label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor lightGrayColor];
        [label  setText: @"Lateral"];
        [_viewAircraftSetupList addSubview: label];
                
        //ARM
        xP = _lArm.frame.origin.x; yP = _lArm.frame.origin.y; xW = _lArm.frame.size.width; xH = _lArm.frame.size.height;
        label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor lightGrayColor];
        [label  setText: @"Arm"];
        [_viewAircraftSetupList addSubview: label];
        
         xP = _tfArm.frame.origin.x; yP = _tfArm.frame.origin.y; xW = _tfArm.frame.size.width; xH = _tfArm.frame.size.height;
        textField = [[UITextField alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:14];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.textAlignment = NSTextAlignmentCenter;
        if (lockBEWSettings == 1) {
            textField.enabled = NO;
            textField.backgroundColor = [UIColor darkGrayColor];
        }else{
            textField.enabled = YES;
            textField.backgroundColor = [UIColor whiteColor];
        }
        textField.textColor = [UIColor blackColor];
        [textField addTarget:self
                      action:@selector(textfieldAction:)
            forControlEvents:UIControlEventEditingDidEndOnExit];
        [textField addTarget:self
                      action:@selector(textfieldActionUpdate:)
            forControlEvents:UIControlEventEditingDidEnd];        
        [textField  setText: [[NSString alloc] initWithFormat:@"%@", ArmLong ] ];  
        textField.tag = i+3000;
        [_viewAircraftSetupList addSubview:textField]; 
        
        //Moment Long
        xP = _lMoment.frame.origin.x; yP = _lMoment.frame.origin.y; xW = _lMoment.frame.size.width; xH = _lMoment.frame.size.height;
        label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor lightGrayColor];
        [label  setText: @"Moment"];
        [_viewAircraftSetupList addSubview: label];
        
        xP = _tfMometn.frame.origin.x; yP = _tfMometn.frame.origin.y; xW = _tfMometn.frame.size.width; xH = _tfMometn.frame.size.height;
        textField = [[UITextField alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:14];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.textAlignment = NSTextAlignmentCenter;
        if (lockBEWSettings == 1) {
            textField.enabled = NO;
            textField.backgroundColor = [UIColor darkGrayColor];
        }else{
            textField.enabled = YES;
            textField.backgroundColor = [UIColor whiteColor];
        }
        textField.textColor = [UIColor blackColor];
        [textField addTarget:self
                      action:@selector(textfieldAction:)
            forControlEvents:UIControlEventEditingDidEndOnExit];
        [textField addTarget:self
                      action:@selector(textfieldActionUpdate:)
            forControlEvents:UIControlEventEditingDidEnd];        
        [textField  setText: [[NSString alloc] initWithFormat:@"%@", MomLong ] ];  
        textField.tag = i+4000;
        [_viewAircraftSetupList addSubview:textField]; 
        
     
       
      
        
        //ARM LAT
        xP = _lArmlat.frame.origin.x; yP = _lArmlat.frame.origin.y; xW = _lArmlat.frame.size.width; xH = _lArmlat.frame.size.height;
        label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor lightGrayColor];
        [label  setText: @"Arm"];
        [_viewAircraftSetupList addSubview: label];
        
        xP = _tfArmLat.frame.origin.x; yP = _tfArmLat.frame.origin.y; xW = _tfArmLat.frame.size.width; xH = _tfArmLat.frame.size.height;
        textField = [[UITextField alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:14];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.textAlignment = NSTextAlignmentCenter;
        if (lockBEWSettings == 1) {
            textField.enabled = NO;
            textField.backgroundColor = [UIColor darkGrayColor];
        }else{
            textField.enabled = YES;
            textField.backgroundColor = [UIColor whiteColor];
        }
        textField.textColor = [UIColor blackColor];
        [textField addTarget:self
                      action:@selector(textfieldAction:)
            forControlEvents:UIControlEventEditingDidEndOnExit];  
        [textField addTarget:self
                      action:@selector(textfieldActionUpdate:)
            forControlEvents:UIControlEventEditingDidEnd];
        [textField  setText: [[NSString alloc] initWithFormat:@"%@", ArmLat ] ];  
        textField.tag = i+5000;
        [_viewAircraftSetupList addSubview:textField]; 
        
        
        //Moment Lat
        xP = _lMomLat.frame.origin.x; yP = _lMomLat.frame.origin.y; xW = _lMomLat.frame.size.width; xH = _lMomLat.frame.size.height;
        label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor lightGrayColor];
        [label  setText: @"Moment"];
        [_viewAircraftSetupList addSubview: label];
        
        xP = _tfMomlat.frame.origin.x; yP = _tfMomlat.frame.origin.y; xW = _tfMomlat.frame.size.width; xH = _tfMomlat.frame.size.height;
        textField = [[UITextField alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:14];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.textAlignment = NSTextAlignmentCenter;
        if (lockBEWSettings == 1) {
            textField.enabled = NO;
            textField.backgroundColor = [UIColor darkGrayColor];
        }else{
            textField.enabled = YES;
            textField.backgroundColor = [UIColor whiteColor];
        }
        textField.textColor = [UIColor blackColor];
        [textField addTarget:self
                      action:@selector(textfieldAction:)
            forControlEvents:UIControlEventEditingDidEndOnExit]; 
        [textField addTarget:self
                      action:@selector(textfieldActionUpdate:)
            forControlEvents:UIControlEventEditingDidEnd];
        [textField  setText: [[NSString alloc] initWithFormat:@"%@", MomLat ] ];  
        textField.tag = i+6000;
        [_viewAircraftSetupList addSubview:textField]; 
        
        // warning text
        if (lockBEWSettings == 1 & loadedFromFC == 0) {
            
            xP = _lPurchaseAberDalli.frame.origin.x; yP = _lPurchaseAberDalli.frame.origin.y; xW = _lPurchaseAberDalli.frame.size.width; xH = _lPurchaseAberDalli.frame.size.height;
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = yellowSpecialColor;
            [label  setText:  @"Not for Flight Planning! Please upgrade your available categories to edit aircraft data and registration"];  
            [_viewAircraftSetupList addSubview: label];  
            
            xP = _butUpgrade.frame.origin.x; yP = _butUpgrade.frame.origin.y; xW = _butUpgrade.frame.size.width; xH = _butUpgrade.frame.size.height;
            UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            aButton.frame     = CGRectMake(xPos1 + xP, yStart + yPos + yP, xW, xH );
            [aButton setTitle:@"Purchase Categories" forState:(UIControlStateNormal)];
            UIImage *buttonBack = [UIImage imageNamed:@"button generic yellow"];
            [aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];
            aButton.tintColor = [UIColor whiteColor];
            aButton.showsTouchWhenHighlighted = YES;
            //aButton.titleLabel.font = [UIFont systemFontOfSize:13];
            [aButton setTag:8000 + i];
            [aButton addTarget:self action:@selector(actionViewInAppPurchases:) forControlEvents:UIControlEventTouchUpInside];
            [_viewAircraftSetupList addSubview:aButton];
            
        }
        
        
        
        
        if (loadedFromFC == 0) {
            
            xP = _butCreateAFLight.frame.origin.x; yP = _butCreateAFLight.frame.origin.y; xW = _butCreateAFLight.frame.size.width; xH = _butCreateAFLight.frame.size.height;
            UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            aButton.frame     = CGRectMake(xPos1 + xP, yStart + yPos + yP, xW, xH );
            [aButton setTitle:@"Create A Flight With This Aircraft" forState:(UIControlStateNormal)];
            UIImage *buttonBack = [UIImage imageNamed:@"button generic dark"];
            if (lockBEWSettings == 0) {
                buttonBack = [UIImage imageNamed:@"button generic green"];                
            }
            [aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];
            aButton.tintColor = [UIColor whiteColor];
            aButton.showsTouchWhenHighlighted = YES;
            //aButton.titleLabel.font = [UIFont systemFontOfSize:13];
            [aButton setTag:8000 + i];
            [aButton addTarget:self action:@selector(actionStartFlightWithAircraft:) forControlEvents:UIControlEventTouchUpInside];
            [_viewAircraftSetupList addSubview:aButton]; 
            
            
            
            if (lockBEWSettings == 0) {
                xP = _butCopy.frame.origin.x; yP = _butCopy.frame.origin.y; xW = _butCopy.frame.size.width; xH = _butCopy.frame.size.height;
                aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                aButton.frame     = CGRectMake(xPos1 + xP, yStart + yPos + yP, xW, xH );
                [aButton setTitle:@"Copy" forState:(UIControlStateNormal)];
                buttonBack = [UIImage imageNamed:@"button generic blue"];
                [aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];
                aButton.tintColor = [UIColor whiteColor];
                aButton.showsTouchWhenHighlighted = YES;
                //aButton.titleLabel.font = [UIFont systemFontOfSize:13];
                [aButton setTag:9000 + i];
                [aButton addTarget:self action:@selector(actionCopyAircraft:) forControlEvents:UIControlEventTouchUpInside];
                [_viewAircraftSetupList addSubview:aButton]; 
                
                
                xP = _lEnterUnitsAberRichtig.frame.origin.x; yP = _lEnterUnitsAberRichtig.frame.origin.y; xW = _lEnterUnitsAberRichtig.frame.size.width; xH = _lEnterUnitsAberRichtig.frame.size.height;
                label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH )];
                label.font = [UIFont boldSystemFontOfSize:14];
                label.textAlignment = NSTextAlignmentLeft;
                label.textColor = [UIColor lightGrayColor];
                
                
                if ([SelectedUnits isEqualToString:@"kg"]) {
                    [label  setText:  @"Enter Arms in Millimeter and Moments in Kilogram.Millimeter"];  
                }else{
                    [label  setText:  @"Enter Arms in inches and Moments in lbs.inches"];  
                }                
                
                [_viewAircraftSetupList addSubview: label]; 
                
                
            }
            
   
            
            if (numberOfCount > 2) {
                xP = _butDelete.frame.origin.x; yP = _butDelete.frame.origin.y; xW = _butDelete.frame.size.width; xH = _butDelete.frame.size.height;
                aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                aButton.frame     = CGRectMake(xPos1 + xP, yStart + yPos + yP, xW, xH );
                [aButton setTitle:@"Delete" forState:(UIControlStateNormal)];
                buttonBack = [UIImage imageNamed:@"button generic blue"];
                [aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];
                aButton.tintColor = [UIColor whiteColor];
                aButton.showsTouchWhenHighlighted = YES;
                //aButton.titleLabel.font = [UIFont systemFontOfSize:13];
                [aButton setTag:10000 + i];
                [aButton addTarget:self action:@selector(actionDeleteAircraft:) forControlEvents:UIControlEventTouchUpInside];
                [_viewAircraftSetupList addSubview:aButton]; 
            }
            
           
            
        }else{
            xP = _butCreateAFLight.frame.origin.x; yP = _butCreateAFLight.frame.origin.y; xW = _butCreateAFLight.frame.size.width; xH = _butCreateAFLight.frame.size.height;
            UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            aButton.frame     = CGRectMake(xPos1 + xP, yStart + yPos + yP - 180, xW, xH );
            [aButton setTitle:@"Create A Flight With This Aircraft" forState:(UIControlStateNormal)];
            UIImage *buttonBack = [UIImage imageNamed:@"button generic blue"];
            [aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];
            aButton.tintColor = [UIColor whiteColor];
            aButton.showsTouchWhenHighlighted = YES;
            //aButton.titleLabel.font = [UIFont systemFontOfSize:13];
            [aButton setTag:8000 + i];
            [aButton addTarget:self action:@selector(actionStartFlightWithAircraft:) forControlEvents:UIControlEventTouchUpInside];
            [_viewAircraftSetupList addSubview:aButton]; 
            
        }
        
        
        
        
         xP = _lLineView.frame.origin.x; yP = _lLineView.frame.origin.y; xW = _lLineView.frame.size.width; xH = _lLineView.frame.size.height;
        UIView *lineView;
        
        if (loadedFromFC == 0) {
             lineView = [[UIView alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP, xW, xH)];
        }else{
             lineView = [[UIView alloc] initWithFrame:CGRectMake( xPos1 + xP, yStart + yPos + yP-90, xW, xH)];    
            
        }
      
        
        
        lineView.backgroundColor = [UIColor lightGrayColor];
        [_viewAircraftSetupList addSubview:lineView]; 
        
        yPos = yPos +  yGap;      
        
    }   
    
     [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft  forKey:@"arrayDictAllAircraft"];
    
   
    [_scrollViewAircraftSetup setContentOffset:CGPointZero animated:YES];
    
  
   
    
}

- (IBAction)dropDown1DidEndOnExit:(id)sender{
    
  
    [self createAircraftSetupList];
    
}

- (IBAction)dropDown2DidEndOnExit:(id)sender{
   
  
    [self createAllAvailableAircraftList];
    
}

- (IBAction)actionStartFlightWithAircraft:(id)sender{
    
    UIButton *btn = (UIButton*)sender;
    float i = btn.tag - 8000;
          
    //NSLog(@"actionStartFlightWithAircraft");   
    
    [[NSUserDefaults standardUserDefaults]  setObject:@"aaaaaaaa"  forKey:@"checkIfThisIsFirstFlight"];    
    ViewController *parent = (ViewController *)self.parentViewController;
          
    if ([parent.self.labelFlightID.text floatValue] < 1) {        
        flagTriggerSpecialCreateFlight = 1;
    } 
    NSString *fleetAC_Type = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"];  
   
    //NSLog(@"fleetAC_Type: %@", fleetAC_Type);
    [[NSUserDefaults standardUserDefaults]  setObject:fleetAC_Type  forKey:@"AC_Type"]; 
   
    NSString *note = [[NSString alloc] initWithFormat:@"%f", i];
    //NSLog(@"sending noteNewCreateFlight note: %@", note);
    [[NSUserDefaults standardUserDefaults]  setObject:note  forKey:@"note1"];  
    
    [parent remoteControlCreateNewFlight];
    //[[NSNotificationCenter defaultCenter] postNotificationName: @"noteNewCreateFlight" object: note];
    
   
   
    
}

- (IBAction)actionDeleteAircraft:(id)sender{
       
   
    UIButton *btn = (UIButton*)sender;
    float i = btn.tag - 10000;
   
    [arrayDictAllAircraft removeObjectAtIndex:i];    
    [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft  forKey:@"arrayDictAllAircraft"]; 
    [self createAircraftSetupList];
    [self createMyFleetList];
    
    
    // Save scrollviewPosition   
    [[NSUserDefaults standardUserDefaults] setObject:NSStringFromCGPoint(_scrollViewAircraftSetup.contentOffset) forKey:@"scrollViewOffset"];
    // Restore   
    CGPoint offset = CGPointFromString([[NSUserDefaults standardUserDefaults] objectForKey:@"scrollViewOffset"]);
    [_scrollViewAircraftSetup setContentOffset:offset animated:NO];
    
    
}

- (IBAction)actionCopyAircraft:(id)sender{
    
    UIButton *btn = (UIButton*)sender;
    
    // check number of copies    
    float acID = btn.tag - 9000; 
    float numberOfCount = 0;
  
    NSString *textManu = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"Manufacturer"];   
    NSString *priceCategory = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"priceCategory"];  
    NSString *fleetAC_Type = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"fleetAC_Type"];  
    NSString *fleetACCategory = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"fleetACCategory"];  
    NSString *Version = [[arrayDictAllAircraft objectAtIndex:acID] objectForKey:@"Version"]; 
    NSString *checkString = [NSString stringWithFormat:@"%@_%@_%@_%@_%@" , fleetACCategory, textManu, fleetAC_Type, Version, priceCategory];
  
    
    for(int ac =0; ac<arrayDictAllAircraft.count; ac++) { 
        NSString *fleetACCategory2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"fleetACCategory"];
        NSString *textManu2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"Manufacturer"];
        NSString *fleetAC_Type2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"fleetAC_Type"];
        NSString *Version2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"Version"];
        NSString *priceCategory2 = [[arrayDictAllAircraft objectAtIndex:ac] objectForKey:@"priceCategory"];            
        NSString *checkString2 = [NSString stringWithFormat:@"%@_%@_%@_%@_%@" , fleetACCategory2, textManu2, fleetAC_Type2, Version2, priceCategory2];
        //NSLog(@"checkString2 %@", checkString2);
        if ([checkString2 isEqualToString:checkString]) {           
            numberOfCount = numberOfCount + 1;
            
        }
    }
    //NSLog(@"numberOfCount %.0f", numberOfCount);
    
    if (numberOfCount >= maxNumberOfAircraftCopies) {
        NSString *messageString = [ [NSString alloc] initWithFormat:@"Max number of aircraft copies is %d. If you have a larger fleet or operate a flight school, please contact us via email: info@gyronimo.com.", maxNumberOfAircraftCopies];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Max Aircraft Copies"
                                                                                 message:messageString
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil]; 
        return;
    }else{
        float i = btn.tag - 9000;
        
        NSMutableDictionary *myACsDictionary = [[NSMutableDictionary alloc] init];
        myACsDictionary[@"Callsign"]        =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Callsign"];
        myACsDictionary[@"fleetACCategory"]          =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetACCategory"];  // HEli 
        myACsDictionary[@"Manufacturer"]    =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Manufacturer"]; //Airbus 
        myACsDictionary[@"fleetAC_Type"]           =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"]; //H145
        myACsDictionary[@"Variant"]         =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Variant"];  
        myACsDictionary[@"Units"]         =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Units"];
        myACsDictionary[@"BEW"]         =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"BEW"];
        myACsDictionary[@"MomLong"]         =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"MomLong"];
        myACsDictionary[@"MomLat"]         =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"MomLat"];
        myACsDictionary[@"SelectedUnits"]         =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"SelectedUnits"];
        myACsDictionary[@"priceCategory"]         =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"priceCategory"];
        myACsDictionary[@"downloadStatus"]         =  @"acdownloaded";
        myACsDictionary[@"Version"]         =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Version"];
        myACsDictionary[@"imageName"]         =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"imageName"];
        myACsDictionary[@"backendID"]         =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"backendID"];
        myACsDictionary[@"description1"]         =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"description1"];
        myACsDictionary[@"description2"]         =  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"description2"];
        myACsDictionary[@"ACdataSource"]         =  @"backend";
        
        [arrayDictAllAircraft addObject:myACsDictionary]; 
        
        [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft  forKey:@"arrayDictAllAircraft"]; 
        [self createAircraftSetupList];
        [self createMyFleetList];
        
        //NSLog(@"1saving units = %@",  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Units"]);
        //NSLog(@"2saving units = %@",  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"SelectedUnits"]);
        
    }
    
        
    // Save scrollviewPosition   
    [[NSUserDefaults standardUserDefaults] setObject:NSStringFromCGPoint(_scrollViewAircraftSetup.contentOffset) forKey:@"scrollViewOffset"];
    // Restore   
    CGPoint offset = CGPointFromString([[NSUserDefaults standardUserDefaults] objectForKey:@"scrollViewOffset"]);
    [_scrollViewAircraftSetup setContentOffset:offset animated:NO];
   
    
    
    
    
}


- (void)textfieldActionUpdate :(UITextField *)textFieldID{
   
    
    float fieldTag = textFieldID.tag; 
    int itemTag = 0; 
    
    triggerUseArmLong = 0; triggerUseArmLat = 0;
    
    if (fieldTag >=1000 & fieldTag<=2000) {
        itemTag = fieldTag - 1000;
    }
    
    if (fieldTag >=2000 & fieldTag <3000) {
        itemTag = fieldTag - 2000; ;
    }
    if (fieldTag >=3000 & fieldTag <4000) {
        itemTag = fieldTag - 3000; triggerUseArmLong = 1;
    }
    if (fieldTag >=4000 & fieldTag <5000) {
        itemTag = fieldTag - 4000; 
    }
    if (fieldTag >=5000 & fieldTag <6000) {
        itemTag = fieldTag - 5000; triggerUseArmLat = 1;
    }
    if (fieldTag >=6000 & fieldTag <7000) {
        itemTag = fieldTag - 6000;
    }
    if (fieldTag >=7000 & fieldTag <8000) {
        itemTag = fieldTag - 7000;
    }
    
    [self overwriteMyFleet:itemTag]; 
    
}



- (void)textfieldAction :(UITextField *)textFieldID{
    
     [self.view endEditing:TRUE];  
    
     float fieldTag = textFieldID.tag; 
     int itemTag = 0; 
    
    triggerUseArmLong = 0; triggerUseArmLat = 0;
    
    if (fieldTag >=1000 & fieldTag<=2000) {
        itemTag = fieldTag - 1000;
    }
    
    if (fieldTag >=2000 & fieldTag <3000) {
        itemTag = fieldTag - 2000; ;
    }
    if (fieldTag >=3000 & fieldTag <4000) {
        itemTag = fieldTag - 3000; triggerUseArmLong = 1;
    }
    if (fieldTag >=4000 & fieldTag <5000) {
        itemTag = fieldTag - 4000; 
    }
    if (fieldTag >=5000 & fieldTag <6000) {
        itemTag = fieldTag - 5000; triggerUseArmLat = 1;
    }
    if (fieldTag >=6000 & fieldTag <7000) {
        itemTag = fieldTag - 6000;
    }
    if (fieldTag >=7000 & fieldTag <8000) {
        itemTag = fieldTag - 7000;
    }
    
     
    [self overwriteMyFleet:itemTag]; 
    
    
    
    
     
}

- (void) overwriteMyFleet :(int)itemTag {
    
    //NSLog(@"overwriteMyFleet");
    
    UITextField *textField = [[UITextField alloc] init];
    //convert dictionary to change data within
    NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
    NSDictionary *oldDict = (NSDictionary *)[arrayDictAllAircraft objectAtIndex:itemTag];
    [newDict addEntriesFromDictionary:oldDict]; 
    
    NSString *replacementText = @"";    
    
    replacementText = [textField = (UITextField *)[ _viewAircraftSetupList viewWithTag: itemTag + 1000  ]text];
    [newDict setObject:replacementText forKey:@"Callsign"];
    replacementText = [textField = (UITextField *)[ _viewAircraftSetupList viewWithTag: itemTag + 2000  ]text];
    [newDict setObject:replacementText forKey:@"BEW"];
    
    //NSLog(@"replacementText %@", replacementText);
    
    if (triggerUseArmLong == 1) {
        NSString *bew = [textField = (UITextField *)[ _viewAircraftSetupList viewWithTag: itemTag + 2000  ]text];
        NSString *arm = [textField = (UITextField *)[ _viewAircraftSetupList viewWithTag: itemTag + 3000  ]text];
        replacementText = [[NSString alloc] initWithFormat:@"%.1f", [bew floatValue] * [arm floatValue]];  
    }else{
        replacementText = [textField = (UITextField *)[ _viewAircraftSetupList viewWithTag: itemTag + 4000  ]text];           
    }
    [newDict setObject:replacementText forKey:@"MomLong"];  
    
    
    if (triggerUseArmLat == 1) {
        NSString *bew = [textField = (UITextField *)[ _viewAircraftSetupList viewWithTag: itemTag + 2000  ]text];
        NSString *armLat = [textField = (UITextField *)[ _viewAircraftSetupList viewWithTag: itemTag + 5000  ]text];
        replacementText = [[NSString alloc] initWithFormat:@"%.1f", [bew floatValue] * [armLat floatValue]];  
    }else{
        replacementText = [textField = (UITextField *)[ _viewAircraftSetupList viewWithTag: itemTag + 6000  ]text];           
    }
    [newDict setObject:replacementText forKey:@"MomLat"];     
   
    [arrayDictAllAircraft replaceObjectAtIndex:itemTag withObject:newDict]; 
    [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft  forKey:@"arrayDictAllAircraft"];  

    [self createAircraftSetupList];  
    
    [self updateACData];
    
    // Save scrollviewPosition   
    [[NSUserDefaults standardUserDefaults] setObject:NSStringFromCGPoint(_scrollViewAircraftSetup.contentOffset) forKey:@"scrollViewOffset"];
    // Restore   
    CGPoint offset = CGPointFromString([[NSUserDefaults standardUserDefaults] objectForKey:@"scrollViewOffset"]);
    [_scrollViewAircraftSetup setContentOffset:offset animated:NO];
    
    
}


- (void) updateACData {
    
    //NSLog(@"updateACData");
    
    ViewController *parent = (ViewController *)self.parentViewController;
    [parent combineACinArrayDictAllAircraft];  
    [parent addHelicopterButtonsMyFleet]; 
    
}

- (void)segmentAction :(UISegmentedControl *)segment{
        
    float segTag = segment.tag - 7000;    
   
    
    NSString *previousSelectedUnits = [[arrayDictAllAircraft objectAtIndex:segTag] objectForKey:@"SelectedUnits"];
    //NSLog(@"previousSelectedUnits %@", previousSelectedUnits);
    
    NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
    NSDictionary *oldDict = (NSDictionary *)[arrayDictAllAircraft objectAtIndex:segTag];
    [newDict addEntriesFromDictionary:oldDict];     
    
    NSString *selectedUNit;
    if (segment.selectedSegmentIndex == 1) {
        [newDict setObject:@"lbs" forKey:@"SelectedUnits"]; 
        selectedUNit = @"lbs";
    }else{
        [newDict setObject:@"kg" forKey:@"SelectedUnits"];
        selectedUNit = @"kg";
    }    
    
    [arrayDictAllAircraft replaceObjectAtIndex:segTag withObject:newDict];
    // check if original units are same, if not then convert!
    //NSString *originalUnits = [[arrayDictAllAircraft objectAtIndex:segTag] objectForKey:@"Units"];    
    //NSLog(@"selectedUNit %@", selectedUNit);
    
    conversionFactorWeight = 1.0;
    conversionFactorMoment = 1.0;
    
    //sdf
    
    if ([previousSelectedUnits isEqualToString:@"kg"] && [selectedUNit isEqualToString:@"lbs"]) {        
        conversionFactorWeight = 2.2046;
        conversionFactorMoment = 0.086795276;
        
        ViewController *parent = (ViewController *)self.parentViewController; 
        if ( [[parent.arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
             //NSLog(@"this is meter!");
            conversionFactorMoment = conversionFactorMoment * 1000;
        }
        
    }
    
    if ([previousSelectedUnits isEqualToString:@"lbs"] && [selectedUNit isEqualToString:@"kg"]) {        
        conversionFactorWeight = 1/2.2046;
        conversionFactorMoment = 1/0.086795276;
        
        ViewController *parent = (ViewController *)self.parentViewController; 
        if ( [[parent.arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
             //NSLog(@"this is meter!");
            conversionFactorMoment = conversionFactorMoment / 1000;
        }
        
    }    
    //NSLog(@"conversionFactorWeight %f", conversionFactorWeight);
    
         
    
     
    
    
    [self convertMyFleet:segTag];   
    [self createAircraftSetupList]; 
    [self.view endEditing:TRUE]; 
    // Save scrollviewPosition   
    [[NSUserDefaults standardUserDefaults] setObject:NSStringFromCGPoint(_scrollViewAircraftSetup.contentOffset) forKey:@"scrollViewOffset"];
    // Restore   
    CGPoint offset = CGPointFromString([[NSUserDefaults standardUserDefaults] objectForKey:@"scrollViewOffset"]);
    [_scrollViewAircraftSetup setContentOffset:offset animated:NO];
    
}


- (void) convertMyFleet: (int)segTag {
    
    UITextField *textField = [[UITextField alloc] init];
    //convert dictionary to change data within
    NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
    NSDictionary *oldDict = (NSDictionary *)[arrayDictAllAircraft objectAtIndex:segTag];
    [newDict addEntriesFromDictionary:oldDict]; 
    
    NSString *replacementText = [textField = (UITextField *)[ _viewAircraftSetupList viewWithTag: segTag + 1000  ]text];
    [newDict setObject:replacementText forKey:@"Callsign"];
    
    replacementText = [textField = (UITextField *)[ _viewAircraftSetupList viewWithTag: segTag + 2000  ]text];
    //[newDict setObject:replacementText forKey:@"BEW"];
    
    NSString *conversionResult =  [[NSString alloc] initWithFormat:@"%.1f", [replacementText floatValue] * conversionFactorWeight];        
    [newDict setObject:conversionResult forKey:@"BEW"];
    
    replacementText = [textField = (UITextField *)[ _viewAircraftSetupList viewWithTag: segTag + 4000  ]text];
    //[newDict setObject:replacementText forKey:@"MomLong"];
    
    conversionResult =  [[NSString alloc] initWithFormat:@"%.1f", [replacementText floatValue] * conversionFactorMoment];        
    [newDict setObject:conversionResult forKey:@"MomLong"];    
    
    replacementText = [textField = (UITextField *)[ _viewAircraftSetupList viewWithTag: segTag + 6000  ]text];
    //[newDict setObject:replacementText forKey:@"MomLat"];
    conversionResult =  [[NSString alloc] initWithFormat:@"%.1f", [replacementText floatValue] * conversionFactorMoment];        
    [newDict setObject:conversionResult forKey:@"MomLat"];        
    
    [arrayDictAllAircraft replaceObjectAtIndex:segTag withObject:newDict];   
     
    [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft  forKey:@"arrayDictAllAircraft"];  
    
}



- (IBAction)actionStartFlightPad:(id)sender {
    
    
    ViewController *parent = (ViewController *)self.parentViewController;    
    [parent closeFleetManagerAndOpenWBpage]; 
    
    
}


- (IBAction)actionViewAllAvailList:(id)sender {
    
    //NSLog(@"actionViewAllAvailList");
    
    if (arrayDictAllAircraft.count < 1) {
        _viewAllAvailList.hidden = NO;
        [_viewOne bringSubviewToFront:_viewAllAvailList];
        [self createAircraftSetupList];
        return;
    }
    
  
    
    _viewInAppPurchases.hidden = YES;
    _viewAircraftSetup.hidden = YES;
    
    _viewAllAvailList.hidden = NO;
    [_viewOne bringSubviewToFront:_viewAllAvailList];
   
    [self createAircraftSetupList];
  
    
}

- (IBAction)actionViewInAppPurchases:(id)sender {
   
    flagShowOnlyFleetIncrease = 0;
    
    _viewAllAvailList.hidden = YES;
    _viewAircraftSetup.hidden = YES;    
    _viewInAppPurchases.hidden = NO;
    [_viewOne bringSubviewToFront:_viewInAppPurchases];
    [self startInAppPurchase];    
   
}




- (IBAction)actionCloseInAppPurchase:(id)sender {    
    _viewInAppPurchases.hidden = YES;
    _viewAllAvailList.hidden = NO;
    [_viewOne bringSubviewToFront:_viewAllAvailList];  
    
    [self createAllAvailableAircraftList];
    
}


- (void) startInAppPurchase {
    [_activityIndicator startAnimating];
    [self fetchAvailableProducts];
}

- (void)viewDidDisappear:(BOOL)animated {
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

-(void)fetchAvailableProducts{
    
    NSSet *productIdentifiers;
    
    NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
    if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
    //NSLog(@"fetchAvailableProducts  userExtraCheck %@", userExtraCheck);
    
    
    if ([userExtraCheck rangeOfString:@"flightSchoolPackage1"].location != NSNotFound  ) {  
        productIdentifiers = [NSSet
                              setWithObjects:IAPproductID6, IAPproductID7, IAPproductID8 ,nil];        
    }else{
        productIdentifiers = [NSSet
                              setWithObjects:IAPproductID1, IAPproductID2, IAPproductID3, IAPproductID4, IAPproductID5, IAPproductIDIncrease3, IAPproductIDIncrease5,  nil];  
    } 
        
    
    //NSLog(@"fetchAvailableProducts  productIdentifiers %@", productIdentifiers);    
    
    productsRequest = [[SKProductsRequest alloc]
                       initWithProductIdentifiers:productIdentifiers];        
    productsRequest.delegate = self;    
    [productsRequest start];    
    
}

- (BOOL)canMakePurchases
{
    return [SKPaymentQueue canMakePayments];
}



#pragma mark StoreKit Delegate

-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    
    //NSLog(@"1 paymentQueue ");
    
    for (SKPaymentTransaction *transaction in transactions) {
        
     
        
        checkHighestCategory = 0;
    
        
        
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
                //NSLog(@"Purchasing %@", transaction.payment.productIdentifier);
                //NSLog(@"selectedProductID %@", selectedProductID);
                break;
            case SKPaymentTransactionStatePurchased:
                //NSLog(@"1 case ");
                
                if ([transaction.payment.productIdentifier isEqualToString:selectedProductID]) {
                    //NSLog(@"Purchased ");                    
                   // save
                    
                    
                     if ([selectedProductID rangeOfString:@"GyronimoFleetIncrease"].location != NSNotFound  ) {  
                         
                         [[NSUserDefaults standardUserDefaults]  setObject: selectedProductID        forKey:@"purchasedIncreaseID"];
                         
                         //NSLog(@"1 selectedProductID %@ ", selectedProductID); 
                     }else{
                         
                         [[NSUserDefaults standardUserDefaults]  setObject: selectedProductID        forKey:@"purchasedProductID"];
                         
                         //NSLog(@"saving purchasedProductID %@ ", selectedProductID);
                     }
                    
                    // check if we have reduced the amount of aircraft
                    int newMaxAircraft = 2;
                    if ([selectedProductID isEqualToString:@"GyronimoFleetIncrease3"]) {
                        newMaxAircraft = 3;
                    }
                    if ([selectedProductID isEqualToString:@"GyronimoFleetIncrease5"]) {
                        newMaxAircraft = 5;
                    }
                   
                    
                    //NSLog(@"2 selectedProductID %@ ", selectedProductID);
                    
                    NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
                    if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
                    //NSLog(@"showPurchaseSuccessAlert userExtraCheck %@", userExtraCheck);       
                    
                    if ([userExtraCheck rangeOfString:@"flightSchoolPackage"].location != NSNotFound  ) {  
                          [self createMyFleetList];
                    }else{
                        if (newMaxAircraft < maxNumberOfAircraftInFleet ) {
                            [arrayDictAllAircraft removeAllObjects];
                            [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft  forKey:@"arrayDictAllAircraft"];
                            
                            [self showPurchaseSuccessAlert:@"Selected number of aircraft is lower than previous number. Aircraft entries will be deleted."];
                            [self createMyFleetList];
                        }
                        
                    }
                    
                    
                    
                    
                    [self createIAPlist];
                    [self createAircraftSetupList];
                    [self createMyFleetList];
                    [self createAllAvailableAircraftList];
                    
                    //NSLog(@"IAPController: purchased Status = purchased !!");
                    
                    
                    if ([userExtraCheck rangeOfString:@"flightSchoolPackage"].location != NSNotFound  ) {          
                        //NSLog(@"111111 is flightSchoolPackageflightSchoolPackage now load it");        
                        [self loadFleetFromFC];
                        
                        //start loading
                        flagDoNotCreateFlightNow = 1; 
                        //NSLog(@"actionLoadAircraftData flagDoNotCreateFlightNow = 1");
                        
                        NSString *note = [[NSString alloc] initWithFormat:@"%f", 0.0];
                        //NSLog(@"noting 3");
                        [[NSNotificationCenter defaultCenter] postNotificationName: @"noteCreateFakeFlight" object: note];   
                        triggerSetDefaultsForPerformanceCharts = 0; 
                        [self createAircraftSetupList];    
                        //showAircraftSetup    
                        _viewAllAvailList.hidden = YES;
                        _viewInAppPurchases.hidden = YES;        
                        _viewAircraftSetup.hidden = NO;
                        [_viewOne bringSubviewToFront:_viewAircraftSetup];
                        flagFleetWasChanged = 0;
                        ViewController *parent = (ViewController *)self.parentViewController;
                        [parent showLoadDataFM];    
                        [self performSelector: @selector (startLoadingData) withObject:nil afterDelay: 0.1f]; 
                        //NSLog(@"all clear %@", userExtraCheck); 
                    }else{
                        [self showPurchaseSuccessAlert:@"Purchase is completed succesfully. "];
                        
                    }
                    
                    
                }
                
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;
                
            case SKPaymentTransactionStateRestored:
                
                
                //NSLog(@"transaction.payment.productIdentifier = %@", transaction.payment.productIdentifier);             
                
                if ([transaction.payment.productIdentifier rangeOfString:@"FlightPad"].location != NSNotFound || [transaction.payment.productIdentifier rangeOfString:@"GyronimoFleetIncrease"].location != NSNotFound ) {  
                
                    //NSLog(@"Restored is %@", transaction.payment.productIdentifier);
                    
                    if ([transaction.payment.productIdentifier rangeOfString:@"GyronimoFleetIncrease"].location != NSNotFound  ) {  
                        
                        [[NSUserDefaults standardUserDefaults]  setObject: transaction.payment.productIdentifier        forKey:@"purchasedIncreaseID"];                        
                        //NSLog(@"1 selectedProductID %@ ", selectedProductID); 
                    }
                    
                    
                    [[NSUserDefaults standardUserDefaults]  setObject:transaction.payment.productIdentifier        forKey:@"checkThisID"];
                    [self setHighestCategory];
                   
                    if (flagRestoreDone == 0) {
                        
                        NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
                        if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
                        //NSLog(@"showPurchaseSuccessAlert userExtraCheck %@", userExtraCheck);       
                        
                        if ([userExtraCheck rangeOfString:@"flightSchoolPackage"].location != NSNotFound  ) {   
                            
                            alertFlag = 6; 
                            flagRestoreDone = 1;
                            NSString *messageString = [ [NSString alloc] initWithFormat:@"Restore Successful. Please load fleet data. This might take 1-2 minutes."];                        
                            UIAlertView *alert = [[UIAlertView alloc]
                                                  
                                                  initWithTitle:@"Restore"                              
                                                  message:messageString                              
                                                  delegate:self                              
                                                  cancelButtonTitle:@"Load Fleet Data"                            
                                                  otherButtonTitles: nil];        
                            [alert show];
                        }else{
                            
                            [self showPurchaseSuccessAlert:@"Restore is completed succesfully. "];
                        }
                    }
                    
                  
                    
                    
                    
                   
                    
                    
                    
                }
                
                [self checkCategories];
                [self createIAPlist];
                [self createAllAvailableAircraftList];
                [self createAircraftSetupList];
                [self createMyFleetList];
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;
                
                
            case SKPaymentTransactionStateFailed:                
                //NSLog(@"Purchase failed ");
                [[NSUserDefaults standardUserDefaults]  setObject:@"failed"        forKey:@"_purchasedStatus"];
                
                if ([transaction.payment.productIdentifier rangeOfString:@"FlightPad"].location != NSNotFound  ) {  
                    [self handlePaymentTransactionFailResponse:transaction];
                    
                }
                /*
                if ([transaction.payment.productIdentifier isEqualToString:IAPproductID1]) {  
                     //NSLog(@"fail 1... ");
                    [self handlePaymentTransactionFailResponse:transaction];
                }
                if ([transaction.payment.productIdentifier isEqualToString:IAPproductID2]) {  
                    //NSLog(@"fail 2... ");
                    [self handlePaymentTransactionFailResponse:transaction];
                }
                if ([transaction.payment.productIdentifier isEqualToString:IAPproductID3]) {  
                    //NSLog(@"fail 2... ");
                    [self handlePaymentTransactionFailResponse:transaction];
                }
                if ([transaction.payment.productIdentifier isEqualToString:IAPproductID4]) {  
                    //NSLog(@"fail 2... ");
                    [self handlePaymentTransactionFailResponse:transaction];
                }
                if ([transaction.payment.productIdentifier isEqualToString:IAPproductID5]) {  
                    //NSLog(@"fail 2... ");
                    [self handlePaymentTransactionFailResponse:transaction];
                }
                if ([transaction.payment.productIdentifier isEqualToString:IAPproductID6]) {  
                    //NSLog(@"fail 2... ");
                    [self handlePaymentTransactionFailResponse:transaction];
                }
                if ([transaction.payment.productIdentifier isEqualToString:IAPproductIDIncrease3]) {  
                    //NSLog(@"fail 2... ");
                    [self handlePaymentTransactionFailResponse:transaction];
                }
                if ([transaction.payment.productIdentifier isEqualToString:IAPproductIDIncrease5]) {  
                    //NSLog(@"fail 2... ");
                    [self handlePaymentTransactionFailResponse:transaction];
                }
                if ([transaction.payment.productIdentifier isEqualToString:IAPproductIDIncrease10]) {  
                    //NSLog(@"fail 2... ");
                    [self handlePaymentTransactionFailResponse:transaction];
                }
                 */
                
                
             
                break;
            default:
                //NSLog(@"paymentQueue:updatedTransactions: Invalid state");
                break;
        }
    }
}



- (void) setHighestCategory {
    
    
    //NSLog(@"setHighestCategory" );
     
    NSString *availableCategory = [[NSUserDefaults standardUserDefaults]  stringForKey:@"checkThisID"];  
    
    int flagIsFlightSchoolPack = 0;
    
    if ([availableCategory isEqualToString:@"GyronimoFlightPadCategory1"]) {
        [arrayHighestCategory addObject:@"1"];
    }
    if ([availableCategory isEqualToString:@"GyronimoFlightPadCategory2"]) { 
        [arrayHighestCategory addObject:@"2"];
    }
    if ([availableCategory isEqualToString:@"GyronimoFlightPadCategory3"]) {
       [arrayHighestCategory addObject:@"3"];
    }
    if ([availableCategory isEqualToString:@"GyronimoFlightPadCategory4"]) {
      [arrayHighestCategory addObject:@"4"];
    }
    if ([availableCategory isEqualToString:@"GyronimoFlightPadCategory5"]) { 
        [arrayHighestCategory addObject:@"5"];
    }
    if ([availableCategory isEqualToString:@"GyronimoFlightSchoolPackHelicopter"]) { 
        flagIsFlightSchoolPack = 1;
        [arrayHighestCategory addObject:@"3"];
    }
    
    if ([availableCategory isEqualToString:@"GyronimoFlightSchoolPackFixedWing"]) { 
        flagIsFlightSchoolPack = 2;
        [arrayHighestCategory addObject:@"3"];
    }
    
    if ([availableCategory isEqualToString:@"GyronimoFlightSchoolPackALL"]) { 
        flagIsFlightSchoolPack = 3;
        [arrayHighestCategory addObject:@"3"];
    }
    
    
    
    NSNumber *maxNumber = [arrayHighestCategory valueForKeyPath:@"@max.self"];
    NSInteger value = [maxNumber integerValue];
    
    //NSLog(@"saving value %ld", (long)value );
    
    if (flagIsFlightSchoolPack == 0) {
        if (value == 1) {      
            [[NSUserDefaults standardUserDefaults]  setObject:IAPproductID1        forKey:@"purchasedProductID"];
        }
        if (value == 2) {           
            [[NSUserDefaults standardUserDefaults]  setObject:IAPproductID2        forKey:@"purchasedProductID"];
        }
        if (value == 3) {       
            [[NSUserDefaults standardUserDefaults]  setObject:IAPproductID3        forKey:@"purchasedProductID"];
        }
        if (value == 4) {         
            [[NSUserDefaults standardUserDefaults]  setObject:IAPproductID4        forKey:@"purchasedProductID"];
        }
        if (value == 5) {         
            [[NSUserDefaults standardUserDefaults]  setObject:IAPproductID5        forKey:@"purchasedProductID"];
        }
    }else{
        
        if (flagIsFlightSchoolPack == 1) {         
            [[NSUserDefaults standardUserDefaults]  setObject:IAPproductID6        forKey:@"purchasedProductID"];
        }
        if (flagIsFlightSchoolPack == 2) {         
            [[NSUserDefaults standardUserDefaults]  setObject:IAPproductID7        forKey:@"purchasedProductID"];
        }
        if (flagIsFlightSchoolPack == 3) {         
            [[NSUserDefaults standardUserDefaults]  setObject:IAPproductID8        forKey:@"purchasedProductID"];
        }
        
        
        
    }
    
   
    
    
    
}




-(void)handlePaymentTransactionFailResponse:(SKPaymentTransaction *) transaction {
    //    SKErrorUnknown,
    //    SKErrorClientInvalid,                                                     // client is not allowed to issue the request, etc.
    //    SKErrorPaymentCancelled,                                                  // user cancelled the request, etc.
    //    SKErrorPaymentInvalid,                                                    // purchase identifier was invalid, etc.
    //    SKErrorPaymentNotAllowed,                                                 // this device is not allowed to make the payment
    //    SKErrorStoreProductNotAvailable,                                          // Product is not available in the current storefront
    //    SKErrorCloudServicePermissionDenied NS_ENUM_AVAILABLE_IOS(9_3),           // user has not allowed access to cloud service information
    //    SKErrorCloudServiceNetworkConnectionFailed NS_ENUM_AVAILABLE_IOS(9_3),    // the device could not connect to the nework
    //    SKErrorCloudServiceRevoked NS_ENUM_AVAILABLE_IOS(10_3),                   // user has revoked permission to use this cloud service
    
    NSString *errorDescription = nil;
    switch (transaction.error.code) {
        case SKErrorClientInvalid:
            //NSLog(@"client is not allowed to issue the request, etc.");
            errorDescription = transaction.error.localizedDescription;
            break;
        case SKErrorPaymentCancelled:
            //NSLog(@"user cancelled the request, etc.");
            //            errorDescription = transaction.error.localizedDescription;
            break;
        case SKErrorPaymentInvalid:
            //NSLog(@"purchase identifier was invalid, etc.");
            errorDescription = transaction.error.localizedDescription;
            break;
        case SKErrorPaymentNotAllowed:
            errorDescription = transaction.error.localizedDescription;
            //NSLog(@"this device is not allowed to make the payment");
            break;
        case SKErrorStoreProductNotAvailable:
            //NSLog(@"Product is not available in the current storefront");
            errorDescription = transaction.error.localizedDescription;
            break;
        case SKErrorCloudServicePermissionDenied:
            //NSLog(@"user has not allowed access to cloud service information");
            errorDescription = transaction.error.localizedDescription;
            break;
        case SKErrorCloudServiceNetworkConnectionFailed:
            //NSLog(@"the device could not connect to the nework");
            errorDescription = transaction.error.localizedDescription;
            break;
        case SKErrorCloudServiceRevoked:
            //NSLog(@"user has revoked permission to use this cloud service");
            errorDescription = transaction.error.localizedDescription;
            break;
        default:
            break;
    }
   
    if (errorDescription) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:errorDescription
                                                                                 message:nil
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
    
}

-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
       
    //NSLog(@"productsRequest ");
    if ([response.products count] > 0) {          
        validProducts = response.products;
        [self createIAPlist];
        
    } else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Not Available"
                                                                                 message:@"No products to purchase"
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
          //NSLog(@"stop animating");
       [_activityIndicator stopAnimating];
    });
    
    
    
   
}


- (void) createIAPlist {
    
   
    
    dispatch_async(dispatch_get_main_queue(), ^{
          //NSLog(@"dispatchung");
        [self createIAPlistReally];
    });
    
}

- (void) createIAPlistReally {
    
   
    //NSLog(@"createIAPlistReally");
    
    _viewLoadingIAPs.hidden = NO;
    [_viewInAppPurchases bringSubviewToFront: _viewLoadingIAPs];
    
    validProduct = nil;
    
    for(UIView *subview in [_viewIAPlist subviews]) {
        [subview removeFromSuperview];
    }
    
    [self checkCategories];
    
    float yStart = 0;
    float xPos1 = 10;
    float yGap = 250; 
    float yPos = 0;
    
    float cellWidth = _viewIAPlist.frame.size.width;
    
    arrayValidProductIDs =  [[NSMutableArray alloc] init];
    
    _viewIAPlist.frame = CGRectMake(_scrollViewIAPlist.frame.origin.x + 210, _viewIAPlist.frame.origin.y, _viewIAPlist.frame.size.width, (validProducts.count * yGap) + yGap);
    
    [_scrollViewIAPlist setContentSize:CGSizeMake(_scrollViewIAPlist.frame.size.width, _viewIAPlist.frame.size.height)];
    
    for(int i =0; i<validProducts.count; i++) { 
        
        NSString *productTitel;
        NSString *desctiption;
        NSString *price;
        
        validProduct = [validProducts objectAtIndex:i];  
        
        [arrayValidProductIDs addObject:validProduct.productIdentifier];

        productTitel = [NSString stringWithFormat: @"Purchase: %@",validProduct.localizedTitle];        
        desctiption = [NSString stringWithFormat: @"Features: %@",validProduct.localizedDescription];         
                  
        //price = [NSString stringWithFormat: @"Product Price: %@",validProduct.price]; 
        
        NSString *prodId = validProduct.productIdentifier;
        
        if (flagShowOnlyFleetIncrease < 1) {
            if ([prodId rangeOfString:@"FleetIncrease"].location != NSNotFound  ) {  
                continue;                
            }
        }
        
        if (flagShowOnlyFleetIncrease == 1) {
         
            if ([prodId rangeOfString:@"GyronimoFlight"].location != NSNotFound  ) {  
                continue;                
            }
        }
       
        
        //NSLog(@"prodId %@", prodId);
        
        
        int currentCategory = 0;
        int flagIsIncreasePack = 0;
        
        if ([prodId isEqualToString:@"GyronimoFlightPadCategory1"]) {         
            currentCategory = 1;
        }
        if ([prodId isEqualToString:@"GyronimoFlightPadCategory2"]) {       
            currentCategory = 2;
        }
        if ([prodId isEqualToString:@"GyronimoFlightPadCategory3"]) {      
            currentCategory = 3;
        }
        if ([prodId isEqualToString:@"GyronimoFlightPadCategory4"]) {     
            currentCategory = 4;
        }
        if ([prodId isEqualToString:@"GyronimoFlightPadCategory5"]) {     
            currentCategory = 5;
        }
        if ([prodId isEqualToString:@"GyronimoFlightSchoolPackHelicopter"]) {     
            currentCategory = 3;
        }
        if ([prodId isEqualToString:@"GyronimoFlightSchoolPackFixedWing"]) {     
            currentCategory = 3;
        }
        if ([prodId isEqualToString:@"GyronimoFlightSchoolPackALL"]) {     
            currentCategory = 3;
        }
        
        
        if ([prodId isEqualToString:@"GyronimoFleetIncrease3"]) {     
            flagIsIncreasePack = 3; 
        }
        if ([prodId isEqualToString:@"GyronimoFleetIncrease5"]) {     
            flagIsIncreasePack = 5; 
        }
        
       
        if (currentCategory < 1) {
            
            UIImage *buttonBack = [UIImage imageNamed:@"button generic blue.png"];
            [_buttonDone setBackgroundImage:buttonBack forState:UIControlStateNormal];

        }else{
            
            UIImage *buttonBack = [UIImage imageNamed:@"button generic green.png"];
            [_buttonDone setBackgroundImage:buttonBack forState:UIControlStateNormal];
        }
        
        //NSLog(@"making currentCategory %d", currentCategory);
        
      
        //flightSchoolPackage
        
        NSString *exampleACtext;
        UIImage *exampleIAPImage;
        NSString *noteText;
        NSString *noteText2;
        NSString *noteText3;
        
        NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
        if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
        
        if ([userExtraCheck rangeOfString:@"flightSchoolPackage1"].location != NSNotFound  ) {  
           
        
            if ([prodId isEqualToString:@"GyronimoFlightSchoolPackHelicopter"]) {  
                exampleACtext =  @"" ;
                exampleIAPImage = [UIImage imageNamed:@"exampleIAPImageHelicopter.png"];
                noteText3 = @"This is a 1-year auto renewal subscription.";
                noteText = @"Note: This subscription will enable all helicopters registered with your flight school";
                noteText2 = @"";
                
            }
            
            if ([prodId isEqualToString:@"GyronimoFlightSchoolPackFixedWing"]) {  
                exampleACtext =  @"" ;
                exampleIAPImage = [UIImage imageNamed:@"exampleIAPImageFixedWing.png"];
                noteText3 = @"This is a 1-year auto renewal subscription.";
                 noteText = @"Note: This subscription will enable all fixed wing aircraft registered with your flight school";
                noteText2 = @"";
                
            }
            
            if ([prodId isEqualToString:@"GyronimoFlightSchoolPackALL"]) {  
                exampleACtext =  @"" ;
                exampleIAPImage = [UIImage imageNamed:@"exampleIAPImageFixedHeli.png"];
                noteText3 = @"This is a 1-year auto renewal subscription.";
                noteText = @"Note: This subscription will enable all fixed wing aircraft registered with your flight school";
                noteText2 = @"";
                
            }
            
            
        }else{
            
            
            if ([prodId isEqualToString:@"GyronimoFleetIncrease3"]) {  
                exampleACtext =  @"" ;
                exampleIAPImage = [UIImage imageNamed:@"exampleIAPImage3aircraft.png"];
                noteText3 = @"This is a 1-year auto renewal subscription. You can upgrade or downgrade between selections anytime.";
                noteText = @"Note: Your fleet can contain helicopter and/or fixed wing aircraft.";
                noteText2 = @"This will increase your fleet to 3 different aircraft models, regardless of the purchased category.";
                
            }
            
            if ([prodId isEqualToString:@"GyronimoFleetIncrease5"]) {  
                exampleACtext =  @"" ;
                exampleIAPImage = [UIImage imageNamed:@"exampleIAPImage5aircraft.png"];
                noteText3 = @"This is a 1-year auto renewal subscription. You can upgrade or downgrade between selections anytime.";
                noteText = @"Note: Your fleet can contain helicopter and/or fixed wing aircraft.";
                noteText2 = @"This will increase your fleet to 5 different aircraft models, regardless of the purchased category.";
                
            }
            
            
            
            if ([prodId isEqualToString:@"GyronimoFlightPadCategory1"]) {  
                exampleACtext =  @"Example: 1-4 seats, no performance computations included" ;
                exampleIAPImage = [UIImage imageNamed:@"exampleIAPImage1.png"];
                noteText3 = @"This is a 1-year auto renewal subscription. You can upgrade or downgrade between categories anytime.";
                noteText = @"Note: Aircraft in Category 1 feature weight & balance computations only.";
                noteText2 = @"Performance computations (takeoff, landing distance etc) are not included in this category.";
               
                
            }
            if ([prodId isEqualToString:@"GyronimoFlightPadCategory2"]) {  
                exampleACtext =  @"Example: 1-4 seats, including performcance computations";
                exampleIAPImage = [UIImage imageNamed:@"exampleIAPImage2.png"];
                noteText3 = @"This is a 1-year auto renewal subscription. You can upgrade or downgrade between categories anytime.";
                noteText = @"Note: Category 2 includes Category 1 plus additional features such as:";
                noteText2 = @"Performance (Takeoff, Landing, Climb, Cruise)";
                
                
            }
            if ([prodId isEqualToString:@"GyronimoFlightPadCategory3"]) {  
                exampleACtext =   @"Example: Complex aircraft, performance computations included";
                exampleIAPImage = [UIImage imageNamed:@"exampleIAPImage3.png"];
                noteText3 = @"This is a 1-year auto renewal subscription. You can upgrade or downgrade between categories anytime.";
                noteText = @"Note: Category 3 includes Category 1 and 2 plus additional features such as:";
                noteText2 = @"Complex Performance (HOGE, HIGE for helicopters etc)";
                
            }
            if ([prodId isEqualToString:@"GyronimoFlightPadCategory4"]) {  
                exampleACtext =   @"Example: Complex aircraft, including performcance computations";
                exampleIAPImage = [UIImage imageNamed:@"exampleIAPImage4.png"];
                noteText3 = @"This is a 1-year auto renewal subscription. You can upgrade or downgrade between categories anytime.";
                noteText = @"Note: Category 4 includes Category 1, 2 and 3 plus additional features such as:";
                noteText2 = @"Complex Interior configurations, advanced performance computations";
                
            }
            if ([prodId isEqualToString:@"GyronimoFlightPadCategory5"]) {  
                exampleACtext =   @"Example: Complex aircraft, including special features" ;  
                exampleIAPImage = [UIImage imageNamed:@"exampleIAPImage5.png"];
                noteText3 = @"This is a 1-year auto renewal subscription. You can upgrade or downgrade between categories anytime.";
                noteText = @"Note: Category 5 includes Category 1,2,3 and 4 plus additional features such as:";
                noteText2 = @"Support for larger aircraft, multiple interior configurations, advanced performance computations";
            }
            
        }
        
        
        
        //NSLog(@"maxAvailableCategory %d", maxAvailableCategory);        
        //NSLog(@"currentCategory %d", currentCategory);
        
        // check if you have this
        int flagYouHaveThis = 0;
        
        //NSLog(@"1 flagIsIncreasePack %d", flagIsIncreasePack);
        //NSLog(@"maxNumberOfAircraftInFleet %d", maxNumberOfAircraftInFleet);  
        
        if (currentCategory <= maxAvailableCategory) {
            flagYouHaveThis = 1;            
        }
        
        if (flagIsIncreasePack == 3) {   
            flagYouHaveThis = 0;
            if (maxNumberOfAircraftInFleet == 3) {
                 flagYouHaveThis = 1;         
            }         
        }
        if (flagIsIncreasePack == 5) {  
            flagYouHaveThis = 0;
            if (maxNumberOfAircraftInFleet == 5) {
                flagYouHaveThis = 1;         
            }         
        }
        if (flagIsIncreasePack == 10) {  
            flagYouHaveThis = 0;
            if (maxNumberOfAircraftInFleet == 10) {
                flagYouHaveThis = 1;         
            }         
        }
        
        
        //NSLog(@"1 flagYouHaveThis %d", flagYouHaveThis);  
        //NSLog(@"maxNumberOfAircraftInFleet %d", maxNumberOfAircraftInFleet);  
        
        if (flagYouHaveThis == 1) {
            // you already have this
            
            /*
            //get local currency
            NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
            [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
            [numberFormatter setLocale:validProduct.priceLocale];
            NSString *formattedPrice = [numberFormatter stringFromNumber:validProduct.price];        
            price = [NSString stringWithFormat: @"Product Price: %@",formattedPrice]; 
             */
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 0, yStart + yPos + 0, 500, 20 )];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];    
            [label  setText:  productTitel ]; 
            [_viewIAPlist addSubview: label]; 
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 0, yStart + yPos + 25, 500, 20 )];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];    
            [label  setText:  desctiption ]; 
            [_viewIAPlist addSubview: label];  
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 0, yStart + yPos + 50, 500, 20 )];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor greenColor];    
            [label  setText:  @"You already purchased this product" ]; 
            [_viewIAPlist addSubview: label];  
                        
            UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            aButton.frame     = CGRectMake(xPos1 -15, yStart + yPos + 80, 300, 45 );
            NSString *buttonText =  [NSString stringWithFormat: @"Manage: %@",validProduct.localizedTitle];   
            [aButton setTitle:buttonText forState:(UIControlStateNormal)];
            //UIImage *buttonBack = [UIImage imageNamed:@"button generic dark.png"];
            UIImage *buttonBack = [UIImage imageNamed:@"button long generic dark"];
            [aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];
            aButton.tintColor = [UIColor whiteColor];
            aButton.showsTouchWhenHighlighted = YES;
            //aButton.titleLabel.font = [UIFont systemFontOfSize:13];
            [aButton setTag:i];
            [aButton addTarget:self action:@selector(actionPurchaseIAP:) forControlEvents:UIControlEventTouchUpInside];
            [_viewIAPlist addSubview:aButton];              
            
            // example            
            UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake( cellWidth - 250, yStart + yPos - 5, 250, 100 )];
            textView.font = [UIFont systemFontOfSize:13];
            textView.textAlignment = NSTextAlignmentRight;
            textView.textColor = [UIColor lightGrayColor];  
            textView.backgroundColor = [UIColor clearColor];
            textView.userInteractionEnabled = NO;            
            [textView  setText:  exampleACtext ];            
            [_viewIAPlist addSubview: textView]; 
            
            // example  Image
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake( cellWidth - 170, yStart + yPos + 45, 170 , 85 )];
            [imageView setImage: exampleIAPImage];
            [_viewIAPlist addSubview: imageView]; 
            
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 0, yStart + yPos + 157, 700, 20 )];
            label.font = [UIFont systemFontOfSize:12];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];    
            [label  setText: noteText3 ]; 
             [_viewIAPlist addSubview: label];
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 0, yStart + yPos + 173, 700, 20 )];
            label.font = [UIFont systemFontOfSize:12];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];    
            [label  setText:  noteText]; 
            [_viewIAPlist addSubview: label];  
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 0, yStart + yPos + 190, 700, 20 )];
            label.font = [UIFont systemFontOfSize:12];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];    
            [label  setText:  noteText2]; 
            [_viewIAPlist addSubview: label];  
            
            
            
        }else{            
            
            // you don't have this            
            //get local currency
            NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
            [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
            [numberFormatter setLocale:validProduct.priceLocale];
            NSString *formattedPrice = [numberFormatter stringFromNumber:validProduct.price];        
            price = [NSString stringWithFormat: @"Product Price: %@ (per year)",formattedPrice];         
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 0, yStart + yPos + 0, 500, 20 )];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor whiteColor];    
            [label  setText:  productTitel ]; 
            [_viewIAPlist addSubview: label]; 
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 0, yStart + yPos + 25, 500, 20 )];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor whiteColor];    
            [label  setText:  desctiption ]; 
            [_viewIAPlist addSubview: label];  
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 0, yStart + yPos + 50, 500, 20 )];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor whiteColor];    
            [label  setText:  price ]; 
            [_viewIAPlist addSubview: label]; 
            
            
            UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            aButton.frame     = CGRectMake(xPos1 -15, yStart + yPos + 80, 300, 55 );
            NSString *buttonText =  [NSString stringWithFormat: @"Purchase: %@",validProduct.localizedTitle];   
            [aButton setTitle:buttonText forState:(UIControlStateNormal)];
            //UIImage *buttonBack = [UIImage imageNamed:@"button generic green"];
            UIImage *buttonBack = [UIImage imageNamed:@"button generic blue.png"];
            [aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];
            aButton.tintColor = [UIColor whiteColor];
            aButton.showsTouchWhenHighlighted = YES;
            //aButton.titleLabel.font = [UIFont systemFontOfSize:13];
            [aButton setTag:i];
            [aButton addTarget:self action:@selector(actionPurchaseIAP:) forControlEvents:UIControlEventTouchUpInside];
            [_viewIAPlist addSubview:aButton];      
            
            // example            
            UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake( cellWidth - 250, yStart + yPos - 5, 250, 100 )];
            textView.font = [UIFont systemFontOfSize:13];
            textView.textAlignment = NSTextAlignmentRight;
            textView.textColor = [UIColor lightGrayColor];  
            textView.backgroundColor = [UIColor clearColor];
            textView.userInteractionEnabled = NO;            
            [textView  setText:  exampleACtext ];            
            [_viewIAPlist addSubview: textView]; 
            
            // example  Image
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake( cellWidth - 170, yStart + yPos + 45, 170 , 85 )];
            [imageView setImage: exampleIAPImage];
            [_viewIAPlist addSubview: imageView]; 
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 0, yStart + yPos + 157, 700, 20 )];
            label.font = [UIFont systemFontOfSize:12];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];    
            [label  setText:  noteText3 ]; 
            [_viewIAPlist addSubview: label];
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 0, yStart + yPos + 173, 700, 20 )];
            label.font = [UIFont systemFontOfSize:12];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];    
            [label  setText:  noteText]; 
            [_viewIAPlist addSubview: label];  
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 + 0, yStart + yPos + 190, 700, 20 )];
            label.font = [UIFont systemFontOfSize:12];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];    
            [label  setText:  noteText2]; 
            [_viewIAPlist addSubview: label];  
            
            
        }

        
                 
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake( xPos1, yStart + yPos + 220, cellWidth, 3 )];
        lineView.backgroundColor = [UIColor lightGrayColor];
        [_viewIAPlist addSubview:lineView]; 
        
        
       
        
        
        
        yPos = yPos +  yGap;  
        
    }
    
    _viewLoadingIAPs.hidden = YES;
     //NSLog(@"arrayValidProductIDs %@", arrayValidProductIDs);
}


- (IBAction)actionPurchaseIAP:(UIButton*)sender {  
    //NSLog(@"actionPurchaseIAP ");
    
    float buttonID = sender.tag;  
    //NSLog(@"actionPurchaseIAP  buttonID %.0f", buttonID);    
    selectedProductID = [arrayValidProductIDs objectAtIndex:buttonID];
    //NSLog(@"selectedProductID %@", selectedProductID);
    
    [self purchaseMyProduct:[validProducts objectAtIndex:buttonID]];     
    
   
}

- (void)purchaseMyProduct:(SKProduct*)product{
    
    if ([self canMakePurchases]) {
        purchaseType = 1;
        dispatch_async(dispatch_get_main_queue(), ^{
            SKPayment *payment = [SKPayment paymentWithProduct:product];
            if (payment != nil) {
                [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
                [[SKPaymentQueue defaultQueue] addPayment:payment];
            }
        });
    }
    else{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Purchases are disabled in your device"
                                                                                 message:nil
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}





- (void) showPurchaseSuccessAlert:(NSString *) title {
    
   
  
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
    }];
    [alertController addAction:actionOk];
    [self presentViewController:alertController animated:YES completion:nil];
    
    
  
    
}




- (IBAction)restoreCompletedTransactions:(id)sender {
    arrayHighestCategory =  [[NSMutableArray alloc] init];
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}


- (bool)is_online {
    
    int serverOnline = 0;
    
    //check if server is reachable / device is online
    //Reachability *r = [Reachability reachafbilityWithHostName:@"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;
    }
    
    if (serverOnline == 2) {
        //NSLog(@"check is_online true");
        return true;
    }else{
        //NSLog(@"check is_online false");
        return false;
    }

}


- (IBAction)actionCheckForAircraftDataUpdates:(id)sender {
    
    [self reloadAllAvailList];
   
}




- (void) reloadAllAvailList {
    
    //NSLog(@"reloadAllAvailList");        
    importConfigurations *_importConfigurations= [[importConfigurations alloc]init];
    [_importConfigurations loadAllAvailableAircraftListFromServer];  
    
    [self createAllAvailableAircraftList];
    
}
    
    
- (void)actionNotificationLoadedAllAircraftList:(NSNotification *)notification {
   
    //NSLog(@"actionNotificationLoadedAllAircraftList");
     triggerCheckForACupdates = 1;
     [self createAllAvailableAircraftList];
    
} 
  

- (void) updateAircraftData {
    

    // update the versions inside my fleet
    
    for(int i =0; i<arrayReplaceMyFleetID.count; i++) {   
        
        int index =  [[arrayReplaceMyFleetID objectAtIndex:i] intValue];
        NSString *replacement = [arrayReplaceMyFleetIDVersion objectAtIndex:i];        
              
        myFleetNewDict = [[NSMutableDictionary alloc] init];
        NSDictionary *oldDict = (NSDictionary *)[arrayDictAllAircraft objectAtIndex: index];
        [myFleetNewDict addEntriesFromDictionary:oldDict];        
        [myFleetNewDict setObject:replacement forKey:@"Version"]; 
        [arrayDictAllAircraft replaceObjectAtIndex:index withObject:myFleetNewDict];         
       
        
    }
    
    
    
    [[NSUserDefaults standardUserDefaults]  setObject:arrayDictAllAircraft  forKey:@"arrayDictAllAircraft" ];    
    [[NSUserDefaults standardUserDefaults]  setObject:arrayLoadedAircraft  forKey:@"arrayLoadedAircraft" ];
           
     
    triggerSetDefaultsForPerformanceCharts = 0; 
   
    flagFleetWasChanged = 0;
    ViewController *parent = (ViewController *)self.parentViewController;
    [parent showLoadDataFM];    
    [self performSelector: @selector (startLoadingData) withObject:nil afterDelay: 0.1f]; 
    
}
    
   
    
    
    

- (IBAction)actionOpenPrivacyPolicy:(id)sender {
    
    [[UIApplication sharedApplication]
     
     openURL:[NSURL URLWithString:@"http://www.gyronimo.com/privacy-policy"]];
    
}

- (IBAction)actionOpenTermsOfUse:(id)sender {
    
    [[UIApplication sharedApplication]
     
     openURL:[NSURL URLWithString:@"https://www.gyronimo.com/terms-of-use"]];
    
}

- (IBAction)actionIncreaseFleet:(id)sender {
    
    _viewAllAvailList.hidden = YES;
    _viewAircraftSetup.hidden = YES;    
    _viewInAppPurchases.hidden = NO;
    [_viewOne bringSubviewToFront:_viewInAppPurchases];
    flagShowOnlyFleetIncrease = 1;
    [self startInAppPurchase]; 
}
@end
