//
//  ViewController.m
//
//
//  Created by Claus Richter on 2/5/13.
//  Copyright (c) 2014 gyronimo. All rights reserved.
//



#import "ViewController.h"
#import "crewPerson.h"
#import "location.h"

#import "StartPage.h"
#import "VDLabelWithDropDown.h"

#import "JBSignatureController.h"
#import "JBSignatureView.h"
#import "dispatcherFlight.h"
#import <QuartzCore/CoreAnimation.h>

#import <SystemConfiguration/SCNetworkReachability.h>
#include <netinet/in.h>
#import "Reachability.h"
#import "DocumentViewer.h"
#import "EquipmentViewController.h"
#import "EquipmentPackages.h"
#import "EquipPackagesManager.h"
#import "PackagesTotalsTVController.h"
#import "NSURLSession+SynchronousTask.h"

#import <CommonCrypto/CommonHMAC.h>
#import "UtilityCategories.h" // VD

#import "RiskAssessment.h"
#import "dList.h"

#import "importPerformanceData.h"
#import "importConfigurations.h"

#import "calcPerfClass.h"
#import "FleetManager.h"


@interface ViewController (){
    
    
    __weak IBOutlet UIView *packagesTotalsView_;
    PackagesTotalsTVController* packagesTotalsController_;
    
    
       dList* dListClass_;    
     __weak IBOutlet UIView *dListClassView_;
    
    importPerformanceData* importPerformanceDataClass_;    
    __weak IBOutlet UIView *importPerformanceDataClassView_;
    
    calcPerfClass *calculatePerformanceClass_;    
    __weak IBOutlet UIView *calculatePerformanceClassView_;
    
    importConfigurations *importConfigurationsClass_;
    
    FleetManager *fleetManagerClass_;
    __weak IBOutlet UIView *fleetManagerClassView_;
    
    
    
}
@end

NSString *const PHIAMSigV4Terminator = @"PHIAM-api-request";

@implementation ViewController

#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: 20.0/255.0 green: 20.0/255.0 blue: 20.0/255.0 alpha: 1.0] // this is dark gray
#define segmentdarkGrayColor [UIColor colorWithRed: 55.0/255.0 green: 55.0/255.0 blue: 55.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


@synthesize crossLDW;
@synthesize buttonDisplayEnvironment;

@synthesize buttonSetup;
@synthesize buttonDisplayFlight;
@synthesize inputFuelFlowOverride;
@synthesize crew_locations_sview;
@synthesize helicopter_sview;
@synthesize buttonLoadManifest;
@synthesize viewSetup;
@synthesize inputWarningPercentMargin;
@synthesize switchWarnings;


@synthesize displayHeliRegistration;

@synthesize vFlightDeparture;
@synthesize vFlightDestination;
@synthesize vFlightRegistration;
@synthesize viewTopDisplayButtons;
@synthesize viewTopTop;
@synthesize enterPad,      labelActualOAT, labelDisplayOAT, labelDisplayPA,   labelISAdiff, sliderISADiff, labelISAAnsage, labelDensityAlt, viewOne, viewMain, ScrollViewManifest, viewLoadManifest, viewEnvironment, viewSliderISA,   sliderOATforOGE, labelOATforOGE;


@synthesize warningAS355Pax5, warningCGoutsideEnvelope, warningWeightLimitExceeded, warningLatCGExceeded, crossTOW, crossZFW, crossLatTOW, labelWeightTakeoff, labelCGTakeoff, labelCGLat, labelWeightLanding, labelWeightZeroFuel, labelCGLanding, labelCGZeroFuel   ;


@synthesize Flight,Callsign, buttonOAT;


@synthesize unitsWeight,sliderHp,vBEW,vBEWMom,vBEWMomLat,lBEWArm,lBEWArmLat;

@synthesize calculatorscreen;

@synthesize buttonISA, buttonPressureAlt;

@synthesize datepick;

@synthesize  sliderQNH, labelQNH, labelQNHEuro, MSLfeet;

int configuration = 1;

int previousConfiguration = 0, flagDoNotDrawCG, createExtraEquipmentPage = 0;

float activeConfigButton = 1, robinsonTotalFuelForCG, robinsonArmForCG;
float auxshare =0, mainshare =0, auxshareLND =0, mainshareLND =0;

int modeEquipListOrInterior = 1;
float flagIsLandscape = 1;
float mainWeight = 0,  auxWeight = 0, mainMom = 0, auxMom = 0, auxMomLat = 0, mainMomLat = 0;
float mainWeightLND = 0,  auxWeightLND = 0, mainMomLND = 0, auxMomLND = 0, auxMomLatLND = 0, mainMomLatLND = 0;

float XstartPix = 0;    //left corner of graphic
float XendPix = 0;      // right corner

float XstartVal = 0;    // left start value
float XendVal = 0;      // right end value

float Xinput = 0;    // OAT
int counterAutoCheckFlagStatus = 0;
float equipmentItemsOnBoard = 0;

float numberOfSwitches = 0;
int calcLateral = 1;
int triggerOpenChart = 0, triggerDoNotShowPerfChart =0, flagClimbEndMustBeHigherThanElevation =0, flagTriggerSpecialCreateFlight = 0, flagShowOnlySameACType = 0, flagCheckForAvailableAircrafts = 0, flagWeHavePenaltyData = 0; 

float cargoWeight =0;
float fuelOnBoardKg = 0, lineOptions = 0, lineForPenaltyOptionsEnd = 0, maxHoistH145standard = 0, maxHoistH145special = 0;
float crewWeight =0;

int flagLoadManifestSentForThisFlight = 0, flagDoNotResetFuelFlow = 0;

float RESERVEfuelRequired = 0, incrementVariSlider1 = 1, incrementVariSlider2 = 1, incrementVariSlider3 = 1, incrementVariSlider4 = 1, MTOWfromEnvelope = 0;

float YbottomPix = 0;
float YtopPix = 0;

float YbottomVal = 0;
float YtopVal = 0;

float Yinput = 0;   // OGEinterpolResultIGE

float fullScreenPerfCharts = 0;

float memX1 = 0, memX2 = 0, memX3 = 0, memY1 = 0, memY2 = 0, memY3 = 0, bNr = 0;

float chartWidthInApp = 0;

float chartHeightInApp = 0;

float paxWeight =0, numberOfPax =0, specificFuelDensityValue = 0;

float transferLineInput = 0, transferAxisInput = 0;

float wantedX = 0, resultY = 0, resultY1 = 0,  resultY2 = 0, x1 = 0, x2 = 0, curveCut = 0;

float flagButtonListoPressed = 0;

int flagSettingDefaults = 0;
float hoistLoadBefore = 0;

int largeTopViewMode = 1;

float sliderColor = 2; float lockISA = 0; float ISAdif = 0; float densityalt = 0;

float OATinput = 0; float OATinISA = 15;

float warningMaxTOW = 0; float FuelReserveTimeMinutes = 0; 

float OGEinterpolResultIGE = 0;

float CGLongTOW = 0; float CGLongZFW = 0; float CGLongLDW = 0;

float internalFlightRandomNumber =0;


float weightZFW = 0; float weightTOW = 0; float weightLDW = 0;

float CGLATTOW = 0; float CGLATZFW = 0; float CGLATLDW = 0;

float weightLATZFW = 0; float weightLATTOW = 0; float weightLATLDW = 0;

float calcisa = 0, flagSignature = 0;

float HeliDataLoaded = 0;

float activeseat = 0;

int flagMakeNewFlgtNow = 0;
int flagLoadConfigDataForButton = 0;

int configMode = 0;

int flagShowCGEnvelopeValues = 0;

int flagResetAllLegs = 0, flagCopyFlight = 0;;

float flagChartsFitToScreenHeight = 0;

//altimetry

float OGEIGEmax = 0; float MSLtoHpDifference = 0; float OGEinterpolMaxHp = 0;



float listStatusIsOnline = 0;

float previousdButton = 1;

int toggleItemsInOut = 0;

float CrewDataLoaded = 0;

float OAT = 15; 

// alert

float alertFlag = 0;

float headWind = 0;

int flagRefreshSpecialEquipmentList = 1;

float  moveupDown = 0, moveLeftRight = 0, pinchScale = 1, pinchScaleEnded = 1;

float KIAS = 0;

float Hp =0;

// tank capcacity in lbs **************************************************************************************************************

float tankCapacityVolume = 0;

int flagCreateFuelPage = 0;

// tank capcacity in lbs **************************************************************************************************************

int flagTanksConnected = 1;

float amountOfButtons  = 0; // amountOfPerfButtons

int flagDoNotCreateFlightNow = 0, flagAlarmWahn = 0;
int triggerSetDefaultsForPerformanceCharts = 2;


//  interpolation Moment Fuel

float InLow1 = 0,  InHigh1 = 0, OutLow1 = 0,  OutHigh1 = 0,  OutInterpol1 = 0; 
float InLow2 = 0, InHigh2 = 0, OutLow2 = 0,  OutHigh2 = 0,  OutInterpol2 = 0;

float momTankFront = 0;  float momTankRear = 0; 

float GroupAKg = 0; float GroupBKg = 0;

float fuelMaxA = 0 ;  float fuelMaxB = 0; float fuelA = 0 ;  float fuelB = 0;

// conversions

float factorKgtoLBS =  2.20462;

float factorArmMeterToInches =  39.3701;

float factorMomentMeterToInches = 86.79517958;


float lineHoistLoad = 0, lineHoistSystem = 0, lineCargoLoad = 0;

int flagDoNOTheckFWDAFTCG = 0;

// floats to be saved 

float MBpagevisit = 0;

float warningFuelReserveTime = 20;

float warningPercentMargin = 3;

float warningsOnOff = 1; float  nvgMode = 0; float previousButton = 0;

float flagFuelVisisble = 1;

float flagShowSliders = 1;

float flagShowCargoPod = 0;




// floats to be saved and converted

float hoistLoadAttached = 0, friesLoadAttached = 0, externalLoadAttached = 0;

float sliderSeatIncrement = 5; 

float sliderFuelIncrement = 50;

float fuelPositionScroll = 0;

float dListInputFieldTag = 0;

int externalLoadActivated = 0; int hoistActivated = 0; int flagOneDoorOff = 0; int flagJustResettedFlightSettings = 0;

float displayWindow = 0;

float flagSetPickerTimeForFields = 0;

// enterpad
float currentNumber = 0; float commapressedTwo = 0;  float minuspressedTwo  = 0; float EnterValueTwo = 0;  

NSString *EnterPadString = @"0"; 

float selectedItem = 0; float enterpadAutoHide = 0; float flagButtonPressed = 0;

// interpol DTC

float interpolResultDTC1 = 0; float interpolResultDTC2 = 0; float interpolResultDTC3 = 0; float HpReduced = 0;


// interpol manually
float curveID = 2400; float yInput = 8; float xposDTCpart1 = 0; float headWindKts = 0;

float xVal1 = 0, xVal2 = 0, xVal3 = 0, xVal4 = 0, xVal5 = 0, xVal6 = 0, xVal7 = 0, xVal8 = 0, xVal9 = 0, xVal10 = 0, xVal11 = 0, xVal12 = 0, xVal13 = 0, xVal14 = 0, xVal15 = 0, xVal16 = 0;

float xVal1b = 0, xVal2b = 0, xVal3b = 0, xVal4b = 0, xVal5b = 0, xVal6b = 0, xVal7b = 0, xVal8b = 0, xVal9b = 0;

float intpol1 = 0; float intpol2 = 0; float intpol1b = 0; float intpol2b = 0; float xOutput = 0; float intpolMinus = 0;

// interpol Helipad

float interpolResultMTOWHelipad = 0; float interpolResultMTOWClearArea = 0; float flightTimeMinutesALL = 0;

// interpol FuelFlow

float interpolResultFuelFlow = 0; float intpolDif = 0;

int flagRecallSeat =0;

// flights

float currentFlightNumber = 0;  float highestFlightNumber = 0;

// individual Environments

float iEnviSliderOATforOGE = 15; float iEnviSliderOATforALL = 15; float iEnviMode = 0;
float iEnviSliderHpforOGE = 0; float iEnviSliderHpforALL = 0;

// warnings

float flagWarningCG = 0; float flagWarningWeight = 0, warningOnOff_MTOW = 0;;

float warningROC2Engines = 0; float warningROC1Engine = 0, statusSignature =0;

float RAW_BEW = 0; float RAW_BEW_Moment = 0; float RAW_BEW_MomentLAT = 0;



float datepickInterval = 1;

float colorModeForCGenvelope = 0;

 float totalFuelRequiredIncludingRESERVE_lbs = 0;


// ****** El Listo  El Listo  El Listo  El Listo  El Listo  El Listo  El Listo  El Listo  El Listo  El Listo  El Listo  El Listo   *********************

float listStart = 1, listEnd = 0;

float width1 = 0, width2 = 0, width3 = 0, width4 = 0, width5= 0, width6 = 0, width7 = 0, width8= 0;

float xButton = 1000;

float xPos1 = 0, xPos2 = 0, xPos3 = 0, xPos4 = 0, xPos5 = 0, xPos6 = 0, xPos7 = 0, xPos8 = 0 ;

float gap = 0;

int signatureForDocumentType = 0;

int foundLines = 0;

int flagUIdesign = 0;

float yPosTable = 0;

double totalWeightListo = 0, totallongMomentListo = 0, totalLatMomentListo = 0, totalArmListo = 0, totalArmLatListo = 0,    listoCGLong  = 0, listoCGLat  = 0;

double totalFuelListo = 0, totalFuelMomentListo = 0;

float listoPackStart = 0, listoPackEnd = 0;

float resultX= 0;

float yIn = 0;

float rideAlongSeat = 0;

float wgtTOWkg = 0, transferValue = 0, fuelPercent = 0;

float movementTranslationX = 0, movementTranslationY = 0;

float connectedToFleetControl = 0;

float sliderWindowXpos = 0;

float sliderWindowYpos = 115;

float sliderWindowWidth = 275;

float sliderWindowHeight = 583;

float stationYincrement = 70;  // pixel vertical gap



float LongArmFrontSeat = 0;

float LongArmRearSeat = 0;

float LatArmLeftSeat = 0;

float LatArmRightSeat = 0;

NSString *pilotNameGlobal = @"";
NSString *vFlightRegGlobal = @"";
NSString *specialdata1 = @"", *specialdata2 = @"", *formatString1 = @"%.4f", *formatString2 = @"%.4f", *formatString3 = @"%.0f", *formatString4 = @"%.0f";
NSString *triggerCopySliderSettingsWithFlightID = @"";
NSString *selectedUnitForItems = @"kg";
NSString *selectedUnitForFuel = @"kg";
NSString *fuelEnterMode = @"";
NSString *calcMode = @"plan";
NSString *unitsDistance = @"ft";
NSString *unitsElevation = @"ft";
NSString *unitsAltimeter = @"EU";
NSString *PHIcallsign = @"";

float factorApplyToNativeWeightforItems = 0;
float factorApplyToNativeFuelWeight = 0;
float factorApplyToNativeFuelVolumeGalLiter = 0;
float factorApplyToNativeDistanceInchMM = 0;
float factorApplyToNativeDistanceInchMMforFuel = 0;
float factorApplyToNativeMoment = 0;
float factorApplyToNativeFuelMoment = 0;

float maxConfigs = 5;

float roc150OEIceiling2600 = 0;
float roc150OEIceiling2900 = 0;
float roc150OEIceiling3175 = 0;
float roc150OEIceiling = 0;

int initialAC = 2;

int linePilot = 0;

int lineMCM = 0;

int flagLATinputH130;

int flagManifestOpen = 0;

// *************************************************************************************************************************************************


-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    
    return self.viewHeliCenterLabels;
    
}



// pax input ************************

BOOL changeRow;



JBSignatureController *signatureController ;
UIImageView *scrollSig;
UIImageView *scroll2Sig;

NSMutableData *pdfData;




// =/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/
// =/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/
// =/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/
// =/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/


-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}



- (BOOL)prefersStatusBarHidden {
    
    if (nvgMode == 1) {        
        return YES;
    }else{
        return NO;        
    }
}


-(void)appWillResignActive:(NSNotification*)note
{   
    //NSLog(@"1 appWillResignActive vFlightID %@", vFlightID);
    if ([vFlightID floatValue] < 1) {
        //NSLog(@"SaveValuesreturn");
        return;
    }else{
         [self SaveValues];
    }
    
    
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.    
    //NSLog(@"viewDidLoad");        
    //viewOne.transform = CGAffineTransformScale(CGAffineTransformIdentity, 2, 2);
  
    [_sliderIAS setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderRatingIndex setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderPROPRPM setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [sliderHp setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [sliderOATforOGE setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [sliderISADiff setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderNVG setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderHeadwind2 setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderMSL setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [sliderQNH setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderKIAS setMaximumTrackTintColor:[UIColor darkGrayColor]];
    
    _segmentUnitsForFuel.backgroundColor = segmentdarkGrayColor;
    _segmentUnitsForItems.backgroundColor = segmentdarkGrayColor;
    _segmentFuelVolumeOrMass.backgroundColor = segmentdarkGrayColor;
    _segmentSwapMode.backgroundColor = segmentdarkGrayColor;
    _segmentSeatLoadOptions.backgroundColor = segmentdarkGrayColor;
    _segmentNamesOnSeats.backgroundColor = segmentdarkGrayColor;
    
    
    [self didLoadInitialStartUp];
    
    _vFlightRemarks.tag = 10011;
    [_vFlightRemarks addTarget:self action:@selector(moveScrollViewItemsFlightLegData:)  forControlEvents:UIControlEventEditingDidBegin];
    _vFlightTypeField.tag = 10010;
    [_vFlightTypeField addTarget:self action:@selector(moveScrollViewItemsFlightLegData:)  forControlEvents:UIControlEventEditingDidBegin];
    
    
    _vEngineStarts1.tag = 10013;
    [_vEngineStarts1 addTarget:self action:@selector(moveScrollViewItemsFlightLegData:)  forControlEvents:UIControlEventEditingDidBegin];
    
    
        
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(resetData:) //note the ":" - should take an NSNotification as parameter
                                                 name:@"resetHelicopterData"
                                               object:nil];
}


- (void) didLoadInitialStartUp {
    
    //NSLog(@"***************** didLoadInitialStartUp *****************");
    
    UIButton *largerButton = [UIButton buttonWithType:UIButtonTypeCustom];        
    largerButton.frame     = CGRectMake( _buttonEnterQNH.frame.origin.x , _buttonEnterQNH.frame.origin.y-15, _buttonEnterQNH.frame.size.width, _buttonEnterQNH.frame.size.height + 20 );   
    [largerButton addTarget:self action:@selector(buttonActionEnterQNH:) forControlEvents:UIControlEventTouchUpInside]; 
    largerButton.backgroundColor = [UIColor clearColor];  
    [_viewSliderPA addSubview:largerButton];
    
    largerButton = [UIButton buttonWithType:UIButtonTypeCustom];        
    largerButton.frame     = CGRectMake( _buttonEnterMSLfeet.frame.origin.x , _buttonEnterMSLfeet.frame.origin.y-15, _buttonEnterMSLfeet.frame.size.width, _buttonEnterMSLfeet.frame.size.height + 20 );   
    [largerButton addTarget:self action:@selector(buttonActionEnterMSLfeet:) forControlEvents:UIControlEventTouchUpInside]; 
    largerButton.backgroundColor = [UIColor clearColor];  
    [_viewSliderPA addSubview:largerButton];
    
    largerButton = [UIButton buttonWithType:UIButtonTypeCustom];        
    largerButton.frame     = CGRectMake( buttonISA.frame.origin.x , buttonISA.frame.origin.y-15, buttonISA.frame.size.width, buttonISA.frame.size.height + 20 );   
    [largerButton addTarget:self action:@selector(buttonActionEnterISA:) forControlEvents:UIControlEventTouchUpInside]; 
    largerButton.backgroundColor = [UIColor clearColor];  
    [viewSliderISA addSubview:largerButton];
    
    largerButton = [UIButton buttonWithType:UIButtonTypeCustom];        
     largerButton.frame     = CGRectMake( buttonOAT.frame.origin.x , buttonOAT.frame.origin.y-15, buttonOAT.frame.size.width, buttonOAT.frame.size.height + 20 );   
     [largerButton addTarget:self action:@selector(buttonActionEnterOAT:) forControlEvents:UIControlEventTouchUpInside]; 
     largerButton.backgroundColor = [UIColor clearColor];  
     [_viewSliderOAT addSubview:largerButton];

    
    
    flagSpecialPHIFlightSettingPage = 0;
    _inputPHIOverrideACtype.items   =  @[ @"B407i", @"AS350B3" ];
    
    
    NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
    if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
    //NSLog(@"startup fetchAvailableProducts  userExtraCheck %@", userExtraCheck);    
    _viewPHIstartScreen.hidden = YES;
    _viewSelectACWindow.hidden = NO;
    _buttonSaveUpdateACdata.hidden = YES;

    if ([userExtraCheck rangeOfString:@"PHIspecials"].location != NSNotFound  ) {  
        flagSpecialPHIFlightSettingPage = 1;
        _viewPHIstartScreen.hidden = NO;
        UIImage *btnImg = [UIImage imageNamed:@"lock - locked-01.png"];        
        [_buttonUnlockBEWOverride setBackgroundImage:btnImg forState:UIControlStateNormal];
        _inputPHIOverrideRegistration.enabled = NO; _inputPHIOverrideRegistration.backgroundColor = [UIColor lightGrayColor];
        _inputPHIOverrideBEW.enabled = NO; _inputPHIOverrideBEW.backgroundColor = [UIColor lightGrayColor];
        _inputPHIOverrideMoment.enabled = NO; _inputPHIOverrideMoment.backgroundColor = [UIColor lightGrayColor];
        _inputPHIOverrideFuelFlow.enabled = NO; _inputPHIOverrideFuelFlow.backgroundColor = [UIColor lightGrayColor];
        _inputPHIOverrideMomentLat.enabled = NO; _inputPHIOverrideMomentLat.backgroundColor = [UIColor lightGrayColor];
        _inputPHIOverrideSledWeight.enabled = NO; _inputPHIOverrideSledWeight.backgroundColor = [UIColor lightGrayColor];
        _viewSelectACWindow.hidden = YES;
        [_viewSelectHelicopter bringSubviewToFront:_viewPHIstartScreen];
        selectedUnitForItems = @"lbs";
   
         if (([self is_online])) {
             NSString *phiDataURL = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerDataURL"]; 
             //NSLog(@"THIS IS PHI SPECIAL phiDataURL %@", phiDataURL);        
             NSURL *URL;
             NSStringEncoding encoding;
             NSError *error;
             NSString *availableACTypesURL = [ [NSString alloc] initWithFormat:@"%@%@", phiDataURL,  @"specialKey.txt" ];
             URL = [NSURL URLWithString: availableACTypesURL];
             [[NSURLCache sharedURLCache] removeAllCachedResponses];
             [[NSURLCache sharedURLCache] setDiskCapacity:0];
             [[NSURLCache sharedURLCache] setMemoryCapacity:0];
             NSString *phiKeyText = [NSString stringWithContentsOfURL:URL usedEncoding:&encoding error:&error];
             [[NSUserDefaults standardUserDefaults]  setObject: phiKeyText  forKey:@"phiKeyText"];             
             //NSLog(@"phiKeyText %@", phiKeyText); 
         }
       
        
        
    }
    
    flagTriggerSpecialCreateFlight = 0;
    
    _vReserveTimeField.items   =  @[ @"20", @"30", @"45"];
    
    [_viewFuelPanel bringSubviewToFront:_viewFuelSettings];
    [_viewFuelPanel bringSubviewToFront:_viewFuelSliders];    
    [_viewFuelPanel bringSubviewToFront:_viewSelectorButtons];
    
    _viewCGlat.backgroundColor = [UIColor blackColor];
    
   
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
           label2.font = [UIFont boldSystemFontOfSize:14];
           label2.textAlignment = NSTextAlignmentCenter;
           label2.text = @"";
           label2.tag = 121212;
           label2.backgroundColor = [UIColor orangeColor];
    [_viewHelicopterInCenter addSubview:label2];
    
    
    decimalFormatter = [[NSNumberFormatter alloc] init];
    
        
    self.scrollView.delegate = self;
    
    self.scrollView.maximumZoomScale = 3.0;
    self.scrollView.minimumZoomScale = 0.1;
    
    
    //_scrollViewHeliCenter.zoomScale = 0.5;
    //_scrollView.contentOffset = CGPointMake(0, 0);

    _switchRatioForItems.on = NO;
    _switchGuidance.on = NO;
    
    //NSLog(@"didLoadInitialStartUp");
    
    // load settings from start page
    serverUrl  = [[NSUserDefaults standardUserDefaults]  stringForKey:@"serverUrl"];
    _inputCommunicationKey.text   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"_inputCommunicationKey"];
    ACCategory  = [[NSUserDefaults standardUserDefaults]  stringForKey:@"ACCategory"];
    ACmanufacturer = [[NSUserDefaults standardUserDefaults]  stringForKey:@"ACmanufacturer"];
    AC_Type = [[NSUserDefaults standardUserDefaults]  stringForKey:@"AC_Type"];
    ACVariant = [[NSUserDefaults standardUserDefaults]  stringForKey:@"ACVariant"];
    equipListID = [[NSUserDefaults standardUserDefaults]  stringForKey:@"equipListID"];
    
        
    _segmentSwapMode.selectedSegmentIndex = 1;    
    _segmentSeatLoadOptions.selectedSegmentIndex = 1;    
    _segmentNamesOnSeats.selectedSegmentIndex = 0;    
    _segmentFlightLegMode.selectedSegmentIndex = 0;    
    selectedChartButton = 1;
    
    arrayCustomFlightDataElements = [[NSMutableArray alloc] init]; 
    legSettingsDictionary = [[NSMutableDictionary alloc] init];
    allFlightsMasterArray = [[NSMutableArray alloc] init];
    arrayInternalFlightNumber = [[NSMutableArray alloc] init];
    allLegsPerFlightArray = [[NSMutableArray alloc] init];  
    guidanceDictionary = [[NSMutableDictionary alloc] init];
    _arrayExternalLoadRestrictions = [[NSMutableArray alloc] init];
    arrayHoistRestrictions = [[NSMutableArray alloc] init];
    arrayACType= [[NSMutableArray alloc] init];
    arrayACRegistration= [[NSMutableArray alloc] init];
    arrayAvailableListIDs = [[NSMutableArray alloc] init];
    arrayBaseName = [[NSMutableArray alloc] init];
    arrayConfigurationName = [[NSMutableArray alloc] init];
    arrayPackageName = [[NSMutableArray alloc] init];
    arrayUnitseName = [[NSMutableArray alloc] init];
    arrayConfigItemName = [[NSMutableArray alloc] init];
    arrayConfigItemWeight = [[NSMutableArray alloc] init];
    arrayConfigItemArmLong = [[NSMutableArray alloc] init];
    arrayConfigItemMomLong = [[NSMutableArray alloc] init];
    arrayConfigItemArmLat = [[NSMutableArray alloc] init];
    arrayConfigItemMomLat = [[NSMutableArray alloc] init];
    arrayConfigIteminOut = [[NSMutableArray alloc] init];
    arrayConfigItemLocked = [[NSMutableArray alloc] init];
    arrayConfigItemData = [[NSMutableArray alloc] init];
    arrayConfigItemMoved = [[NSMutableArray alloc] init];    
    arrayConfigItemAltLong = [[NSMutableArray alloc] init];
    arrayConfigItemAltLat = [[NSMutableArray alloc] init];
    arrayConfigItemMovable = [[NSMutableArray alloc] init];
    arrayConfigItemTrigger = [[NSMutableArray alloc] init];    
    arrayConfigItemItemR1 = [[NSMutableArray alloc] init];
    arrayConfigItemItemR2 = [[NSMutableArray alloc] init];
    arrayConfigItemItemR3 = [[NSMutableArray alloc] init];    
    availableACTypes = [[NSMutableArray alloc] init];    
    [_scrollViewSpecialEquipList setScrollEnabled:YES];    
    [_scrollViewLegData setScrollEnabled:YES];   

    _viewSetupItems.frame = CGRectMake(0, 0, 725, 1048);
    [_scrollViewConfiguratorItems setScrollEnabled:YES];    
    [_scrollViewInteriorMaker setScrollEnabled:YES];
    
    
    arrayConfigButtons = [[NSMutableArray alloc] init];
    arrayConfigurations = [[NSMutableArray alloc] init];
    //NSLog(@"1 kill");
    _arrayName1 = [[NSMutableArray alloc] init];
    _arrayName2 = [[NSMutableArray alloc] init];
    _arrayName3 = [[NSMutableArray alloc] init];
    _arrayName4 = [[NSMutableArray alloc] init];
    _arrayName5 = [[NSMutableArray alloc] init];
    _arrayName6 = [[NSMutableArray alloc] init];
    _arrayName7 = [[NSMutableArray alloc] init];
    _arrayName8 = [[NSMutableArray alloc] init];
    _arrayName9 = [[NSMutableArray alloc] init];
    _arrayName10 = [[NSMutableArray alloc] init];
    _arrayName11 = [[NSMutableArray alloc] init];
    _arrayName12 = [[NSMutableArray alloc] init];
    _arrayName13 = [[NSMutableArray alloc] init];
    _arrayName14 = [[NSMutableArray alloc] init];
    _arrayName15 = [[NSMutableArray alloc] init];
    _arrayName16 = [[NSMutableArray alloc] init];
    _arrayName17 = [[NSMutableArray alloc] init];
    _arrayName18 = [[NSMutableArray alloc] init];
    _arrayName19 = [[NSMutableArray alloc] init];
    _arrayName20 = [[NSMutableArray alloc] init];
    _arrayName21 = [[NSMutableArray alloc] init];
    _arrayName22 = [[NSMutableArray alloc] init];
    _arrayName23 = [[NSMutableArray alloc] init];
    _arrayName24 = [[NSMutableArray alloc] init];
    _arrayName25 = [[NSMutableArray alloc] init];
    
    _bundleVersion.text =[@"Version: " stringByAppendingFormat:@"%@ ",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]];
    /*
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(6, 0, 40, 21.0)];
    label.font = [UIFont systemFontOfSize:9.0];
    label.textColor = [UIColor lightGrayColor];
    label.textAlignment = NSTextAlignmentLeft;
    label.text =[@"" stringByAppendingFormat:@"%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]];
    [viewTopTop addSubview:label];
     */
    
    
    [self prefersStatusBarHidden];    
    [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];    
    [[UITextField appearance] setKeyboardAppearance:UIKeyboardAppearanceDark];        
    _inputCommunicationKey.secureTextEntry = YES;    
    _inputCommunicationKey.keyboardType = UIKeyboardTypeDefault;    
    _inputCommunicationKey.autocorrectionType = UITextAutocorrectionTypeNo;    
    
     sliderHp.minimumValue = -1000; _sliderMSL.minimumValue = -1000;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];   
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incomingNotificationCreateFakeFlight:) name:@"noteCreateFakeFlight" object:nil]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incomingNotificationDeleteFakeFlight:) name:@"noteDeleteFakeFlight" object:nil];    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incomingNotificationFromPerformance:) name:@"noteFromPerformance" object:nil]; 
    
   
    
    // dList    
    dListClass_ = [[dList alloc] init];
    [self addChildViewController:dListClass_];    
    [dListClassView_ addSubview:dListClass_.view]; 
    dListClass_.view.frame = dListClassView_.bounds;
    [dListClass_ didMoveToParentViewController:self];
    
        
    importPerformanceDataClass_ = [[importPerformanceData alloc] init];
    [self addChildViewController:importPerformanceDataClass_];    
    [importPerformanceDataClassView_ addSubview:importPerformanceDataClass_.view];
    importPerformanceDataClass_.view.frame = importPerformanceDataClassView_.bounds;
    [importPerformanceDataClass_ didMoveToParentViewController:self];
    
    
    // calc perf class    
    calculatePerformanceClass_ = [[calcPerfClass alloc] init];
    [self addChildViewController:calculatePerformanceClass_];    
    [calculatePerformanceClassView_ addSubview:calculatePerformanceClass_.view];
    calculatePerformanceClass_.view.frame = calculatePerformanceClassView_.bounds;
    [calculatePerformanceClass_ didMoveToParentViewController:self];
    
    // Fleet Manager Class
    fleetManagerClass_ = [[FleetManager alloc] init];
    [self addChildViewController:fleetManagerClass_];    
    [fleetManagerClassView_ addSubview:fleetManagerClass_.view]; 
    fleetManagerClass_.view.frame = fleetManagerClassView_.bounds;
    [fleetManagerClass_ didMoveToParentViewController:self];
   
    
    
    // shadow
    //dListClassView_.layer.masksToBounds = NO;
    //dListClassView_.layer.shadowOffset = CGSizeMake(0, 0);
    //dListClassView_.layer.shadowRadius = 10;
    //dListClassView_.layer.shadowOpacity = 0.5;
    
    
    
    [EquipPackagesManager initializeWithMaxConfigs:maxConfigs];
    
    packagesTotalsController_ = [[UIStoryboard storyboardWithName:@"MedicalList" bundle:nil] instantiateViewControllerWithIdentifier:@"packagesTotals"];
    [packagesTotalsController_ willMoveToParentViewController:self];
    [self addChildViewController:packagesTotalsController_];
    [packagesTotalsView_ addSubview:packagesTotalsController_.view];
    packagesTotalsController_.view.frame = packagesTotalsView_.bounds;
    
    
    
    EquipmentViewController* controller = [[UIStoryboard storyboardWithName:@"MedicalList" bundle:nil] instantiateViewControllerWithIdentifier:@"medicalListController"];   // VD
    controller.equipmentPackages = [self currentFlightEquipmentPackage];
    
    [controller.equipmentPackages setWeightUnits:YES]; // VD set to LBS (LBS=NO, KG=YES)
    
    
    
    serverpath_alternate        = @"http://testserver.gyronimosystems.com/manager/webservice_";
    serverpath_new_alternate    = @"http://testserver.gyronimosystems.com/api/default/";
    serverhost_alternate        = @"gyronimo.kulanaserver.com";
    
    serverpath_standard         = @"http://gyronimo.kulanaserver.com/manager/webservice_";
    serverpath_new_standard     = @"http://gyronimo.kulanaserver.com/api/default/";
    serverhost_standard         = @"gyronimo.kulanaserver.com";
    
    
    
   
    
    _switchAdjustACTopView.on = NO; 
    buttonRed = [UIImage imageNamed:@"button_red.png"];    
    buttonGrey = [UIImage imageNamed:@"button grey top184x52.png"];    
    buttonBlue = [UIImage imageNamed:@"button blue top184x52.png"];
    
    
    // performance ******** performance******** performance******** performance******** performance******** performance******** performance
    
    [_scrollViewUniversalButtons setScrollEnabled:YES];
    [_scrollViewUniversalButtons setContentSize:CGSizeMake(_viewUniversalButtons.frame.size.width, _viewUniversalButtons.frame.size.height)];
    
    
    perfButtonChartNames = [[NSMutableArray alloc] init];
    perfButtonUserNames = [[NSMutableArray alloc] init];
    
    buttonChartNamesToProcess = [[NSMutableArray alloc] init];
    
    
    UITapGestureRecognizer *singleTapRecognizer = [[UITapGestureRecognizer alloc]
                                                   initWithTarget: self
                                                   action:@selector(handleSingleTapOnCGEnvelope:)];
    [singleTapRecognizer setNumberOfTouchesRequired:1];
    [_viewCGLong addGestureRecognizer: singleTapRecognizer];
    
    singleTapRecognizer = [[UITapGestureRecognizer alloc]
                           initWithTarget: self
                           action:@selector(handleSingleTapOnCGEnvelopeLat:)];
    [singleTapRecognizer setNumberOfTouchesRequired:1];
    [_viewCGlat addGestureRecognizer: singleTapRecognizer];
   
    
    panRecognizerForGhost = [[UIPanGestureRecognizer alloc]
                             initWithTarget:self
                             action:@selector(panRecognizerAction:)];
    
    [[self viewInterior] addGestureRecognizer:panRecognizerForGhost];
    
    panRecognizerForEquipment = [[UIPanGestureRecognizer alloc]
                                 initWithTarget:self
                                 action:@selector(panRecognizerEquipmentAction:)];

    
    
    [viewLoadManifest bringSubviewToFront: ScrollViewManifest]; [viewLoadManifest bringSubviewToFront: _buttonmanifest]; [viewLoadManifest bringSubviewToFront: _viewManifestLowerButtons];
    ScrollViewManifest.frame = CGRectMake(0, -2, 1024, 694);
    
    [_viewPowerCheck bringSubviewToFront: _ScrollViewPowerCheck]; [_viewPowerCheck bringSubviewToFront: _viewPoweCheckButtons];   [_viewPowerCheck bringSubviewToFront: _buttonClosePowerCheck];
    [_ScrollViewPowerCheck bringSubviewToFront: _logoPowerCheck];
    _viewPowerCheck.frame = CGRectMake(0, -2, 1024, 694);    
    
    _viewStationsWindow.hidden = NO; [viewOne bringSubviewToFront: _viewStationsWindow];
    crew_sectioned = [[NSMutableArray alloc] init];
    crew_types = [[NSMutableArray alloc] init];
    locations = [[NSMutableArray alloc] init];
    dispatcherFlights = [[NSMutableArray alloc] init];
    dispatcherPaxNames = [[NSMutableArray alloc] init];
    dispatcherPaxWeight = [[NSMutableArray alloc] init];
    dispatcherCrewNames= [[NSMutableArray alloc] init];
    dispatcherCrewWeight = [[NSMutableArray alloc] init];
    
    [_scrollViewConfigurations setScrollEnabled:YES];
    [_scrollViewHeliCenter setScrollEnabled:YES];    
    [_scrollViewHeliCenter scrollRectToVisible:CGRectMake(376, 1186, 376, 600) animated:YES];
    switchWarnings.on = YES;
    warningsOnOff = 1;
    signatureController = [[ JBSignatureController  alloc] init];
    [ _viewSignature addSubview:signatureController.view];    
    _viewChangeSelectedEntry.hidden = YES;  _viewEditPilotList.hidden = YES; _viewPilotList.hidden = YES;    
    self.tableViewDataName = [NSMutableArray arrayWithCapacity:10];
    self.tableViewDataWeight = [NSMutableArray arrayWithCapacity:10];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    changeRow = NO;
    [viewMain bringSubviewToFront:_viewHelicopterInCenter];    
    [viewMain bringSubviewToFront:_viewFuelPanel];
    [viewOne bringSubviewToFront:_viewConfigurations];
    
    
    // hide views hideviews
    
    //_viewHVdata.hidden = YES;
    _viewAddEquipmentItem.hidden = YES;
    _labelEquipWarningMessage.hidden = YES;
    _viewEquipmentListOverManifest.hidden = YES;
    _viewAddStation.hidden = YES;
    _viewGenericACaccess.hidden = YES;
    _labelNotePlanMode.hidden = YES;
    _viewButtonAutoCalcMode.hidden = YES;
    _viewOverrideBEWData.hidden = YES;   
    _buttonRefreshInterior.hidden = YES;    
    _scrollViewConfiguratorItems.hidden = NO;    
    _scrollViewInteriorMaker.hidden = YES;    
    _viewFleetManager.hidden = YES;
    _viewLoadDataFleetManager.hidden = YES;    
    _viewLoadingData.hidden = YES;    
    _viewEquipmentOnHeli.hidden = YES;    
    _viewPowerCheck.hidden = YES;    
    _viewImportPerformanceData.hidden = YES;
    _warningHoistDAPA.hidden = YES;    
    _viewStationOptionsList.hidden = YES;    
    _viewConfigurator.hidden = YES;    
    _viewACViewSettings.hidden = YES;    
    _viewSummaryManifest.hidden = YES;    
    _viewLegData.hidden = YES;    
    _viewFlightManager.hidden = YES;    
    _viewDispatch.hidden = YES;    
    _labelAvailableExternalLoad.hidden = YES;    
    _viewSpecialEquiplist.hidden = YES;    
    _viewAltimetry.hidden = YES;    
    _viewDatePicker.hidden = YES;    
    _viewDlist.hidden = YES;    
    _viewSelectServer.hidden = YES;    
    viewLoadManifest.hidden = YES;  viewSliderISA.hidden = YES;    
    _viewConfigurations.hidden = YES;    
    viewEnvironment.hidden = YES;    
    enterPad.hidden = YES;    
    viewSetup.hidden = YES;    
    _viewSignature.hidden = YES;    
    _viewSelectHelicopter.hidden = YES;
    
    
    
    
    // scroll view
    
    [ScrollViewManifest setScrollEnabled:YES];
    [ScrollViewManifest setContentSize:CGSizeMake(644, 1800)];
    [ScrollViewManifest scrollRectToVisible:CGRectMake(0, 0, 644, 635) animated:YES];    
    [_scrollViewSummaryManifest setScrollEnabled:YES];    
    
    UIImage *sliderImage = [UIImage imageNamed:@"sliderEmpty.png"];    
    UIImage *sliderThumb = [UIImage imageNamed:@"triangle3.png"];
        
    [sliderOATforOGE setMaximumTrackImage:sliderImage forState:UIControlStateNormal];
    [sliderOATforOGE setMinimumTrackImage:sliderImage forState:UIControlStateNormal];
    [sliderOATforOGE setThumbImage:sliderThumb forState:UIControlStateNormal];
    
    [sliderHp setMaximumTrackImage:sliderImage forState:UIControlStateNormal];
    [sliderHp setMinimumTrackImage:sliderImage forState:UIControlStateNormal];
    [sliderHp setThumbImage:sliderThumb forState:UIControlStateNormal];
    
    [sliderISADiff setMaximumTrackImage:sliderImage forState:UIControlStateNormal];
    [sliderISADiff setMinimumTrackImage:sliderImage forState:UIControlStateNormal];
    [sliderISADiff setThumbImage:sliderThumb forState:UIControlStateNormal];
    
    // hide warnings       
    warningAS355Pax5.hidden = YES; warningWeightLimitExceeded.hidden = YES; warningCGoutsideEnvelope.hidden = YES; warningLatCGExceeded.hidden = YES;    
    
    // check if here for the first time:    
    // load aircraft number
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];    
    MBpagevisit = [defaults  floatForKey: @"MBpagevisit"];    
    //NSLog (@"*********** starting MBpagevisit %@ ", [ [NSString alloc] initWithFormat:@"%.0f ", MBpagevisit]);
  
    
    NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];
    
 
    if (MBpagevisit < 10 ) { // first start  - wirklich 
        
        //[[NSUserDefaults standardUserDefaults]  setObject:@""        forKey:@"purchasedProductID"];
        
        //NSLog(@"MBpagevisit triggerSetDefaultsForPerformanceCharts %d  ", triggerSetDefaultsForPerformanceCharts);
    
        _buttonCreateNewPHIFlight.hidden = NO;
        _buttonPHIchangeBackToOriginalFormC.hidden = YES;
        _buttonPHIcancelCreateFlight.hidden = YES;
        
        [[NSUserDefaults standardUserDefaults]  setObject:@"None" forKey:@"purchasedPlan"];        
        _buttonCancelSelectAC.hidden = YES;        
              
        [allFlightsMasterArray removeAllObjects];
        [allFlightsMasterArray addObject:@"-"];
        [self addInternalFlightNumber];
        [[NSUserDefaults standardUserDefaults]  setObject: allFlightsMasterArray  forKey:@"allFlightsMasterArray"];
       
       


        [allLegsPerFlightArray addObject:@"-"];
        [[NSUserDefaults standardUserDefaults]  setObject: allLegsPerFlightArray  forKey:@"allLegsPerFlightArray"];
        
        serverpath= serverpath_standard;
        serverpath_new= serverpath_new_standard;
        serverhost= serverhost_standard;        
        _labelServer.text = @"Standard Server";                
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];        
        [defaults  setObject: _labelServer.text                     forKey:@"_labelServer"];
        
             
        importPerformanceData *_importPerformanceData = [[importPerformanceData alloc]init];
      
        
        vLegID = @"0";
        vFlightID = @"0";
        
        [arrayInternalFlightNumber removeAllObjects];
        [arrayInternalFlightNumber addObject:vFlightID];
        [[NSUserDefaults standardUserDefaults]  setObject: arrayInternalFlightNumber  forKey:@"arrayInternalFlightNumber"];
        
        
        // prepare the arrayDictAllAircraft        
        if ([customerFolderName isEqualToString:@"Test User"] || [customerFolderName isEqualToString:@"Apple"] || [customerFolderName isEqualToString:@"Tester"]) {            
            [_importPerformanceData loadAvailableACTypesArrayFromDisk];
            
            //tu557821
            
        }else if ([customerFolderName isEqualToString:@"noAccount"] ) { 
             //[_importPerformanceData loadAvailableACTypesArrayFromDisk];
          
            
        } else{
            
            NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
            if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
            //NSLog(@"startup fetchAvailableProducts  userExtraCheck %@", userExtraCheck);       
            if ([userExtraCheck rangeOfString:@"flightSchoolPackage"].location != NSNotFound  ) {  
                
            }else{
                
               
                [_importPerformanceData loadAvailableACTypesArrayFromFleetControl];   
            }
            
                     
        }
        
        
        
        if ([customerFolderName isEqualToString:@"noAccount"]  ) {
            
        }else{
            availableACTypes = [[[NSUserDefaults standardUserDefaults] objectForKey:@"availableACTypesArray"] mutableCopy];
            //NSLog (@"1111 loaded availableACTypes %@", availableACTypes);
            [self loadHelicoptersFromServerVoid];        
            fleetManagerClass_ = [[FleetManager alloc] init];         
            ACCategory = [[NSUserDefaults standardUserDefaults] objectForKey:@"ACCategory"];
            ACmanufacturer = [[NSUserDefaults standardUserDefaults] objectForKey:@"ACmanufacturer"];
            AC_Type = [[NSUserDefaults standardUserDefaults] objectForKey:@"AC_Type"];
            ACVariant = [[NSUserDefaults standardUserDefaults] objectForKey:@"ACVariant"];
            equipListID = [[NSUserDefaults standardUserDefaults] objectForKey:@"equipListID"];
            
            
        }
        
        
        
        
        vFlightRegistration.text = [defaults  stringForKey:@"initialAcReg"];        
        AC_Type  = [defaults  stringForKey:@"initialAC_Type"];
  
        if (flagSpecialPHIFlightSettingPage == 1) {
            vFlightRegistration.text = _inputPHIOverrideRegistration.text;
        }
        
      
        flagMakeNewFlgtNow = 1;
      
        
        
        //******************************************************************************************************************************

        
        vLegID = @"0";
        vFlightID = @"0";
        
        
        
        NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
        if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
        //NSLog(@"startup fetchAvailableProducts  userExtraCheck %@", userExtraCheck);       
        
        if ([userExtraCheck rangeOfString:@"flightSchoolPackage"].location != NSNotFound  ) {  
            
            
            if ([userExtraCheck rangeOfString:@"freeOfCharge"].location != NSNotFound  ) {  
                
                [_importPerformanceData loadAvailableACTypesArrayFromFleetControl];   
                
                [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightSchoolPackALL"        forKey:@"purchasedProductID"];
                displayWindow = 99;
                _viewFleetManager.hidden = NO;
                [viewOne bringSubviewToFront:_viewFleetManager];  
                
                /*
                NSNotification *myNotification = [NSNotification notificationWithName:@"notificationLoadFleetForFlightSchool"
                                                                               object:self //object is usually the object posting the notification
                                                                             userInfo:nil]; //userInfo is an optional dictionary
                
                //Post it to the default notification center
                [[NSNotificationCenter defaultCenter] postNotification:myNotification];
                 */
                
                
                
            }else{
                //NSLog(@"is flightSchoolPackageflightSchoolPackage");
                displayWindow = 99;
                _viewFleetManager.hidden = NO;
                [viewOne bringSubviewToFront:_viewFleetManager];  
                NSNotification *myNotification = [NSNotification notificationWithName:@"notificationViewPurchase"
                                                                               object:self //object is usually the object posting the notification
                                                                             userInfo:nil]; //userInfo is an optional dictionary
                
                //Post it to the default notification center
                [[NSNotificationCenter defaultCenter] postNotification:myNotification];
                
                
            }
           
            
            
            
        }else{
            if ([customerFolderName isEqualToString:@"noAccount"] ) {             
                displayWindow = 99;
                _viewFleetManager.hidden = NO;
                [viewOne bringSubviewToFront:_viewFleetManager];            
            }else{            
                // preload crewlist!    
                [self loadLocationsFromServer];      
                UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                [aButton setTag:0];      
                [self loadCrewFromServer:aButton]; 
                // open up flight manager
                displayWindow = 12;
                [self checkButtonFlight];
                [buttonDisplayFlight setImage:buttonBlue forState:UIControlStateNormal];
                _viewSelectHelicopter.hidden = NO; [viewOne bringSubviewToFront:_viewSelectHelicopter];            
            }
            
        }
        
        
        
        

        
    }else {
        
        //NSLog (@"start 2");        
        //NSLog (@"hello again! started second time");        
        _buttonCancelSelectAC.hidden = NO;        
        //  ************************************************************************************
        
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        _labelServer.text = [defaults  stringForKey:@"_labelServer"];        
        _inputCommunicationKey.text = [defaults  stringForKey:@"_inputCommunicationKey"];
        customer = [defaults  stringForKey:@"customer"];
                
        
        if ([_labelServer.text isEqualToString:@"Alternate Server"] ) {
            // Alternate Server
            serverpath      = serverpath_alternate;
            serverpath_new  = serverpath_alternate;
            serverhost      = serverhost_alternate;
        }else{
            // Standard Server
            serverpath      = serverpath_standard;
            serverpath_new  = serverpath_new_standard;
            serverhost      = serverhost_standard;
        }
        
        //  ************************************************************************************'
        
       _buttonCreateNewPHIFlight.hidden = YES;
       _buttonPHIchangeBackToOriginalFormC.hidden = YES;
       _buttonPHIcancelCreateFlight.hidden = YES;
        
        vLegID = @"1";
        vFlightID =@"1";
        [self LoadValues]; // get bew
        [self makeConfigButtons];
      
        [self addPerformanceButtons];
        
        
        displayWindow = 0;
        [self displayWindows];
        
    }
  
    
    _buttonUpdateAircraftList.hidden = NO;
 
    
    
    
    // NVG safety
    if ([defaults  floatForKey:@"_sliderNVG"] > 85) {
        _sliderNVG.value = 80;
        [defaults  setFloat: _sliderNVG.value    forKey:@"_sliderNVG"];
    }

    
}

- (void)resetData:(NSNotification *)notification
{
    //NSLog(@"Reacting to notification %@ from object %@ with userInfo %@", notification, notification.object, notification.userInfo);
    [viewSetup setHidden:true];
    [self didLoadInitialStartUp];
    [self loadHelicoptersFromServerVoid];
}

// =/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/
// =/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/
// =/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/
// =/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/








//Dennis START
//Dennis START



//---------------- Packages.txt Import/Export START-----------




- (IBAction)buttonActionViewEquipmentList:(id)sender {
    
    // VD
    EquipmentViewController* controller = [[UIStoryboard storyboardWithName:@"MedicalList" bundle:nil] instantiateViewControllerWithIdentifier:@"medicalListController"];   // VD
    controller.equipmentPackages = [self currentFlightEquipmentPackage];
    // VD
    [controller.equipmentPackages setWeightUnits:YES];
    [self presentViewController:controller animated:YES completion:nil]; // VD
    __block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"EquipmentControllerDismissed" object:nil queue:nil usingBlock:^(NSNotification *note) {
        [[NSNotificationCenter defaultCenter] removeObserver:observer];
        [self MainRoutine];
    }];    
    
    
}












//---------------- Packages.txt Import/Export END-----------




- (void)loadCrewFromServer:(UIButton*)sender {
    
    //Check if server reachable
    
    if (!([self is_online])) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Error"
                              message:@"Cannot reach server. Please check if this device is online."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        
    } else {
        
        // get location from button clicked
        NSString *locationName=@"";
        NSString *locationCode=@"";
        locationCode=[[locations objectAtIndex:sender.tag]locationCode];
        locationName=[[locations objectAtIndex:sender.tag]locationName];
        //        locationCode = @"base1";
        //
        //        locationName = @"base1";        
        crew_lastLocation=locationCode;
        // send request to server
        //NSLog(@"loadCrewFromServer customer %@",customer);
        NSString *url=serverpath;
        url = [url stringByAppendingString:@"get_crew.php?customer="];
        url = [url stringByAppendingString:customer];
        url = [url stringByAppendingString:@"&location="];
        
        if (flagSpecialPHIFlightSettingPage == 1) {
             url=@"https://api.phiairmedical.com/0.1/CrewList/";
        }
        
        url = [url stringByAppendingString:locationCode];
                
        //NSLog(@"url: %@",url);        
        NSData* data = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString: url]];
        __autoreleasing NSError* error = nil;
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        
        //check if JSON data valid        
        if (error != nil) {
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Error [02]"
                                  message:@"Received data that is not valid. Please contact administrator."
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            //NSLog(@"%@",error);
        } else {
            
            //create crew objects            
            [crew_sectioned removeAllObjects];
            [crew_types removeAllObjects];
            NSArray *allItems = [result objectForKey:@"crewData"];
            NSArray *allTypes = [result objectForKey:@"crewTypes"];            
            
            for (int i=0; i<allTypes.count; ++i) {
                NSDictionary *item = [allTypes objectAtIndex:i];
                NSString *crewType =[item objectForKey:@"crewType"];                
                [crew_types addObject:crewType];
            }
    
            
            NSString *currentType=@"";
            int currentTypeID=-1;
            
            for (int i=0; i<allItems.count; ++i) {
                NSDictionary *item = [allItems objectAtIndex:i];
                NSString *TheName=[item objectForKey:@"name"];
                NSString *TheInitial=[item objectForKey:@"initial"];
                NSString *TheCrewtype=[item objectForKey:@"crewType"];
                NSString *TheStatus=[item objectForKey:@"status"];                
                
                NSString *TheEMPnumber=[item objectForKey:@"emp"];
                
                double WeightValue = 0;
                WeightValue = ([[item objectForKey:@"weight"]doubleValue] );
                NSString *TheWeight = [NSString stringWithFormat:@"%f",WeightValue];
            
                
                // crew is sorted by crewType
                // so we put all crew objects into array crew_sectioned
                // crew_sectioned[0] could be for objects with crewtype PIC
                // and crew_sectioned[1] could be for objects with crewtype PAR
                //if we find a new crewtype we create a new element in crew_sectioned array
                
                if ([currentType isEqualToString:TheCrewtype]) {
                    [[crew_sectioned objectAtIndex:currentTypeID] addObject:[[crewPerson alloc] initWithName:TheName AndInitial:TheInitial
                                                                                                 AndCrewtype:TheCrewtype AndStatus:TheStatus AndWeight:TheWeight  AndEMPnumber:TheEMPnumber   ]];
                } else {
                    currentTypeID+=1;
                    currentType=TheCrewtype;
                    NSMutableArray *temp = [[NSMutableArray alloc] init];
                    [crew_sectioned insertObject:temp atIndex:currentTypeID];
                    [[crew_sectioned objectAtIndex:currentTypeID] addObject:[[crewPerson alloc] initWithName:TheName AndInitial:TheInitial
                                                                                                 AndCrewtype:TheCrewtype AndStatus:TheStatus AndWeight:TheWeight AndEMPnumber:TheEMPnumber]];
                }
                
                
            }
         
            allItems = [result objectForKey:@"updateData"];
            NSDictionary *item = [allItems objectAtIndex:0];
            lastupdate_crew=[item objectForKey:@"lastUpdate"];
            
            
            CrewDataLoaded = 1;            
            NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];            
            [defaults  setFloat: CrewDataLoaded                     forKey:@"CrewDataLoaded"];            
            [self.tableView reloadData];            
            _viewEditPilotList.hidden = YES;            
            //[self SaveValues];
            
        }
    }
    
   
}

- (void) addLocationButtons {
    
    //NSLog (@"addLocationButtons ");  
    //we create one button per location dynamically in our scrollview
    
    int xCoord=0;
    int yCoord=0;
    int buttonWidth=200;
    int buttonHeight=50;
    int buffer = 10;
    
    
    //we take the locations that are already in our locations array
    
    for(UIView *subview in [crew_locations_sview subviews]) {
        [subview removeFromSuperview];
    }
    
    
    for(int i=0; i<locations.count; i++) {
        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        aButton.frame     = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
        [aButton setTitle:[[locations objectAtIndex:i]locationName] forState:(UIControlStateNormal)];
        [aButton setTag:i];
        [aButton addTarget:self action:@selector(loadCrewFromServer:) forControlEvents:UIControlEventTouchUpInside];
        [crew_locations_sview addSubview:aButton];
        
        aButton.tintColor = [UIColor whiteColor];
        
        aButton.titleLabel.font = [UIFont systemFontOfSize:18];
        
        
        
        yCoord += buttonHeight + buffer;
        
    }
    
    
    [crew_locations_sview setContentSize:CGSizeMake(200, yCoord)];
    [crew_locations_sview setScrollEnabled:YES];
    [crew_locations_sview setNeedsDisplay];
    
    
}

- (void) addHelicopterButtons {
    
    //NSLog (@"addHelicopterButtons availableACTypes %@", availableACTypes);  
    availableACTypes = [[[NSUserDefaults standardUserDefaults] objectForKey:@"availableACTypesArray"] mutableCopy];
    
    
    NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"];
    if (dedicatedCustomerData.length < 2) {
        dedicatedCustomerData = @"";
    }  
    _buttonShowHideEquipmentListPage.hidden = YES;
    if ([dedicatedCustomerData rangeOfString:@"enableBEWoverride"].location != NSNotFound  ) {   
         _viewOverrideBEWData.hidden = NO;
         _viewSelectACWindow.frame = CGRectMake(0, 275, 1040, 525);
         _viewOverrideBEWData.frame = CGRectMake(0, 0, 1040, 285);
         [_viewSelectHelicopter bringSubviewToFront:_viewOverrideBEWData];
        
        
    }else{
        _viewOverrideBEWData.hidden = YES;
        _viewPHIstartScreen.hidden = YES;
        _viewSelectACWindow.frame = CGRectMake(0, 150, 1040, 525);        
    }

    if (flagSpecialPHIFlightSettingPage == 1) {
        _viewOverrideBEWData.hidden = YES; 
        _viewSelectACWindow.frame = CGRectMake(0, 150, 1040, 525); 
        [_viewSelectHelicopter bringSubviewToFront:_viewPHIstartScreen];
    }
   
    
    for (UIView *subview in helicopter_sview.subviews) {
        [subview removeFromSuperview];
    }
    
    //we create buttons for each helicopter callsign
    
    int xCoord=65;
    int yCoord=14;
    int buttonWidth=190;
    int buttonHeight=45;
    int buffer = 66;
 
    
    //the helicopters array contains all helicopter objects that came from the server
    
    
    int acPositionInList = 0;
    
    //NSLog (@"helicopters count %d", helicopters.count);
    
     arrayDictAllAircraft = [[NSMutableArray alloc] init]; 
     arrayDictAllAircraft = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"] mutableCopy];    
    //NSLog (@"arrayDictAllAircraft count %lu", (unsigned long)arrayDictAllAircraft.count);
    
    //NSLog (@"addHelicopterButtons arrayDictAllAircraft %@ ",arrayDictAllAircraft);
          
  
           
     for (int i=0; i<arrayDictAllAircraft.count; i++) {
         
         if (flagShowOnlySameACType == 1) {
             //NSLog (@"check %@ ", [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"]);
             if ([[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"] isEqualToString:AC_Type]) {
                 //NSLog (@"ok AC Type is same as current so we can show it");
             }else{
                 //NSLog (@"AC type is different so we can not show it");
                 continue;
             }
         }
         
         
         if (flagSpecialPHIFlightSettingPage == 1) {
             if ([[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"] isEqualToString:_inputPHIOverrideACtype.text]) {
                 //NSLog (@"ok AC Type is same as current so we can show it");
             }else{
                 //NSLog (@"AC type is different so we can not show it");
                 continue;
             }
         }
         
         if (![availableACTypes containsObject:  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"] ]) {
             //NSLog (@"this aircraft is in Fleet Control but not authorized for this app -%@-",[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"] );             
         }else{
             UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
             aButton.frame     = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
             //NSString *callsignAndType = [NSString stringWithFormat:@"%@: %@", current.typeM, current.callsign];
             NSString *callsignAndType = [NSString stringWithFormat:@" %@",  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Callsign"] ];             
             //NSLog (@"making callsign %@", [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Callsign"] );
             [aButton setTitle:callsignAndType  forState:(UIControlStateNormal)];
             [aButton setTag:i];
             [aButton addTarget:self action:@selector(buttSelHeli:) forControlEvents:UIControlEventTouchUpInside];         
             aButton.tintColor = [UIColor whiteColor];
             aButton.showsTouchWhenHighlighted = YES;
             aButton.titleLabel.font = [UIFont systemFontOfSize:18];
             UIImage *buttonBack = [UIImage imageNamed:@"button generic blue.png"];
             [aButton setBackgroundImage:buttonBack forState:UIControlStateNormal];
             [helicopter_sview addSubview:aButton];
             
             UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xCoord, yCoord+28, buttonWidth, buttonHeight)];
             label.font = [UIFont systemFontOfSize:15];
             label.textAlignment = NSTextAlignmentCenter;
             label.textColor = [UIColor whiteColor];         
             [label  setText: [NSString stringWithFormat:@"%@",  [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"]  ]  ];
             [helicopter_sview addSubview: label];
             if ((acPositionInList%2)!=0) {
                 xCoord=65;
                 yCoord += buffer;                 
             } else {
                 xCoord=270;
             } 
             acPositionInList +=1;
         }
     }
    
   
    
    [helicopter_sview setContentSize:CGSizeMake(432, yCoord +100)];
    [helicopter_sview setScrollEnabled:YES];
    
    
    
    
}

- (bool)is_online {
    
    int serverOnline = 0;
    
    //check if server is reachable / device is online
    //Reachability *r = [Reachability reachabilityWithHostName:@"gyronimo.kulanaserver.com"];
    Reachability *r = [Reachability reachabilityWithHostName:@"gyronimo.online"]; 
    NetworkStatus internetStatus = [r currentReachabilityStatus];
    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
        //NSLog(@"1 check is_online false");
        
    } else {
              
        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;
    }
    
    
}

- (void)loadLocationsFromServer {
    
    //NSLog(@"1 loadLocationsFromServer customer %@",customer);    
    //send a request to server to get all locations of this customer
    
    NSString *url=serverpath;
    url = [url stringByAppendingString:@"get_locations.php?customer="];
    
    if (flagSpecialPHIFlightSettingPage == 1) {
        url=@"https://api.phiairmedical.com/0.1/BaseList/";
    }
    
    url = [url stringByAppendingString:customer];
    NSData* data = [NSData dataWithContentsOfURL:
                    [NSURL URLWithString: url]];
    __autoreleasing NSError* error = nil;
    
    
    //NSLog(@"url %@",url);    
    //NSLog(@"data %@",url);
    
    id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    
    //check if JSON data is valid
    
    if (error != nil) {
        
        //NSLog(@"%@",error);
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Error [01]"
                              message:@"Received data that is not valid. Please contact administrator."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    } else {
        
        _viewEditPilotList.hidden = NO; // mklist
        
        
        
        [locations removeAllObjects];
        
        NSArray *allItems = [result objectForKey:@"locationData"];
        
        
        
        //put locations into global locations object array
        
        for (int i=0; i<allItems.count; ++i) {
            
            
            NSDictionary *item = [allItems objectAtIndex:i];
            NSString *TheLocationCode=[item objectForKey:@"location"];
            NSString *TheLocationName=[item objectForKey:@"locationName"];
            
            [locations addObject:[[location alloc] initWithLocationCode:TheLocationCode AndLocationName:TheLocationName]];
            
            
        }
        
        //create button for each location
        
        [self addLocationButtons];
       
        
    }
    
    
}






- (IBAction)actionConnectButton:(id)sender {
    
    // this is the "Connect" button
    
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    [defaults  setObject: _inputCommunicationKey.text                     forKey:@"_inputCommunicationKey"];
    
    
    [self.view endEditing:TRUE];
    
    
    
    
    [self loadHelicoptersFromServerVoid];
    
}

- (IBAction)actionUpdateAircraftList:(id)sender {
    //[self loadHelicoptersFromServerVoid];
     //NSLog(@"actionUpdateAircraftList   ");
    [self checkForUpdates_Helicopter];
   
}


- (void) updateAircraftData {
    
    //NSLog(@"updateAircraftData   ");
    importPerformanceData *_importPerformanceData = [[importPerformanceData alloc]init];
    [_importPerformanceData loadAvailableACTypesArrayFromFleetControl];
    [self loadHelicoptersFromFleetControl];
      
    
}


- (void)loadHelicoptersFromServerVoid {
    
    //NSLog(@"loadHelicoptersFromServerVoid  !!!!!!");
    
    
     //check if online
    
    _inputCommunicationKey.text   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"_inputCommunicationKey"];
    //NSLog(@"_inputCommunicationKey  %@", _inputCommunicationKey.text);
    
    
    
    if ([self is_online]) {
        NSString *url=serverpath;
        //NSLog(@"serverpath %@ ", serverpath);
        url = [url stringByAppendingString:@"get_codecheck.php?code="];
        url = [url stringByAppendingString:_inputCommunicationKey.text];        
        NSData* data = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString: url]];
        __autoreleasing NSError* error = nil;        
        id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        
        
        if (error != nil) {
            //NSLog(@"JSON error.");
        } else {           
            NSArray *allItems = [result objectForKey:@"check"];
            NSDictionary *item = [allItems objectAtIndex:0];            
            if (!([[item objectForKey:@"result"] isEqualToString:@"OK"])) {
                //NOT SUCCESSFULL - AlertView
                UIAlertView *alert = [[UIAlertView alloc]
                                      initWithTitle:@"FleetControl™"
                                      message:@"The code you entered is not valid."
                                      delegate:self
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil, nil];
                
                NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
                
                customer = @"";
                [defaults  setObject:customer                    forKey:@"customer"];  // here we set the customer no zero *********************                                
                [alert show];
            } else {
                customer=[item objectForKey:@"customer"];
                //NSLog(@"2loadHelicoptersFromServerVoid  customer object =  %@",customer);
                NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];                
                [defaults  setObject:customer                    forKey:@"customer"];  // here we set the customer *********************   
                
                
                
                if (flagCheckForAvailableAircrafts == 1) {                
                    flagCheckForAvailableAircrafts = 0;
                    [self checkAvailabaleAircraftInFleetControl];
                }else{                  
                    [self loadHelicoptersFromFleetControl];
                    
                }
                
                
                
               
                
            }
            
        }
    } else {        
        
        //NSLog(@"Device offline.");        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Can not update Helicopter Data!"
                              message:@"Device Offline"
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        
        [alert show];
        
        
        
    }
    
    
}


- (void) checkForUpdates_HelicopterSilent {
    
    //check if online
    
    if ([self is_online]) {
        //send request to server to get lastupdate data as json data
        NSString *url=serverpath;
        url = [url stringByAppendingString:@"get_lastupdate_heli.php?customer="];
        url = [url stringByAppendingString:customer];
        NSData* data = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString: url]];
        __autoreleasing NSError* error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        
        //check if json data is valid
        if (error != nil) {
            
        } else {
            //compare timestamps
            NSArray *allItems = [result objectForKey:@"updateData"];
            //NSLog(@"%i",allItems.count);
            NSDictionary *item = [allItems objectAtIndex:0];            
            
            if (!([[item objectForKey:@"lastUpdate"] isEqualToString:lastupdate_helicopters])) {
                alertFlag = 8;            
                UIAlertView *alert = [[UIAlertView alloc]
                                      
                                      initWithTitle:@"Update Available"                                  
                                      message:@"There is an update available. Please make sure you have a stable online connection, then select 'Update Now', or check back later on."                                  
                                      delegate:self                                  
                                      cancelButtonTitle: @"Cancel"                                  
                                      otherButtonTitles:@"Update Now", nil];            
                [alert show];
            } 
        }
    }
    
}



- (void) checkForUpdates_Helicopter {
    
    //check if online
    
    if ([self is_online]) {
        //send request to server to get lastupdate data as json data
        NSString *url=serverpath;
        url = [url stringByAppendingString:@"get_lastupdate_heli.php?customer="];
        url = [url stringByAppendingString:customer];
        NSData* data = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString: url]];
        __autoreleasing NSError* error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        
        //check if json data is valid
        if (error != nil) {
            
        } else {
            //compare timestamps
            NSArray *allItems = [result objectForKey:@"updateData"];
            //NSLog(@"%i",allItems.count);
            NSDictionary *item = [allItems objectAtIndex:0];            
            
            if (!([[item objectForKey:@"lastUpdate"] isEqualToString:lastupdate_helicopters])) {
                alertFlag = 8;            
                UIAlertView *alert = [[UIAlertView alloc]
                                      
                                      initWithTitle:@"Update Available"                                  
                                      message:@"There is an update available. Please make sure you have a stable online connection, then select 'Update Now', or check back later on."                                  
                                      delegate:self                                  
                                      cancelButtonTitle: @"Cancel"                                  
                                      otherButtonTitles:@"Update Now", nil];            
                [alert show];
            } else {
                alertFlag = 81;
                UIAlertView *alert = [[UIAlertView alloc]                                      
                                      initWithTitle:@"Data OK"                                  
                                      message:@"Your aircraft data is up to date."                                  
                                      delegate:self                                  
                                      cancelButtonTitle: @"OK & Close"                                 
                                      otherButtonTitles:@"Force Update All Aircraft", nil];            
                [alert show];
            }
        }
    }
    
}

- (void) checkForUpdates_Crew {
    
    //check if online
    
    if ([self is_online]) {
        
        //send request to server to get lastupdate data as json data
        
        if (crew_lastLocation!=nil) {
            NSString *url=serverpath;
            url = [url stringByAppendingString:@"get_lastupdate_crew.php?customer="];
            url = [url stringByAppendingString:customer];
            url = [url stringByAppendingString:@"&location="];
            url = [url stringByAppendingString:crew_lastLocation];
            //NSLog(@"url: %@",url);
            NSData* data = [NSData dataWithContentsOfURL:
                            [NSURL URLWithString: url]];
            __autoreleasing NSError* error = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
            //check if json data is valid
            if (error != nil) {
            } else {
                //compare timestamps
                NSArray *allItems = [result objectForKey:@"updateData"];
                //NSLog(@"%i",allItems.count);
                
                NSDictionary *item = [allItems objectAtIndex:0];
                
                if (!([[item objectForKey:@"lastUpdate"] isEqualToString:lastupdate_crew])) {
                    UIAlertView *alert = [[UIAlertView alloc]
                                          initWithTitle:@"CREW LIST UPDATE!"
                                          message:@"Crew list update available. Please open the Crew List window and tap Load Crew List. Then select a base."
                                          delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
                    [alert show];                    
                } else {
                    //NSLog(@"No Update available.");
                }
            }
        }
    }
    
}


- (void)checkDocuments_lastUpdate {
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    connectedToFleetControl = [defaults floatForKey:@"connectedToFleetControl"];
    
    //Check if FC is connected
    
    if (connectedToFleetControl==1) {
        
        
        //NSLog(@"checkDocuments_lastUpdate:  customer %@", customer );
        
     
        
        if (!([self is_online])) {
            
            
        } else {
            
            // send request to server
            
            NSString *url=serverpath_new;
            url = [url stringByAppendingString:@"get_lastupdate_documents/1.1/?customer="];
            url = [url stringByAppendingString:customer];
            //NSLog(@"url: %@",url);
            
            NSData* data = [NSData dataWithContentsOfURL:
                            [NSURL URLWithString: url]];
            __autoreleasing NSError* error = nil;
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
            
            //check if JSON data valid
            
            if (error != nil) {
                
                // RECEIVED DATA NOT VALID
                
                
            } else {
                
                
                NSString *current_lastUpdate= [defaults stringForKey:@"documents_lastUpdate"];
                
                //PARSE json object
                NSArray *lastUpdate = [result objectForKey:@"updateData"];
                NSString *value=@"";
                for (int i=0; i<lastUpdate.count; i++) {
                    NSDictionary *item = [lastUpdate objectAtIndex:i];
                    value= [item objectForKey:@"lastUpdate"];
                }
                
                if ([current_lastUpdate isEqual:value]) {
                    
                    //local lastUpdate value is equal to Server value
                    
                    //DO NOTHING
                    
                    UIAlertView *alert = [[UIAlertView alloc]
                                          initWithTitle:@"no Change detected"
                                          message:@"LastUpdate on server equal to local var"
                                          delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
                    [alert show];
                    
                } else {
                    
                    //Local lastUpdate value is NOT equal to Server Value
                    //Something changed on the server
                    
                    //NOTIFY USER
                    
                    UIAlertView *alert = [[UIAlertView alloc]
                                          initWithTitle:@"Updates available"
                                          message:@"Please open the document viewer to download new files."
                                          delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
                    [alert show];
                }
            }
            
        }
    }
    
}

- (IBAction)buttonSwitchToDocumentViewer:(id)sender {
    
    [self SaveValues];
    
    DocumentViewer *second = [[DocumentViewer alloc] initWithNibName:nil bundle:nil];   
    second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    second.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:second animated:YES completion:nil];

    
}



// DENNIS stuff - END



- (IBAction)buttonSwitchToRiskPage:(id)sender {
    
    
    if (CrewDataLoaded != 1) {
        
        
        UIAlertView *alert = [[UIAlertView alloc]
                              
                              initWithTitle:@"No Crew List Loaded"
                              
                              message:@"Please load crew list before opening the Risk Assessment."
                              
                              delegate:self
                              
                              cancelButtonTitle:@"CANCEL"
                              
                              
                              
                              otherButtonTitles: nil];
        
        [alert show];
    }else{
        
      
        pilotNameGlobal = [_arrayName7 objectAtIndex:linePilot];
        vFlightRegGlobal = vFlightRegistration.text;
        
        [[NSUserDefaults standardUserDefaults]  setObject: [_arrayName25 objectAtIndex:7]  forKey:@"RAtypeOPS"];
        
        [self SaveValues];
        
        displayWindow = 0;
        
        [self displayWindows];
        
        RiskAssessment *second = [[RiskAssessment alloc] initWithNibName:nil bundle:nil];
       second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
         second.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:second animated:YES completion:nil];


        
        
    }
    
    
    
}



- (IBAction)buttonActionLogInPage:(id)sender {
    
    [self SaveValues];
    
    StartPage *second = [[StartPage alloc] initWithNibName:nil bundle:nil];
   second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
     second.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:second animated:YES completion:nil];

    
}



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





- (IBAction)actionCancelEditPilotList:(id)sender {
    
      _viewEditPilotList.hidden = YES;
    
    
}

- (IBAction)actionClosePilotList:(id)sender {
    
    _viewPilotList.hidden = YES;
    
    [self.tableView deselectRowAtIndexPath:selectedPathTransfer animated:YES];
  
    
}

- (IBAction)actionShowPilotList:(id)sender {
    
    
    //NSLog(@"actionShowPilotList CrewDataLoaded  %.0f ", CrewDataLoaded);
    
    guidanceDictionary[@"guidanceBtnCrew"] =  @"ok";
    guidanceDictionary[@"guidanceBtnDispatch"] =  @"ok";
    
    
    if (_viewPilotList.hidden == NO) { // viewPilotList visible
        
        _viewPilotList.hidden = YES;
        [self.tableView deselectRowAtIndexPath:selectedPathTransfer animated:YES];
        _viewEditPilotList.hidden=YES;
        
        
    } else { // viewPilotList hidden
        
        _viewConfigurations.hidden = YES;
        _viewLegData.hidden = YES;
        
        
        if (CrewDataLoaded==1) {            
            _viewPilotList.hidden = NO;
            _viewEditPilotList.hidden=YES;
            _viewSeatOptions.hidden=YES;
            
            [viewOne bringSubviewToFront:_viewPilotList];
            [viewOne bringSubviewToFront:viewTopTop];
            
           
            
        } else {
            
            _viewPilotList.hidden = NO;
            _viewEditPilotList.hidden=NO;
            
            [viewOne bringSubviewToFront:_viewPilotList];
            [viewOne bringSubviewToFront:viewTopTop];
            
        }
    }
    
    
    [self MainRoutine];
    
    
}

- (IBAction)actionShowFlightSettings:(id)sender {
    
    if (flagSpecialPHIFlightSettingPage == 1) {        
        if (flagFuelVisisble == 1) {
            flagFuelVisisble = 0;
            triggerFuelAnimation = 1;
            [self setFuelPanelandLegDataViews];
            return;           
        }
    }
    if (_viewLegData.hidden == YES) {
        _viewLegData.hidden = NO;
        _viewConfigurations.hidden = YES;
        _viewPilotList.hidden = YES;
        [viewOne bringSubviewToFront:_viewLegData];
    }else{
         _viewLegData.hidden = YES;
    }
}




// seat options

- (void) seatOptions {
    
    //NSLog(@"seatOptions ");
    _viewPilotList.hidden = NO; [viewOne bringSubviewToFront:_viewPilotList]; [viewOne bringSubviewToFront:viewTopTop];
    _inputSeatName.text = @"";
    [_viewPilotList bringSubviewToFront:_viewSeatOptions];
    return;
}



- (IBAction)buttonActionCancelSeatOptions:(id)sender {
    _viewPilotList.hidden = YES; [_viewPilotList sendSubviewToBack:_viewSeatOptions];
    _inputSeatName.text =@"";
    
}





//functions for getting name and weight of crew table view

- (NSString *)nameForRow:(float)rowNo AndSection:(float)section {
    if (listStatusIsOnline == 1) {
        return [NSString stringWithFormat:@"%@, %@",[[[crew_sectioned objectAtIndex:section] objectAtIndex:rowNo]name],[[[crew_sectioned objectAtIndex:section] objectAtIndex:rowNo]initial]];
    }
    if ( rowNo>=0 && rowNo<self.tableViewDataName.count){
        return [self.tableViewDataName objectAtIndex:rowNo];
    } else {
        return nil;
    }
}

- (NSString *)weightForRow:(float)rowNo AndSection:(float)section {
    if (listStatusIsOnline == 1) {
        return [[[crew_sectioned objectAtIndex:section] objectAtIndex:rowNo]weight];
    }
    
    if ( rowNo>=0 && rowNo<self.tableViewDataName.count){
        return [self.tableViewDataWeight objectAtIndex:rowNo];
    } else {
        return nil;
    }
}

- (NSString *)EMPnumber:(int)rowNo AndSection:(int)section {    
    
    return [[[crew_sectioned objectAtIndex:section] objectAtIndex:rowNo]EMPnumber];
    
    
}


- (void)changeCurrentRowWithName:(NSString *)name andWeight:(NSString *)weight{
    NSIndexPath *selectedPath = [self.tableView indexPathForSelectedRow];
    if ( selectedPath != nil){
        [ self.tableViewDataName setObject:name atIndexedSubscript:selectedPath.row];
        [ self.tableViewDataWeight setObject:weight atIndexedSubscript:selectedPath.row];
        [ self sortData];
        [ self.tableView reloadData];
    }
};


- (void) sortData {
    BOOL didSwap = YES;
    while (didSwap) {
        didSwap = NO;
        for (int i=0; i< self.tableViewDataName.count-1; i++){
            NSString *nameI = [self.tableViewDataName objectAtIndex:i];
            for (int j=i+1; j< self.tableViewDataName.count; j++){
                NSString *nameJ = [self.tableViewDataName objectAtIndex:j];
                if ( [nameJ compare:nameI] == NSOrderedAscending){
                    [self.tableViewDataName exchangeObjectAtIndex:i withObjectAtIndex:j];
                    [self.tableViewDataWeight exchangeObjectAtIndex:i withObjectAtIndex:j];
                    didSwap = YES;
                }
            }
        }
    }
}



#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (listStatusIsOnline == 1) {
        return crew_sectioned.count;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (listStatusIsOnline == 0) {
        return self.tableViewDataName.count;
    }
    if (crew_sectioned.count==0) {
        return 0;
    } else {
        return [[crew_sectioned objectAtIndex:section] count];
    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (crew_types.count==0) {
        return @"test";
    } else {
        return [crew_types objectAtIndex:section];
    }
}



static NSString *CellIdentifier = @"CELL";
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
      if (cell.selectionStyle != UITableViewCellSelectionStyleNone) {
          // Handle tap code here 
          cell.contentView.backgroundColor = [UIColor darkGrayColor];       
          previousCell.contentView.backgroundColor = [UIColor blackColor];        
      }
      previousCell = cell;
    
    if (flagEnterCrewListMode == 2) {
        [self loadSeatFromCrewList];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}


// color table cells

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (listStatusIsOnline == 1) {
        UITableViewCell * normalCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (normalCell == nil){
            normalCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];        }
        // color the cells
        // every other cell or red if NOK
        if (indexPath.section %2==0) {
            normalCell.textLabel.textColor=[UIColor colorWithRed:255.0f/255.0f green:148.0f/255.0f blue:0.0f/255.0f alpha:1.0f]; // yellow
        } else {
            normalCell.textLabel.textColor=[UIColor colorWithRed:140.0f/255.0f green:186.0f/255.0f blue:253.0f/255.0f alpha:1.0f]; // light blue
        }
        if ([[[[crew_sectioned objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]status] isEqualToString:@"NOK"]) {
            normalCell.textLabel.textColor=[UIColor redColor];
        }
        normalCell.contentView.backgroundColor = [UIColor blackColor];
        normalCell.selectionStyle = UITableViewCellSelectionStyleBlue;
        NSString *name_combined = [NSString stringWithFormat:@"%@, %@",[[[crew_sectioned objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]name],[[[crew_sectioned objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]initial]];
        [normalCell.textLabel setText:name_combined]; // hier Name
        
        if (flagSpecialPHIFlightSettingPage == 1) {
            NSString *name_combined = [NSString stringWithFormat:@"%@, %@, %@",[[[crew_sectioned objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]name],[[[crew_sectioned objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]initial],[[[crew_sectioned objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]EMPnumber]      ];
            
            [normalCell.textLabel setText:name_combined]; // set name
        }
        
        return normalCell;
    }else{
      
        UITableViewCell * normalCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (normalCell == nil){
            normalCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        }
        NSString *cellLabel =  [ NSString stringWithFormat:@"%@, %@ lbs", [ self.tableViewDataName objectAtIndex:indexPath.row],
                                [ self.tableViewDataWeight objectAtIndex:indexPath.row]];
        _labelPilotCheck.text = cellLabel;
        normalCell.textLabel.textColor=[UIColor whiteColor];
        normalCell.textLabel.textColor=[UIColor colorWithRed:255.0f/255.0f green:222.0f/255.0f blue:0.0f/255.0f alpha:1.0f]; // yellow
        normalCell.textLabel.textColor=[UIColor whiteColor];
        normalCell.contentView.backgroundColor = [UIColor blackColor];
        [normalCell.textLabel setText:cellLabel];
        
        return normalCell;
    }
}





- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // First, create the text that will end up in the input field if you'll return YES:
    NSString *resultString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    // Now, validate the text and return NO if you don't like what it'll contain.
    // You accomplish this by trying to convert it to a number and see if that worked.
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber* resultingNumber = [numberFormatter numberFromString:resultString];
    return resultingNumber != nil;
}


// ********************************************************************************************************************************************
// ********************************************************************************************************************************************
// ********************************************************************************************************************************************






/// ================================================================  DETECT PORTRAIT LANDSCAPE ==================================================================




-(void)viewDidAppear:(BOOL)animated{
    [self setUpViewForInterfaceOrientation:self.interfaceOrientation];
    //[[UIApplication sharedApplication] statusBarOrientation];
    
    
}

- (void) setUpViewForInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation{
    if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
        //NSLog(@"Start in Landscape ");
        [self sortForLandscape];
    }
    else {
        //NSLog(@"Start in Portrait ");
        [self sortForPortrait];
    }
}



-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
    
   //NSLog(@"checking supportedInterfaceOrientations --------");
    //return UIInterfaceOrientationMaskAll;
    //return UIInterfaceOrientationMaskPortrait; // lock to portrait
    //return UIInterfaceOrientationMaskLandscape; // lock to landscape
    //return UIInterfaceOrientationMaskAll;
    
    if (_arrayName25.count > 1) {
        
        if ( [[_arrayName25 objectAtIndex:5] isEqualToString:@"Land"]) {
            // lock to landscape
            //NSLog(@"lock to landscape");
           return UIInterfaceOrientationMaskLandscape;
        }else if ([[_arrayName25 objectAtIndex:5] isEqualToString:@"Port"]) {
            //NSLog(@"lock to portrait");
            return UIInterfaceOrientationMaskPortrait;
        } else{
            //NSLog(@"unlock all");
            return UIInterfaceOrientationMaskAll;
        }
    }else{
        //NSLog(@"no orientation info - lock to all");
        return UIInterfaceOrientationMaskAll;
    }
    
}





- (BOOL) shouldAutorotate {
    
    //NSLog(@"checking shouldAutorotate --------");    
   return YES;
}



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


-(void) sortForLandscape { // normal!
    //NSLog(@"sortForLandscape");
   
    _logoOnlyGyronimo.frame = CGRectMake(296, -10, 143, 40);
    _labelLogoOnlyACtype.frame = CGRectMake(77, 24, 349, 26);
    
    
    _viewHelicopterInCenter.userInteractionEnabled = YES;
    _viewEquipmentOnHeli.hidden = YES;
    flagIsLandscape = 1;
    configMode = 0;
    _scrollViewSpecialEquipList.frame = CGRectMake(0, 126, 1024, 570);
    _viewSpecialEquipLowerTotals.frame = CGRectMake(0, 687, 1024, 60);
    _viewDlist.frame = CGRectMake(0, 0, 1024, 748);
    dListClassView_.frame = CGRectMake(436, 105, 475, 546);
    calculatePerformanceClassView_.frame  = CGRectMake( 0, 114, 646, 634 );
    
    _label2AvailableExternalLoad.frame = CGRectMake(80, 235, 242, 21);

    _viewTrennerTop.hidden = NO;
    _buttonmanifest.frame = CGRectMake( 967, 4, 50, 50 ) ;
    _buttonSummary.frame = CGRectMake( 967, 4, 50, 50 ) ;
    _buttonSpecialEquipList.frame = CGRectMake( 955, 5, 50, 50 ) ;
    viewMain.frame = CGRectMake( 0, -10, 1024, 768 );
    viewOne.frame = CGRectMake( 0, 20, 1024, 748 );
    viewLoadManifest.frame = CGRectMake( 0, 57, 1024, 694 );
    _viewPowerCheck.frame = CGRectMake( 0, 57, 1024, 694 );
    _viewSignature.frame = CGRectMake( 0, 54, 1024, 704 );
    _viewFlightManager.frame = CGRectMake(0, 0, 1024, 748);
    viewSetup.frame = CGRectMake(0, 0, 1024, 748);
    _viewSetupButtons.frame = CGRectMake(-2, 580, 1026, 54);
    enterPad.frame = CGRectMake(  648, 410, 377, 346 );
   
    UIImage *background = [UIImage imageNamed:@"Flight_Page.png"];
    [_backgroundMain setImage:background];

    
    UIImage *backgroundFlight = [UIImage imageNamed:@"Flight_Page.png"];
    [_backgroundFlightPage setImage:backgroundFlight];
    [_backgroundFlightManager setImage:backgroundFlight];
    [_backgroundSetupPage setImage:backgroundFlight];
    _backgroundSetupPage.frame = CGRectMake(0, 0, 1024, 768);
    UIImage *triangle = [UIImage imageNamed:@"triangle white.png"];
    [_triangleWhite setBackgroundImage:triangle forState:UIControlStateNormal];
    _backgroundMain.frame = CGRectMake( 0, 10, 1024, 748 ) ;
   
    
 
    _triangleWhite.frame = CGRectMake( 188, 13, 19, 38 );
    _viewButtonOATPA.frame = CGRectMake( -1, 6, 186, 52 );  buttonDisplayEnvironment.frame = CGRectMake( 1, 0, 182, 52 );
    _viewButtonOATlabelOAT.frame = CGRectMake( 2, 1, 90, 23 ); labelDisplayOAT.frame = CGRectMake( 2, 22, 92, 23 );
    _viewButtonOATLabelPA.frame = CGRectMake( 82, 1, 90, 23 ); labelDisplayPA.frame = CGRectMake( 75, 22, 92, 23 );
    _trennerBottom.hidden = YES;
   

    _trennerVerticalBottom.hidden  = YES;
    viewEnvironment.frame  = CGRectMake( 645, 117, 382, 304 );
    
    _viewPilotList.frame = CGRectMake( 647, 115, 383, 633 ); // landscape
    _tableView.frame = CGRectMake( 0, 0, _viewPilotList.frame.size.width, _viewPilotList.frame.size.height - 40 );
    crew_locations_sview.frame = CGRectMake( 91, 74, 200, 423 );
    
    
    _buttonONLINEloadCrewList.frame = CGRectMake( 0, 584, 388, 50 );
    [viewMain bringSubviewToFront:_viewPilotList];
    _labelLoadCrewList.frame = CGRectMake( 96, 598, 197, 23 );
    ScrollViewManifest.frame = CGRectMake(0, -2, 1024, 694);
    [ScrollViewManifest setContentSize:CGSizeMake(644, 1800)];
    [ScrollViewManifest scrollRectToVisible:CGRectMake(0, 0, 644, 635) animated:YES];
    _scrollViewSummaryManifest.frame = CGRectMake(0, 0, 1024, 694);
    [_scrollViewSummaryManifest setContentSize:CGSizeMake(644, 1600)];
    _ScrollViewPowerCheck.frame = CGRectMake(0, -2, 1024, 694);
    [_ScrollViewPowerCheck setContentSize:CGSizeMake(1030, 700)];
    _viewConfigurations.frame = CGRectMake(647, 114, 377, 635); [viewOne bringSubviewToFront:_viewConfigurations];
    _viewSelectHelicopter.frame = CGRectMake( 0, 0, 1040, 750 );
    _viewManifestLowerButtons.frame = CGRectMake( 0, 644, 1024, 50 );
    _viewSummaryLowerButtons.frame  = CGRectMake( 0, 644, 1024, 50 ); // landscape
    _viewButtonsCrewList.frame = CGRectMake( 0, 591, 378, 41 ); 
    _scrollViewSetupItems.frame = CGRectMake(17, 119, 725, 576);
     _viewButtonsSETUPpage.frame  = CGRectMake( -1, 703, 1026, 54 );
    
    _viewButtonAutoCalcMode.frame = CGRectMake( 1, 6, 182, 52 );
    _buttonCalcMode.frame = CGRectMake( 0, 0, 182, 52 );
    _labelCalculationMode.frame = CGRectMake( 0, 2, 182, 23 );
    _labelCalcMode.frame = CGRectMake( 0, 22, 182, 23 );
    _labelCalculationMode.font = [UIFont systemFontOfSize:16];
    
    NSNotification *myNotification = [NSNotification notificationWithName:@"notificationSetLandscape"
                                                                   object:self 
                                                                 userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:myNotification];
    
    if (MBpagevisit > 10 ) {
        [self addPerformanceButtons];
        [self setBasicsForConfiguration];
        [self displayWindows];
    }
    
    [viewOne bringSubviewToFront:_viewDlist];
    [viewOne bringSubviewToFront:_viewFleetManager];
    
    if (_viewSelectHelicopter.hidden == NO) {
        [viewOne bringSubviewToFront:_viewSelectHelicopter];
    }
    if (_viewConfigurations.hidden == NO) {
        [viewOne bringSubviewToFront:_viewConfigurations];
    }
}




-(void) sortForPortrait {
    
    //NSLog(@"sortForPortrait");
    
    _logoOnlyGyronimo.frame = CGRectMake(45, -10, 143, 40);
    _labelLogoOnlyACtype.frame = CGRectMake(-175, 24, 349, 26);
    
    _viewHelicopterInCenter.userInteractionEnabled = YES;
    _viewEquipmentOnHeli.hidden = YES;
    flagIsLandscape = 0;
    configMode = 0;

    _scrollViewSpecialEquipList.frame = CGRectMake(0, 126, 1024, 1024);
    _viewSpecialEquipLowerTotals.frame = CGRectMake(0, 944, 1024, 60);
    _viewDlist.frame = CGRectMake(0, 0, 768, 1024);
    dListClassView_.frame = CGRectMake(160, 305, 475, 546);
    calculatePerformanceClassView_.frame  = CGRectMake( 0, 114 - 58, 643, 630 );
    
    _label2AvailableExternalLoad.frame = CGRectMake(80, 238, 242, 21);
    _buttonmanifest.frame = CGRectMake( 710, 4, 50, 50 ) ;
    _buttonSummary.frame = CGRectMake( 710, 4, 50, 50 ) ;
    _buttonSpecialEquipList.frame = CGRectMake( 725, 5, 50, 50);
    viewMain.frame = CGRectMake( 0, -10, 1024, 1900 );
    viewOne.frame = CGRectMake( 0, 20, 1024, 1900 );
    viewLoadManifest.frame = CGRectMake( 0, 57, 1024, 1900 );
    _viewPowerCheck.frame = CGRectMake( 0, 57, 1024, 1900 );
    _viewSignature.frame = CGRectMake( -128, -1, 1024, 1010 );
    _viewFlightManager.frame = CGRectMake(0, 0, 768, 1004);
    viewSetup.frame = CGRectMake(0, 0, 768, 1004);
    _viewSetupButtons.frame = CGRectMake(-2, 840, 1026, 54);
    enterPad.frame = CGRectMake(  389, 690, 380, 346 ) ;
  
    UIImage *background = [UIImage imageNamed:@"WB_background_portrait.png"];
    [_backgroundMain setImage:background];
    UIImage *triangle = [UIImage imageNamed:@"triangle white down.png"];
    [_triangleWhite setBackgroundImage:triangle forState:UIControlStateNormal];
    UIImage *backgroundFlight = [UIImage imageNamed:@"WB_background_generic_empty.png"];
    [_backgroundFlightPage setImage:backgroundFlight];
     [_backgroundFlightManager setImage:backgroundFlight];
    [_backgroundSetupPage setImage:backgroundFlight];
    _backgroundSetupPage.frame = CGRectMake(0, 0, 1024, 980);
    _backgroundMain.frame = CGRectMake( 0, 10, 768, 1004 ) ;
    
    
    _triangleWhite.frame = CGRectMake( 45, 105, 38, 19 );
    float yGapEnvi = 5;
    _viewButtonOATPA.frame = CGRectMake( -1, 3, 128, 95 );  buttonDisplayEnvironment.frame = CGRectMake( 0, 0, 128, 95 ) ;
    _viewButtonOATlabelOAT.frame = CGRectMake( 0, yGapEnvi, 128, 23 ) ; labelDisplayOAT.frame = CGRectMake( 0, yGapEnvi+20, 128, 23 ) ;
    _viewButtonOATLabelPA.frame = CGRectMake( 0, yGapEnvi+20+20, 128, 23 ) ; labelDisplayPA.frame = CGRectMake( 0, yGapEnvi+20+20+20, 128, 23 );
    _trennerBottom.hidden = NO; [viewOne bringSubviewToFront:_trennerBottom];
    
    
    _trennerVerticalBottom.hidden  = NO; [viewOne bringSubviewToFront:_trennerVerticalBottom];
    viewEnvironment.frame  = CGRectMake( 0, 712, 400, 600 );
    
    _viewPilotList.frame = CGRectMake( 0, 528, 383, 630 ); // portrait
    _tableView.frame = CGRectMake( 0, 0, _viewPilotList.frame.size.width, _viewPilotList.frame.size.height - 200 );
    crew_locations_sview.frame = CGRectMake( 91, 74, 200, 423 - 80 );    
    
    _buttonONLINEloadCrewList.frame = CGRectMake( -10, 430, 388, 50 );
    [viewMain bringSubviewToFront:_viewPilotList];
    _labelLoadCrewList.frame = CGRectMake( 96, 442, 197, 23 );
    ScrollViewManifest.frame = CGRectMake(0, -2, 768, 980);
    [ScrollViewManifest setContentSize:CGSizeMake(1024, 1800)];
    [ScrollViewManifest scrollRectToVisible:CGRectMake(0, 0, 644, 635) animated:YES];
    _ScrollViewPowerCheck.frame = CGRectMake(0, -2, 1024, 694);
    [_ScrollViewPowerCheck setContentSize:CGSizeMake(1030, 700)];
    _scrollViewSummaryManifest.frame = CGRectMake(0, 0, 768, 980);
    [_scrollViewSummaryManifest setContentSize:CGSizeMake(1024, 1600)];
    _viewConfigurations.frame = CGRectMake(0, 536, 386, 630); [viewOne bringSubviewToFront:_viewConfigurations];
    _viewSelectHelicopter.frame = CGRectMake( -150, 0, 1040, 750 );
    _viewManifestLowerButtons.frame = CGRectMake( 0, 900, 1024, 50 );
    _viewSummaryLowerButtons.frame  = CGRectMake( 0, 900, 1024, 50 ); // portrait
    _scrollViewSetupItems.frame = CGRectMake(17, 119, 725, 760);
    _viewButtonsSETUPpage.frame  = CGRectMake( -1, 955, 1026, 54 );
    _viewButtonsCrewList.frame = CGRectMake( 0, 430, 378, 41 );
    
    _viewButtonAutoCalcMode.frame = CGRectMake( 1, 6, 125, 92 );
    _buttonCalcMode.frame = CGRectMake( 0, 0, 125, 92 );
    _labelCalculationMode.frame = CGRectMake( 0, 20, 123, 23 );
    _labelCalcMode.frame = CGRectMake( 0, 42, 123, 23 );    
    _labelCalculationMode.font = [UIFont systemFontOfSize:14];
    
    NSNotification *myNotification = [NSNotification notificationWithName:@"notificationSetPortrait"
                                                                   object:self 
                                                                 userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:myNotification];
    
    if (MBpagevisit > 10 ) {
        [self addPerformanceButtons];      
        [self setBasicsForConfiguration];
        [self displayWindows];
    }
    
   
    [viewOne bringSubviewToFront:_viewDlist];
    [viewOne bringSubviewToFront:_viewFleetManager];
    
    if (_viewSelectHelicopter.hidden == NO) {
        [viewOne bringSubviewToFront:_viewSelectHelicopter];
    }
    if (_viewConfigurations.hidden == NO) {
        [viewOne bringSubviewToFront:_viewConfigurations];
    }
}









- (void)viewDidUnload
{
    [super viewDidUnload];
}





- (EquipmentPackages*)currentFlightEquipmentPackage {
    return [[EquipPackagesManager sharedInstance] packageForKey:@"SASS"];
}



#pragma mark MainRoutine


- (IBAction)actionLOGACViewSettings:(id)sender {
    
    [self.view endEditing:TRUE];
    
    //NSLog(@"_viewMeasureFrontSeats.center.y %.0f ", _viewMeasureFrontSeats.center.y);
    //NSLog(@"_viewMeasureFrontSeats.frame.origin.y %.0f ", _viewMeasureFrontSeats.frame.origin.y);
    
    NSString *previousYup = @"";
    previousYup = [_arrayName21 objectAtIndex:37];
    [_arrayName21 replaceObjectAtIndex:37 withObject:_iacHeliYUp.text];
    
    
    if (![previousYup isEqualToString:_iacHeliYUp.text]) {
        
        [self setTopViewWindowSettings];
        
    }
    

    //NSLog(@"_iacACwidth.text %@", _iacACwidth.text);
    //NSLog(@"_iacACheight.text %@", _iacACheight.text);
    
    _viewMeasureFrontSeats.frame = CGRectMake(_viewMeasureFrontSeats.frame.origin.x, [_iacMeasureFrontSeatsY.text floatValue], _viewMeasureFrontSeats.frame.size.width, _viewMeasureFrontSeats.frame.size.height);
    _viewMeasureRearSeats.frame = CGRectMake(_viewMeasureRearSeats.frame.origin.x, [_iacMeasureRearSeatsY.text floatValue], _viewMeasureRearSeats.frame.size.width, _viewMeasureRearSeats.frame.size.height);
    _viewSeatSize.frame = CGRectMake(_viewSeatSize.frame.origin.x, _viewSeatSize.frame.origin.y, [_iacSeatWidth.text floatValue] , [_iacSeatHeight.text floatValue]);
    _viewMeasureCenter.frame = CGRectMake([_iacLatCenter.text floatValue], _viewMeasureCenter.frame.origin.y, _viewMeasureCenter.frame.size.width , _viewMeasureCenter.frame.size.height);
    _viewMeasureLatRight.frame = CGRectMake([_iacLatCenter.text floatValue] + [_iacLatRight.text floatValue], _viewMeasureLatRight.frame.origin.y, _viewMeasureLatRight.frame.size.width , _viewMeasureLatRight.frame.size.height);
    
    
    if (largeTopViewMode == 1) {
        _ACtopView.frame = CGRectMake([_iacACX.text floatValue] + 75, [_iacACY.text floatValue], [_iacACwidth.text floatValue], [_iacACheight.text floatValue]);
    }else{
        _ACtopView.frame = CGRectMake([_iacACX.text floatValue], [_iacACY.text floatValue], [_iacACwidth.text floatValue], [_iacACheight.text floatValue]);
    }
    
        if (![prevStation isEqualToString:_iacStationID.text ]) {
        
        if ([_iacStationID.text length] >=1 ) {
            _iacOffsetX.text =  [_arrayName13 objectAtIndex:[_iacStationID.text intValue]];
            _iacOffsetY.text =  [_arrayName11 objectAtIndex:[_iacStationID.text intValue]];
            _iacSizeX.text =  [_arrayName19 objectAtIndex:[_iacStationID.text intValue]];
            _iacSizeY.text =  [_arrayName20 objectAtIndex:[_iacStationID.text intValue]];
        }
    }
    
    if ([_iacStationID.text length] >=1 ) {
        
        NSString *imgageNameTest = [_arrayName10 objectAtIndex: [_iacStationID.text intValue]  ];
        NSString *imgageName;
        if ([ imgageNameTest rangeOfString:@"!"].location != NSNotFound     ) {
            
            if ([imgageNameTest isEqualToString:@"fuelTank!"]) {
                
                
                imgageName =  @"fuelTank.png";
                
                
            }else{
               imgageName =  [ [_arrayName10 objectAtIndex: [_iacStationID.text intValue]  ] stringByReplacingOccurrencesOfString:@"!" withString:@""];
                
            }
            
            
        }else{
            imgageName =  [[NSString alloc] initWithFormat:@"%@Dark.png", imgageNameTest ];
        }
       
        UIImage *img = [UIImage imageNamed:imgageName];
        CGFloat width = img.size.width;
        CGFloat height = img.size.height;
        float ratio = height / width;
        NSString *newY =  [[NSString alloc] initWithFormat:@"%.0f", [_iacSizeX.text floatValue] * ratio ];
        
       if (_switchRatioForItems.on == YES) {
            [_arrayName20 replaceObjectAtIndex:[_iacStationID.text integerValue] withObject:newY];
        }else{
             [_arrayName20 replaceObjectAtIndex:[_iacStationID.text integerValue] withObject:_iacSizeY.text];
        }
        
       if ([_iacStationID.text length] >=1 ) {
           _iacSizeY.text =  [_arrayName20 objectAtIndex:[_iacStationID.text intValue]];
        }
        [_arrayName11 replaceObjectAtIndex:[_iacStationID.text integerValue] withObject:_iacOffsetY.text];
        [_arrayName13 replaceObjectAtIndex:[_iacStationID.text integerValue] withObject:_iacOffsetX.text];
        [_arrayName19 replaceObjectAtIndex:[_iacStationID.text integerValue] withObject:_iacSizeX.text];
       
    }
 
    
    prevStation = _iacStationID.text;
    previousConfiguration = 999;
    [self createListoItemsSlidersAndInterior];
    [self MainRoutine];
    
}



- (void) setACImage:(int)ACstate {    
    //NSLog(@"ACstate %d", ACstate);    
    if (previousACTopViewState == ACstate) {
        return;
    }    
    if (ACstate == 0) {
        [_ACtopView setImage:ACtopImage ]; 
    }else{
        [_ACtopView setImage:ACtop_WarningImage ]; 
    }    
    previousACTopViewState = ACstate;    
}

- (void) MainRoutine {
    
  
    
    //NSLog(@"MainRoutine -----------------------------------------");
    //NSLog(@"AC_Type %@", AC_Type);
    
    //NSLog(@"flagDoNotResetFuelFlow %d", flagDoNotResetFuelFlow);    
    //NSLog(@"calculatePerformanceClass_.cruiseInputFuelFlow.text %@", calculatePerformanceClass_.cruiseInputFuelFlow.text);   
    //NSLog(@"MainRoutine   %ld", (long)_segmentFlightLegMode.selectedSegmentIndex);  
        
    
    if (flagDoNotResetFuelFlow == 1) {
        flagDoNotResetFuelFlow = 0;        
    }else{
        if ([calculatePerformanceClass_.cruiseInputFuelFlow.text isEqualToString:@"xxx"] || [calculatePerformanceClass_.cruiseInputFuelFlow.text isEqualToString:@"0.0"]) { 
            //NSLog(@"1 NOT setting  inputFuelFlowOverride ");        
            inputFuelFlowOverride.enabled = YES;
            inputFuelFlowOverride.textColor = [UIColor blackColor];
            [inputFuelFlowOverride setBorderStyle:UITextBorderStyleRoundedRect];
            inputFuelFlowOverride.backgroundColor = [UIColor whiteColor];
            
        }else{
            
            inputFuelFlowOverride.text = calculatePerformanceClass_.cruiseInputFuelFlow.text;
            //NSLog(@"setting inputFuelFlowOverride.text = %@", inputFuelFlowOverride.text);        
            inputFuelFlowOverride.enabled = NO;
            inputFuelFlowOverride.textColor = [UIColor whiteColor];
            [inputFuelFlowOverride setBorderStyle:UITextBorderStyleLine];
            inputFuelFlowOverride.backgroundColor = [UIColor clearColor];
        }
    }
    
    if (flagSpecialPHIFlightSettingPage == 1) {
         inputFuelFlowOverride.enabled = NO;
        inputFuelFlowOverride.textColor = [UIColor whiteColor];
        [inputFuelFlowOverride setBorderStyle:UITextBorderStyleLine];
        inputFuelFlowOverride.backgroundColor = [UIColor clearColor];
    }
    

    if (lineHoistLoad > 0 && [[_arrayName8 objectAtIndex:lineHoistLoad] isEqualToString:@"1"] && ![[_arrayName18 objectAtIndex:lineHoistLoad] isEqualToString:@""]) {
        
        NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"_"];        
        NSArray *arrayComponents = [[_arrayName18 objectAtIndex:lineHoistLoad]  componentsSeparatedByCharactersInSet:charSet1];
        //NSLog(@"arrayComponents %@", arrayComponents);
        // get arm alternate from hoist
        // example: max 249_< 0_max 229
        float maxHoistLoadWeight = [[arrayComponents objectAtIndex:0]floatValue];
        //NSLog(@"maxHoistLoadWeight %.0f", maxHoistLoadWeight);
        float minTemp = [[arrayComponents objectAtIndex:1]floatValue];
        //NSLog(@"minTemp %.0f", minTemp);        
        float reducedHoistLoad = [[arrayComponents objectAtIndex:2]floatValue];        
        if (OAT <minTemp) {
            //NSLog(@"reducing to reducedHoistLoad %.0f", reducedHoistLoad);         
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1500 + lineHoistLoad];   
            if (!valueField) {               
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1500 + lineHoistLoad];
            }
            valueField.textColor = [UIColor orangeColor];
            [valueField  setText: [[NSString alloc] initWithFormat:@"<%.0fº OAT: Max Hoist %.0fkg", minTemp, reducedHoistLoad  ]   ];
            restrictingHoistWeight = reducedHoistLoad;            
            //NSLog(@"_arrayName2 %@", [_arrayName2 objectAtIndex:lineHoistLoad]);
            if ([[_arrayName2 objectAtIndex:lineHoistLoad] floatValue] > reducedHoistLoad) {
                weightValue = reducedHoistLoad;
                [self updateSlider: lineHoistLoad + 1600];
            }            
        }else{
            //NSLog(@"enabling hoist to %.0f", maxHoistLoadWeight);          
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1500 + lineHoistLoad];
            if (!valueField) {               
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1500 + lineHoistLoad];
            }            
            [valueField  setText: @""  ];
            restrictingHoistWeight = maxHoistLoadWeight;
            if ([[_arrayName2 objectAtIndex:lineHoistLoad] floatValue] > restrictingHoistWeight) {
                weightValue = restrictingHoistWeight;
                [self updateSlider: lineHoistLoad + 1600];
            } 
        }
    }else{
        restrictingHoistWeight = 99999;        
    }

    
    //NSLog(@"restrictingHoistWeight %.0f", restrictingHoistWeight);   
    
          
    if (_arrayName1.count < 1) {       
        return; // important to fix crash on re-login
    }
    
    //NSLog(@"1 calcMode %@", calcMode);
    
    if ([calcMode isEqualToString:@"plan"]) {
        _labelCalcMode.text = @"Plan Mode";
    }else{
        _labelCalcMode.text = @"Individual";
    }
    
   
    int flagUsingMultipleCGenvelopes = 0;
    
        
    if ( [[_arrayName22 objectAtIndex:49]length] > 4) {
        flagUsingMultipleCGenvelopes =1;
    }
    
    if (flagUsingMultipleCGenvelopes == 0) {
        
        if ( [[_arrayName22 objectAtIndex:49]isEqualToString:@"yes"] ) {
            NSString *previousAlternateCGEnvelope = alternateCGenvelope;
            if ([[_arrayName2 objectAtIndex:lineExternal] floatValue] * [[_arrayName8 objectAtIndex:lineExternal] floatValue] > 1) {
                alternateCGenvelope = @"CGexternal";
            }else{
                alternateCGenvelope = @"CGenvelope";
            }
            
            if (![previousAlternateCGEnvelope isEqualToString:alternateCGenvelope]) {
                [self setCGenvelope];
            }
        }
    }    
    
    //NSLog(@"flagUsingMultipleCGenvelopes %d", flagUsingMultipleCGenvelopes );    
    //NSLog(@"lineHoistLoad %.0f", lineHoistLoad );    
    //NSLog(@"[_arrayName2 objectAtIndex:lineHoistLoad] %@", [_arrayName2 objectAtIndex:lineHoistLoad] );
    //NSLog(@"[_arrayName8 objectAtIndex:lineHoistLoad] %@", [_arrayName8 objectAtIndex:lineHoistLoad] );
    
 
     if (flagUsingMultipleCGenvelopes == 1) {
        //NSLog(@"checking for alternate");
          NSString *previousAlternateCGEnvelope = alternateCGenvelope;
        if ([[_arrayName2 objectAtIndex:lineExternal] floatValue] * [[_arrayName8 objectAtIndex:lineExternal] floatValue] > 1) {            
           
            alternateCGenvelope = [_arrayName12 objectAtIndex:lineExternal];
            
            //NSLog(@"alternateCGenvelope %@", alternateCGenvelope);
            
        }else  if ([[_arrayName2 objectAtIndex:lineHoistLoad] floatValue] * [[_arrayName8 objectAtIndex:lineHoistLoad] floatValue] > 1) {
         
            alternateCGenvelope = [_arrayName12 objectAtIndex:lineHoistLoad];     
            
            if ([alternateCGenvelope isEqualToString:@"H145hoist"]) {
                //special H145 hoist rule  Depends on Display Button
                if (densityalt < 12000 || Hp < 12000) {
                   
                    alternateCGenvelope = @"H145hoist";
                }else{
                  
                    alternateCGenvelope = @"H145hoistAbove12000";
                    
                }
            }
             //NSLog(@"alternateCGenvelope %@", alternateCGenvelope);            
        }else{
       
             alternateCGenvelope = [_arrayName22 objectAtIndex:49];
        }
         
         
        //NSLog(@"previousAlternateCGEnvelope %@", previousAlternateCGEnvelope);   
        //NSLog(@"alternateCGenvelope %@", alternateCGenvelope);       
         [self setCGenvelope];
        if (![previousAlternateCGEnvelope isEqualToString:alternateCGenvelope]) {
         
            [self setCGenvelope];
        }
    }
    
  //NSLog(@"2alternateCGenvelope %@", alternateCGenvelope);     
     

    
    //NSLog(@"1 arrayConfigurations %@", arrayConfigurations);
    
    if (lineSeats > 0) {
      
        // compute total seats removed
        float totalWgtRemoved = 0;
        float totalMomtRemoved = 0;
        float totalArmRemoved = 0;
        float totalMomtRemovedLat = 0;
        float totalArmRemovedLat = 0;
        float wgtRemoved =0;
        float momRemoved =0;
        float momRemovedLat =0;
        int configStationsStart = 0;
        int configStationsEnd = 0;
        
        configStationsStart = [[_arrayName23 objectAtIndex:11] intValue];
        configStationsEnd = [[_arrayName23 objectAtIndex:13] intValue];
        
        for(int i =configStationsStart; i<lineZFW; i++) {
                        
            //NSLog(@"%d %@  == %@ ", i, [_arrayName1 objectAtIndex:i], [_arrayName17 objectAtIndex:i]);                        
            //NSLog(@"checking %d = %@", i, [_arrayName17 objectAtIndex:i]);            
            // if seat is negative then the seat is included in the BEW and has to be subtracted if unloaded. If loadednothing happens.
            
            if ( [[_arrayName17 objectAtIndex:i] floatValue] <0) {
                
                if ( [[_arrayName8 objectAtIndex:i] floatValue] == 1) {
                    wgtRemoved = 0;
                    momRemoved = 0;
                    momRemovedLat = 0;
                }else{
                    wgtRemoved = [[_arrayName17 objectAtIndex:i] floatValue] ;
                    
                    
                    float itemArm = 0;
                    if ([[_arrayName18 objectAtIndex:i] length] > 1 & [[_arrayName18 objectAtIndex: i ] rangeOfString:@"max"].location == NSNotFound) {
                        itemArm = [[_arrayName18 objectAtIndex:i]floatValue];
                    }else{
                        itemArm = [[_arrayName3 objectAtIndex:i]floatValue];
                    }
                    momRemoved = wgtRemoved * itemArm;
                    momRemovedLat = wgtRemoved * [[_arrayName5 objectAtIndex:i] floatValue];
                }
                
                
                
               
                
            }else if ( [[_arrayName8 objectAtIndex:i] floatValue] == 1) {
                wgtRemoved = [[_arrayName17 objectAtIndex:i] floatValue] ;
                //NSLog(@"wgtRemoved %.0f", wgtRemoved);                
                float itemArm = 0;
                if ([[_arrayName18 objectAtIndex:i] length] > 1 & [[_arrayName18 objectAtIndex: i ] rangeOfString:@"max"].location == NSNotFound) {
                    itemArm = [[_arrayName18 objectAtIndex:i]floatValue];
                }else{
                    itemArm = [[_arrayName3 objectAtIndex:i]floatValue];
                }
                momRemoved = wgtRemoved * itemArm;
                momRemovedLat = wgtRemoved * [[_arrayName5 objectAtIndex:i] floatValue];
            }else{
                wgtRemoved = 0;
                momRemoved = 0;
                momRemovedLat = 0;
            }            
            totalWgtRemoved = totalWgtRemoved + wgtRemoved;
            totalMomtRemoved = totalMomtRemoved + momRemoved;
            totalArmRemoved = totalMomtRemoved / totalWgtRemoved;
            totalMomtRemovedLat = totalMomtRemovedLat + momRemovedLat;
            totalArmRemovedLat = totalMomtRemovedLat / totalWgtRemoved;
            if (totalMomtRemoved == 0) {
                totalArmRemoved = 0;
            }
            if (totalMomtRemovedLat == 0) {
                totalArmRemovedLat = 0;
            }
        }
        
        
       
        NSString *labelRemovedWgt= [[NSString alloc] initWithFormat:@"%.2f", totalWgtRemoved ];
        NSString *labelRemovedArm = [[NSString alloc] initWithFormat:@"%.0f", totalArmRemoved ];
        NSString *labelRemovedMoment = [[NSString alloc] initWithFormat:@"%.0f", totalMomtRemoved ];
        NSString *labelRemovedArmLat = [[NSString alloc] initWithFormat:@"%.0f", totalArmRemovedLat ];
        NSString *labelRemovedMomentLat = [[NSString alloc] initWithFormat:@"%.0f", totalMomtRemovedLat ];
       
        [_arrayName2 replaceObjectAtIndex:lineSeats withObject:labelRemovedWgt];
        [_arrayName3 replaceObjectAtIndex:lineSeats withObject:labelRemovedArm];
        [_arrayName4 replaceObjectAtIndex:lineSeats withObject:labelRemovedMoment];
        [_arrayName5 replaceObjectAtIndex:lineSeats withObject:labelRemovedArmLat];
        [_arrayName6 replaceObjectAtIndex:lineSeats withObject:labelRemovedMomentLat];
            
    }    

  
    
    if (flagUsingAlternateEquipment ==0) {
             
        _labelConfigurationName.text = arrayConfigurations[configuration];         
        _labelConfigurationName2.text = arrayConfigurations[configuration]; 
        _labelConfigurationName2.textColor = yellowSpecialColor;
        _labelConfigurationName2.backgroundColor = [UIColor clearColor];        
    }else{  
        _labelConfigurationName.text = _dropDownAvailableCallsigns.text;
        _labelConfigurationName2.text = _dropDownAvailableCallsigns.text;        
        _labelConfigurationName2.textColor = [UIColor blackColor];;
        _labelConfigurationName2.backgroundColor = yellowSpecialColor;
    }


   
    [self calcLegTime];


    if (flagIsLandscape == 1) {
        _viewLegButtons.frame = CGRectMake(0, 0, 1024, 52);
    }else{
        _viewLegButtons.frame = CGRectMake( 0, 0, 150, 650 );
    }    
    
   
    if (flagPerfBoxOn == 0) {
        
        
        
        if (_segmentFlightLegMode.selectedSegmentIndex == 0) {
            // flight mode - no legs
            
          
        }else{
            //legs mode         
            int numberOfLegsThisFlight = [[flightSettingsDictionary  objectForKey:@"numberOfLegsThisFlight"] floatValue];
            if (flagIsLandscape == 1) {
                _scrollViewTopDisplayButton.frame = CGRectMake( -2, 54, 1031, 73 );
                [_scrollViewTopDisplayButton setScrollEnabled:YES];                     
                viewTopDisplayButtons.frame = CGRectMake( 2+ (123 *numberOfLegsThisFlight), 0, 1031, 73 ) ;
                [_scrollViewUniversalButtons setContentSize:CGSizeMake(_viewUniversalButtons.frame.size.width + (numberOfLegsThisFlight * 75), 73)];                     
                [_scrollViewTopDisplayButton setContentSize:CGSizeMake(_viewUniversalButtons.frame.size.width + (numberOfLegsThisFlight * 75) + (75 *numberOfLegsThisFlight), 73)];
                
            }else{
                _scrollViewTopDisplayButton.frame = CGRectMake( 645, 54, 150, 650 ) ;
                [_scrollViewTopDisplayButton setScrollEnabled:YES];
                viewTopDisplayButtons.frame = CGRectMake( 0, 0 + (55 *numberOfLegsThisFlight), 150, 650 ) ;
                //_scrollViewUniversalButtons.frame   = CGRectMake(  -1, 130, 150, 500  - (55 *numberOfLegsThisFlight) );
                [_scrollViewUniversalButtons setContentSize:CGSizeMake(_viewUniversalButtons.frame.size.width , _viewUniversalButtons.frame.size.height + (numberOfLegsThisFlight * 55) )]; 
                [_scrollViewTopDisplayButton setContentSize:CGSizeMake(_viewUniversalButtons.frame.size.width , _viewUniversalButtons.frame.size.height + (numberOfLegsThisFlight * 55) + (numberOfLegsThisFlight * 55) )]; 
            }         
        }
    }
    
    

    
    if (_segmentSwapMode.selectedSegmentIndex == 1) {
        panRecognizerForGhost.enabled = YES;
    }else{
         panRecognizerForGhost.enabled = NO; ;
    }
    
    
    if (_switchAdjustACTopView.on == YES) {
        //NSLog(@" _arrayName19 %@", _arrayName19 );
        _viewACViewSettings.hidden = NO;
        [viewOne bringSubviewToFront:_viewACViewSettings];
        _iacMeasureFrontSeatsY.text =  [ [NSString alloc] initWithFormat:@"%.0f", _viewMeasureFrontSeats.frame.origin.y ];
        _iacMeasureRearSeatsY.text =  [ [NSString alloc] initWithFormat:@"%.0f", _viewMeasureRearSeats.frame.origin.y ];
        _iacSeatWidth.text =  [ [NSString alloc] initWithFormat:@"%.0f", _viewSeatSize.frame.size.width];
        _iacSeatHeight.text =  [ [NSString alloc] initWithFormat:@"%.0f", _viewSeatSize.frame.size.height];
        _iacLatCenter.text =  [ [NSString alloc] initWithFormat:@"%.0f", _viewMeasureCenter.frame.origin.x];
        _iacLatRight.text =  [ [NSString alloc] initWithFormat:@"%.0f", _viewMeasureLatRight.frame.origin.x - _viewMeasureCenter.frame.origin.x];
        
        if (largeTopViewMode == 1) {
            _iacACX.text =  [ [NSString alloc] initWithFormat:@"%.0f", _ACtopView.frame.origin.x - 75] ;
        }else{
            _iacACX.text =  [ [NSString alloc] initWithFormat:@"%.0f", _ACtopView.frame.origin.x  ] ;
        }
        _iacACY.text =  [ [NSString alloc] initWithFormat:@"%.0f", _ACtopView.frame.origin.y];
        _iacACwidth.text =  [ [NSString alloc] initWithFormat:@"%.0f", _ACtopView.frame.size.width];
        _iacACheight.text =  [ [NSString alloc] initWithFormat:@"%.0f", _ACtopView.frame.size.height];
        
    }else{
         _viewACViewSettings.hidden = YES;
        
    }
    
    if (flagIsLandscape == 1) {
        viewEnvironment.frame  = CGRectMake( 645, 126, 382, 304 ); // landscape
        _viewEnvironmerntButtons.frame  = CGRectMake( 0, 256, 391, 43 );
    }else{
        viewEnvironment.frame  = CGRectMake( 0, 699, 400, 600 ); // portrait
        _viewEnvironmerntButtons.frame  = CGRectMake( 0, 279, 391, 49 );
    }

    
    if (displayWindow > 100) {
        
        _viewUniversalExtras.hidden = NO;
        if (flagIsLandscape == 1) {
            _trennerBottom.hidden = YES; _trennerVerticalBottom.hidden = YES;
            viewEnvironment.frame  = CGRectMake( 645, 126, 382, 304 ); // landscape
             _viewUniversalExtras.frame  = CGRectMake( 645, 419, 382, 283 );
            
        }else{
            _trennerBottom.hidden = NO; _trennerVerticalBottom.hidden = NO;
            viewEnvironment.frame  = CGRectMake( 0, 695, 390, 600 ); // portrait
            _viewUniversalExtras.frame  = CGRectMake( 390, 695, 390, 300 );
        }
        
    }else{
        _viewUniversalExtras.hidden = YES;
        if (flagIsLandscape == 1) {
             _trennerBottom.hidden = YES; _trennerVerticalBottom.hidden = YES;
        }        
        if (flagIsLandscape == 0 & configMode == 0) {
            _trennerBottom.hidden = NO; _trennerVerticalBottom.hidden = NO;
        }
        
    }
    if (flagShowCGEnvelopeValues == 1) {
         _trennerBottom.hidden = YES; _trennerVerticalBottom.hidden = YES;
    }
    
    
    if (configMode ==0) {
        _scrollViewTopDisplayButton.hidden = NO;
        
        
        
    }
     
    
    if (_viewFlightManager.hidden == NO) {
         _scrollViewTopDisplayButton.hidden = YES;
        _viewLegButtons.hidden = YES;
 
    }
    
    if (displayWindow == 10) {
        _scrollViewTopDisplayButton.hidden = YES;
        _viewLegButtons.hidden = YES;
       
    }
    

    
    // fuel arie ************************************************************************************
    
  
    
    
    specificFuelDensityValue = [_inputSpecificFuelMassPerVolume.text floatValue];
        
    
    if ([selectedUnitForFuel isEqualToString:@"lbs"]) {         
        _unitFuelFlow.text = @"lbs/h";        
        if ([fuelEnterMode isEqualToString:@"mass"]) {           
            _labelFuelUnitMainTank.text = @"lbs";
            _labelFuelUnitLandingFuel.text = @"lbs";            
            _labelFuelUnitOnBar.text = @"lbs";
            _labelMainFuelOnBar.text = _labelSliderFuelMain.text;
            _labelLandingFuelOnBar.text = _labelSliderFuelLanding.text;
            
        }else{ 
            _labelFuelUnitMainTank.text = @"Gal";
            _labelFuelUnitLandingFuel.text = @"Gal";            
            _labelFuelUnitOnBar.text = @"Gal";
            _labelMainFuelOnBar.text = _labelSliderFuelMain.text;
            _labelLandingFuelOnBar.text = _labelSliderFuelLanding.text;
        }
    }else{        
        _unitFuelFlow.text = @"kg/h"; 
        if ([fuelEnterMode isEqualToString:@"mass"]) {           
            _labelFuelUnitMainTank.text = @"kg";
            _labelFuelUnitLandingFuel.text = @"kg";
            _labelFuelUnitOnBar.text = @"kg";
            _labelMainFuelOnBar.text = _labelSliderFuelMain.text;
            _labelLandingFuelOnBar.text = _labelSliderFuelLanding.text;         
        }else{         
            _labelFuelUnitMainTank.text = @"Ltr";
            _labelFuelUnitLandingFuel.text = @"Ltr";           
            _labelFuelUnitOnBar.text = @"Ltr";
            _labelMainFuelOnBar.text = _labelSliderFuelMain.text;
            _labelLandingFuelOnBar.text = _labelSliderFuelLanding.text;
        }        
        
    }
    
    _labelMainOnBar.text = @"Main";
    _labelUsingSupplyFuelMain.hidden = YES;
    _labelUsingSupplyFuelLanding.hidden = YES;
    
    if ([[_arrayName25 objectAtIndex:21] isEqualToString:@"yes"]) {
        //subtract supply fuel        
        supplyFuelVolume = [[_arrayName25 objectAtIndex:19] floatValue] * factorApplyToNativeFuelVolumeGalLiter ;
                
        if (_sliderFuelMain1.value < supplyFuelVolume) {
            _labelUsingSupplyFuelMain.hidden = NO;
        }
        
        if (_sliderFuelLanding.value < supplyFuelVolume) {
            _labelUsingSupplyFuelLanding.hidden = NO;
        }
        
        _labelMainOnBar.text = @"Main + Supply";
        
        if ([fuelEnterMode isEqualToString:@"mass"]) {        
            _labelSliderFuelMain.text =  [ [NSString alloc] initWithFormat:@"%.0f", (_sliderFuelMain1.value - supplyFuelVolume) * [_inputSpecificFuelMassPerVolume.text floatValue] * factorApplyToNativeFuelWeight ];
            _labelSliderFuelLanding.text =  [ [NSString alloc] initWithFormat:@"%.0f", (_sliderFuelLanding.value - supplyFuelVolume) * [_inputSpecificFuelMassPerVolume.text floatValue] * factorApplyToNativeFuelWeight ];
        }else{        
            _labelSliderFuelMain.text =  [ [NSString alloc] initWithFormat:@"%.0f", (_sliderFuelMain1.value - supplyFuelVolume) * factorApplyToNativeFuelVolumeGalLiter ];        
            _labelSliderFuelLanding.text =  [ [NSString alloc] initWithFormat:@"%.0f", (_sliderFuelLanding.value - supplyFuelVolume) * factorApplyToNativeFuelVolumeGalLiter  ];        
        }
        
        
        if ([selectedUnitForFuel isEqualToString:@"lbs"]) {        
            _unitFuelFlow.text = @"lbs/h";
            
            if ([fuelEnterMode isEqualToString:@"mass"]) { 
                _labelFuelUnitOnBar.text = @"Total lbs";
                _labelMainFuelOnBar.text = [ [NSString alloc] initWithFormat:@"%.0f", (_sliderFuelMain1.value ) * [_inputSpecificFuelMassPerVolume.text floatValue] * factorApplyToNativeFuelWeight  ];
                _labelLandingFuelOnBar.text = [ [NSString alloc] initWithFormat:@"%.0f", (_sliderFuelLanding.value - supplyFuelVolume) * [_inputSpecificFuelMassPerVolume.text floatValue] * factorApplyToNativeFuelWeight  ];
                
            }else{ 
                     
                _labelFuelUnitOnBar.text = @"Total Gal";
                _labelMainFuelOnBar.text = [ [NSString alloc] initWithFormat:@"%.0f", _sliderFuelMain1.value   ];
                _labelLandingFuelOnBar.text = [ [NSString alloc] initWithFormat:@"%.0f", _sliderFuelLanding.value   ];
            }
        }else{        
            _unitFuelFlow.text = @"kg/h";      
            
            if ([fuelEnterMode isEqualToString:@"mass"]) {
                _labelFuelUnitOnBar.text = @"Total kg";
                _labelMainFuelOnBar.text =  [ [NSString alloc] initWithFormat:@"%.0f", (_sliderFuelMain1.value ) * [_inputSpecificFuelMassPerVolume.text floatValue] * factorApplyToNativeFuelWeight ];
                _labelLandingFuelOnBar.text =  [ [NSString alloc] initWithFormat:@"%.0f", (_sliderFuelLanding.value ) * [_inputSpecificFuelMassPerVolume.text floatValue] * factorApplyToNativeFuelWeight ];
                
                
            }else{      
                _labelFuelUnitOnBar.text = @"Total ltr";
                _labelMainFuelOnBar.text = [ [NSString alloc] initWithFormat:@"%.0f", _sliderFuelMain1.value   ];
                _labelLandingFuelOnBar.text = [ [NSString alloc] initWithFormat:@"%.0f", _sliderFuelLanding.value   ];
            }        
            
        }
        
        
    }else{
        
        
        if ([fuelEnterMode isEqualToString:@"mass"]) {        
            _labelSliderFuelMain.text =  [ [NSString alloc] initWithFormat:@"%.0f", _sliderFuelMain1.value * [_inputSpecificFuelMassPerVolume.text floatValue] * factorApplyToNativeFuelWeight ];
            _labelSliderFuelLanding.text =  [ [NSString alloc] initWithFormat:@"%.0f", _sliderFuelLanding.value  * [_inputSpecificFuelMassPerVolume.text floatValue] * factorApplyToNativeFuelWeight ];
        }else{        
            _labelSliderFuelMain.text =  [ [NSString alloc] initWithFormat:@"%.0f", _sliderFuelMain1.value * factorApplyToNativeFuelVolumeGalLiter ];        
            _labelSliderFuelLanding.text =  [ [NSString alloc] initWithFormat:@"%.0f", _sliderFuelLanding.value * factorApplyToNativeFuelVolumeGalLiter  ];        
        } 
        
        
    }
 
    
    // fuel arie ************************************************************************************
  

    
  

    
    
    
    if (flagUsingAlternateEquipment ==0) {
        //_mani_Configuration.text = arrayConfigurations[configuration];        
    }else{
        //_mani_Configuration.text = _dropDownAvailableCallsigns.text;
    }
    
    
    connectedToFleetControl = 1;    
    if (connectedToFleetControl == 1) {        
        listStatusIsOnline = 1; 
    }else{        
        listStatusIsOnline = 0;        
        HeliDataLoaded = 0;        
    }
    
    
    _labelFuelMainPercent.text =  [ [NSString alloc] initWithFormat:@"%.0f", (100.0/tankCapacityVolume) * _sliderFuelMain1.value ];    
    _labelFuelLandingPercent.text =  [ [NSString alloc] initWithFormat:@"%.0f", (100.0/tankCapacityVolume) * _sliderFuelLanding.value ];    
    _labelKIAS.text = [ [NSString alloc] initWithFormat:@"%.0f", _sliderKIAS.value];    
    //NSLog(@"formatString1 %@", formatString1);
    
    _labelHeadwind2.text = [ [NSString alloc] initWithFormat:formatString1, _sliderHeadwind2.value];
    _labelSliderIAS.text = [ [NSString alloc] initWithFormat:formatString2, _sliderIAS.value];
    _labelSliderRatingIndex.text = [ [NSString alloc] initWithFormat:formatString3, _sliderRatingIndex.value];
    _labelSliderPROPRPM.text = [ [NSString alloc] initWithFormat:formatString4, _sliderPROPRPM.value];
   
       
    //float OATCelsius = OAT;    
    float fahrenheit = (OAT * 1.8) + 32;
    _labelOATinFahrenheit.text = [ [NSString alloc] initWithFormat:@"%.0fºF", fahrenheit];  
    // Environment ALTIMETRY
    float QNHEuro = sliderQNH.value * 33.86530749;
    
   
 
    if ( [unitsAltimeter isEqualToString:@"US"]) {          
        labelQNHEuro.text = [ [NSString alloc] initWithFormat:@"%.2f", sliderQNH.value];    
        labelQNH.text = [ [NSString alloc] initWithFormat:@"%.1f", QNHEuro]; 
        _labelUnitQNHmain.text = @"IN.Hg";        
    }else{        
        labelQNHEuro.text = [ [NSString alloc] initWithFormat:@"%.1f", QNHEuro];    
        labelQNH.text = [ [NSString alloc] initWithFormat:@"%.2f", sliderQNH.value]; 
        _labelUnitQNHmain.text = @"hPA";        
    }
    
    
    
    
    // MSL slider ****   ****   ****   ****   ****   ****   ****   ****   ****
    
    
    
    //float MSL = sliderHp.value - ((29.92- sliderQNH.value) * 1000);
    
    
    float MSL = _sliderMSL.value;
    
    float paCalc = ((29.92 - sliderQNH.value) *1000);
    if (paCalc < 0.001 & paCalc > -0.001) {
        paCalc = 0;
    }
    
     
    
    sliderHp.value = MSL + paCalc;
        
    MSLfeet.text = [ [NSString alloc] initWithFormat:@"%.0f", MSL];   
    _labelUnitsMSL.text = @"ft";    
    _MSLmeter.text = [ [NSString alloc] initWithFormat:@"= %.0fm", MSL * 0.3048]; 
    MSLtoHpDifference = MSL - sliderHp.value;    
    // animate Hp Lines
    _graphicHpLines.center = CGPointMake( 322, 318 - (MSLtoHpDifference * 0.023)  );
    displayHeliRegistration.text = vFlightRegistration.text ;
    
    if (displayWindow ==1  ) {  
        [buttonDisplayEnvironment setBackgroundImage:buttonBlue forState:UIControlStateNormal];
    } else {        
        [buttonDisplayEnvironment setBackgroundImage:buttonGrey forState:UIControlStateNormal];        
    }  
    // check for options
    
    if ( [[_arrayName2 objectAtIndex: lineOptions + 1 ] isEqualToString:@"0"]  ) {
        
        flagSlump = 0;
        
    }else{
        
        flagSlump = 1;
        
    }
    
    if ( [[_arrayName2 objectAtIndex: lineOptions + 2 ] isEqualToString:@"0"]  ) {
        
        flagSkies = 0;
        
    }else{
        
        flagSkies = 1;
        
    }
    
    
   
    
    
    // ************************************   Fuel Flow  **********************************************************************
    
    
  
    
    
   
    
    
    // crosses ***************************************************************************************
    
    

    // robinson fuel specials
    if ([AC_Type rangeOfString:@"R44Raven"].location != NSNotFound   || [AC_Type rangeOfString:@"R44Cadet"].location != NSNotFound  || [AC_Type rangeOfString:@"R22Beta"].location != NSNotFound  ) {
        _viewRobinsonFuelPanel.hidden = NO;
        float totalFuel = _sliderFuelMain1.value;
        auxshare =0;
        mainshare =0;
        float tankVolumeTotal   = 0;
        float tankVolumeMain    = 0;
        float tankVolumeAux     = 0;   
        float wonderValue = 0;
         
       
        
         if ([AC_Type rangeOfString:@"R22Beta"].location != NSNotFound  ) {             
             tankVolumeTotal     = [[_arrayName21 objectAtIndex:17] floatValue];
             tankVolumeMain      = tankVolumeTotal/100 * 64.1; // 63.44%
             tankVolumeAux       = tankVolumeTotal/100 * 35.9;// 36.55%             
             wonderValue = 4; 
         }else{
             tankVolumeTotal     = [[_arrayName21 objectAtIndex:17] floatValue];
             tankVolumeMain      = tankVolumeTotal/100 * 63.44; // 63.44%
             tankVolumeAux       = tankVolumeTotal/100 * 36.55; // 36.55%
             wonderValue = 7.0; 
         }
        
        //NSLog(@"tankVolumeTotal %f", tankVolumeTotal);
        
        
        if (totalFuel <= wonderValue) {
            auxshare = 0; mainshare = totalFuel;        
        }else {            
            float fuelToShare = totalFuel - wonderValue ;  // 44.3 = 46.5 - 4.6  und 4.6 ist das was im Tank drin ist am Anfang        
            float faktorTank = (tankVolumeTotal - wonderValue) / tankVolumeAux;        
            float fuelAux = fuelToShare / faktorTank;// (bei max ist das  17.0!)        
            auxshare = fuelAux; mainshare = wonderValue + (fuelToShare - fuelAux);
        }   
        
        float mainshareradiants = 0;
        float auxshareradiants = 0;    
        float gaugedegree = 100;    
        mainshareradiants =  ( ( (gaugedegree / tankVolumeMain) * mainshare ) -  (gaugedegree/2)  )  * 0.01745;    
        auxshareradiants =    ( ( (gaugedegree / tankVolumeAux) * auxshare ) -   (gaugedegree/2)  )  * 0.01745;
        
    
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.1];
        _robinsonFuelNeedleMain.transform =CGAffineTransformMakeRotation(mainshareradiants);    
        _robinsonFuelNeedleAux.transform =CGAffineTransformMakeRotation(auxshareradiants);    
        [UIView commitAnimations];
     
        
        if ([selectedUnitForFuel isEqualToString:@"kg"]) {          
            if ([fuelEnterMode isEqualToString:@"mass"]) {
                _labelRobinsonTankMain.text = [ [NSString alloc] initWithFormat:@"%.1f kg", mainshare * factorApplyToNativeFuelWeight * [_inputSpecificFuelMassPerVolume.text floatValue] ]; 
                _labelRobinsonTankAux.text = [ [NSString alloc] initWithFormat:@"%.1f kg", auxshare * factorApplyToNativeFuelWeight * [_inputSpecificFuelMassPerVolume.text floatValue] ]; 
            }else{
                _labelRobinsonTankMain.text = [ [NSString alloc] initWithFormat:@"%.1f ltr", mainshare * factorApplyToNativeFuelVolumeGalLiter]; 
                _labelRobinsonTankAux.text = [ [NSString alloc] initWithFormat:@"%.1f ltr", auxshare * factorApplyToNativeFuelVolumeGalLiter];                 
            }
            
        }else{         
            if ([fuelEnterMode isEqualToString:@"mass"]) {
                _labelRobinsonTankMain.text = [ [NSString alloc] initWithFormat:@"%.1f lbs", mainshare * [_inputSpecificFuelMassPerVolume.text floatValue] ]; 
                _labelRobinsonTankAux.text = [ [NSString alloc] initWithFormat:@"%.1f lbs", auxshare * [_inputSpecificFuelMassPerVolume.text floatValue]]; 
            }else{
                _labelRobinsonTankMain.text = [ [NSString alloc] initWithFormat:@"%.1f Gal", mainshare ]; 
                _labelRobinsonTankAux.text = [ [NSString alloc] initWithFormat:@"%.1f Gal", auxshare ];                 
            } 
        }
        
        _labelRobsinonEndurance.text = [ [NSString alloc] initWithFormat:@"%@ h", _labelEnduranceHoursMinutes.text    ]; 

        
        totalFuel = _sliderFuelLanding.value;
        if (totalFuel <= wonderValue) {
            auxshareLND = 0; mainshareLND = totalFuel;        
        }else {            
            float fuelToShare = totalFuel - wonderValue ;  // 44.3 = 46.5 - 4.6  und 4.6 ist das was im Tank drin ist am Anfang        
            float faktorTank = (tankVolumeTotal - wonderValue) / tankVolumeAux;        
            float fuelAux = fuelToShare / faktorTank;// (bei max ist das  17.0!)        
            auxshareLND = fuelAux; mainshareLND = wonderValue + (fuelToShare - fuelAux);
        }  
        
        
    }else{
        // fuel bar 
        _fuelBarMain.layer.anchorPoint = CGPointMake(0.5, 1);    
        float totalFuelPercent = (100.0/tankCapacityVolume) * _sliderFuelMain1.value; 
        fuelPercent = totalFuelPercent;
        float TotalFuelBarHeight = (10.1 / 100) * totalFuelPercent;          
        _fuelBarMain.layer.transform = CATransform3DMakeScale(1, TotalFuelBarHeight, 0);  
        _fuelBarLanding.layer.anchorPoint = CGPointMake(0.5, 1);    
        totalFuelPercent = (100.0/tankCapacityVolume) * _sliderFuelLanding.value;    
        TotalFuelBarHeight = (10.1 / 100) * totalFuelPercent;    
        _fuelBarLanding.layer.transform = CATransform3DMakeScale(1, TotalFuelBarHeight, 0);   
        
    }
    

    [self calculateListo];  // from mainRoutine
    [self updateSeatButtonLabels];
    
    
    
    // CG WARNINGS ********************************************************************************************
    
    [self calculateCGLimits];
    
    
    // labels  lat and long ***************************************************************************************
    
    labelWeightTakeoff.text     = [ [NSString alloc] initWithFormat:@"%.0f", vTOW  * factorApplyToNativeWeightforItems ];    
    labelWeightLanding.text     = [ [NSString alloc] initWithFormat:@"%.0f", vLDW * factorApplyToNativeWeightforItems ];
    _labelWeightLanding2.text     = labelWeightLanding.text;
    _labelWeightTakeoff2.text     = labelWeightTakeoff.text;
    
    
    if ([selectedUnitForItems isEqualToString:@"kg"]) {
        _labelKgLbsEditStation.text = @"kg";
        _labelKgLbsEditStation2.text = @"kg";
        _labelKgLbsEditStation3.text = @"kg";
        _labelUnitLongEditStation.text = @"mm";
        _labelUnitLatEditStation.text = @"mm";
        
        if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
            // if meter
            labelCGTakeoff.text         = [ [NSString alloc] initWithFormat:@"%.2f", vTOWArm ];
            labelCGLanding.text         = [ [NSString alloc] initWithFormat:@"%.2f", vLDWArm ];
            labelCGZeroFuel.text        = [ [NSString alloc] initWithFormat:@"%.2f", lZFWArm ];
        }else{
            labelCGTakeoff.text         = [ [NSString alloc] initWithFormat:@"%.0f", vTOWArm * factorApplyToNativeDistanceInchMM ];
            labelCGLanding.text         = [ [NSString alloc] initWithFormat:@"%.0f", vLDWArm * factorApplyToNativeDistanceInchMM ];
            labelCGZeroFuel.text        = [ [NSString alloc] initWithFormat:@"%.0f", lZFWArm * factorApplyToNativeDistanceInchMM ];
        }
    }else{
        _labelKgLbsEditStation.text = @"lbs";
        _labelKgLbsEditStation2.text = @"lbs";
        _labelKgLbsEditStation3.text = @"lbs";
        _labelUnitLongEditStation.text = @"In.";
        _labelUnitLatEditStation.text = @"In.";
        labelCGTakeoff.text         = [ [NSString alloc] initWithFormat:@"%.1f", vTOWArm * factorApplyToNativeDistanceInchMM];
        labelCGLanding.text         = [ [NSString alloc] initWithFormat:@"%.1f", vLDWArm * factorApplyToNativeDistanceInchMM ];
        labelCGZeroFuel.text        = [ [NSString alloc] initWithFormat:@"%.1f", lZFWArm * factorApplyToNativeDistanceInchMM];
    }
    labelWeightZeroFuel.text    = [ [NSString alloc] initWithFormat:@"%.0f", lZFW * factorApplyToNativeWeightforItems ];
    
    if ([selectedUnitForItems isEqualToString:@"kg"]) {
        
        if (CGLATTOW > 0) {
            labelCGLat.text = [ [NSString alloc] initWithFormat:@"%.1f", (vTOWArmLat * 100) * factorApplyToNativeDistanceInchMM ];
        } else {
            labelCGLat.text = [ [NSString alloc] initWithFormat:@"%.1f", (vTOWArmLat * 100) * factorApplyToNativeDistanceInchMM ];
        }            
    } else {                
        if (CGLATTOW > 0) {
            labelCGLat.text = [ [NSString alloc] initWithFormat:@"%.1f", vTOWArmLat * factorApplyToNativeDistanceInchMM ];
        } else {
            labelCGLat.text = [ [NSString alloc] initWithFormat:@"%.1f", vTOWArmLat * factorApplyToNativeDistanceInchMM ];
        }                
    }
    
    
   
    
    // *********************************************************************************************************
    // ******************************** calc performance ********************************************************
    // *********************************************************************************************************
    
    
    
    
    [self  iEnviCalcALL];
    
    [self checkButtonFlight];
    
    [self checkButtonMainPage];
  
    
    [self checkButtonSetup];
    
    [self checkButtonManifeest];
    
    [self checkButtonSummaryManifest];
    
       
    [self calcPerformance];

    if (displayWindow > 100){
        
        [viewMain bringSubviewToFront:_viewUniversalExtras];
        
    }
    
    if (amountofButtonsNeeded < 1) {
        //NSLog(@"here 1");
        _viewButtonAutoCalcMode.hidden = YES; 
    }
    
    
    
    // *********************************************************************************************************
    // ******************************** check if red warnings on ***********************************************
    // *********************************************************************************************************
    
    
    float warningTrigger = 0;
    
    for (int i = 1; i < amountOfButtons+1; i++) {
        
        UIButton* button = (UIButton *)[self.viewTopDisplayButtons viewWithTag: i];
        
        UIImage *img = button.currentBackgroundImage ;
    
        if(img == [UIImage imageNamed:@"button_red.png" ]){
            
            //NSLog (@"warning on !!!! ");
            
            warningTrigger = 1;
        }
        
       
    }
    
    
    if (warningTrigger == 1) {
        
        if (flagIsLandscape == 1) {
            UIImage *triangle = [UIImage imageNamed:@"triangle red.png"];
            
            [_triangleWhite setBackgroundImage:triangle forState:UIControlStateNormal];

        }else{
            UIImage *triangle = [UIImage imageNamed:@"triangle red down.png"];
            
            [_triangleWhite setBackgroundImage:triangle forState:UIControlStateNormal];
            
        }
        
        
        /*
        self.triangleWhite.alpha = 0.2;
        
        [UIView animateWithDuration:0.5 delay:0.2 options:UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse animations:^{
            self.triangleWhite.alpha = 1.0;
            
        } completion:nil];
         
         */

    }else{
        
        if (flagIsLandscape == 1) {            
            UIImage *triangle = [UIImage imageNamed:@"triangle white.png"];            
            [_triangleWhite setBackgroundImage:triangle forState:UIControlStateNormal];            
        }else{
            UIImage *triangle = [UIImage imageNamed:@"triangle white down.png"];            
            [_triangleWhite setBackgroundImage:triangle forState:UIControlStateNormal];
            
        }
        
    }
    
    
    // *********************************************************************************************************
    // ******************************** calc second  max avail   ***********************************************
    // *********************************************************************************************************
    
    
     _label2AvailableExternalLoad.hidden = YES;
    if (![[_arrayName25 objectAtIndex:25] isEqualToString:@""] & ![[_arrayName23 objectAtIndex:29] isEqualToString:@"yes"]) {         
         [self calcSecondMaxExternalLoad];
    }
    
    // *********************************************************************************************************
    // ******************************** NVG / NIGHT MODE   *****************************************************
    // *********************************************************************************************************
    
    
    _labelNVGpercent.text = [ [NSString alloc] initWithFormat:@"%.0f %%", _sliderNVG.value  ];
    
    
    if (nvgMode == 1) {
        
        //NSLog(@"nightMode ON");
        
        _switchNVG.on = YES;
        
        _viewFilterNVG.hidden = NO; [viewOne bringSubviewToFront:_viewFilterNVG];
        
        [self prefersStatusBarHidden];
        
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
        
        _viewFilterNVG.alpha = _sliderNVG.value/100;
        
        
    }else{
        
        
        //NSLog(@"nightMode OFF");
        
        
        _viewFilterNVG.hidden = YES;
        
        _switchNVG.on = NO;
        
    }

    
  
    
    if (_segmentCGAutoCheck.selectedSegmentIndex == 1) {
        [self autoCheckFWDAFTCG];
    }else{
        _labelCGWarning.hidden = YES;
        
      

    }
    
  
    
    
   

    
    
}


- (void) makeFreakViewShape1 {
    
   //NSLog(@"makeFreakViewShape" );
    
    MTOWfromEnvelope = 0;
    
    float numberOfPoints = 0;
    pathCGenvelope = [UIBezierPath bezierPath];
    for (int i = 7; i < _arrayCG1.count ; i++) { /// make path
        
        // get point coordinates
        NSString *Xstring     = [_arrayCG1 objectAtIndex: i ];
        NSString *searchKeyword = @"/";
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        float xCGpos = 0;
        float yCGpos = 0;
        
        if(rangeOfYourString.location == NSNotFound) {
            // error condition — the text searchKeyword wasn't in 'string'
        }else{
            if (numberOfPoints == 0) { // first point only
                xCGpos = [ [Xstring substringToIndex:rangeOfYourString.location] floatValue];
                yCGpos = [ [Xstring substringFromIndex:rangeOfYourString.location+1] floatValue];
                [pathCGenvelope moveToPoint:CGPointMake( xCGpos, yCGpos )];
            }else{
                xCGpos = [ [Xstring substringToIndex:rangeOfYourString.location] floatValue];
                yCGpos = [ [Xstring substringFromIndex:rangeOfYourString.location+1] floatValue];
                [pathCGenvelope addLineToPoint:CGPointMake( xCGpos, yCGpos )];
            }
            
            if (yCGpos > MTOWfromEnvelope) {
                MTOWfromEnvelope = yCGpos;
            }
            
            
            numberOfPoints = numberOfPoints + 1;            
        }// end add to path
    }// end for next make path
    
    shapeLayerFreakViewCG1 = [CAShapeLayer layer];
    shapeLayerFreakViewCG1.path = [pathCGenvelope CGPath];
    return;
}


- (void) makeFreakViewShape2 {
    
    //NSLog(@"makeFreakViewShape" );
    
    float numberOfPoints = 0;
    pathCGenvelope = [UIBezierPath bezierPath];
    for (int i = 7; i < _arrayCG2.count ; i++) { /// make path
        
        // get point coordinates
        NSString *Xstring     = [_arrayCG2 objectAtIndex: i ];
        NSString *searchKeyword = @"/";
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        float xCGpos = 0;
        float yCGpos = 0;
        
        if(rangeOfYourString.location == NSNotFound) {
            // error condition — the text searchKeyword wasn't in 'string'
        }else{
            if (numberOfPoints == 0) { // first point only
                xCGpos = [ [Xstring substringToIndex:rangeOfYourString.location] floatValue];
                yCGpos = [ [Xstring substringFromIndex:rangeOfYourString.location+1] floatValue];
                [pathCGenvelope moveToPoint:CGPointMake( xCGpos, yCGpos )];
            }else{
                xCGpos = [ [Xstring substringToIndex:rangeOfYourString.location] floatValue];
                yCGpos = [ [Xstring substringFromIndex:rangeOfYourString.location+1] floatValue];
                [pathCGenvelope addLineToPoint:CGPointMake( xCGpos, yCGpos )];
            }
            numberOfPoints = numberOfPoints + 1;
        }// end add to path
    }// end for next make path
    
    shapeLayerFreakViewCG2 = [CAShapeLayer layer];
    shapeLayerFreakViewCG2.path = [pathCGenvelope CGPath];
    return;
}


- (void) makeFreakViewShapeMargin {
    
    
    float marginCGx = [_inputSafetyMargin.text floatValue];
    
    //NSLog(@"makeFreakViewShapeMargin" );
    
    
    float numberOfPoints = 0;
    int flagfirstMoveToRight = 0;
    
    //NSLog(@"******************************************************************************" );
    
    pathCGenvelope = [UIBezierPath bezierPath];
    
    for (int i = 7; i < _arrayCG1MarginLine.count ; i++) { /// make path for freak
     
        
        NSString *Xstring     = [_arrayCG1MarginLine objectAtIndex: i ];
        NSString *searchKeyword = @"/";
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
        
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        
        NSString *XstringNext     = [_arrayCG1MarginLine objectAtIndex: i+1];
        if ([XstringNext isEqualToString: @""]) {
            XstringNext = Xstring;
        }
        
        searchKeyword = @"/";
        NSRange rangeOfYourStringNext = [XstringNext rangeOfString:searchKeyword];
        
        
        float xCGpos = 0;
        float yCGpos = 0;
        
        float xCGposNext = 0;
        float yCGposNext = 0;
        
        float xCGposMargined = 0;
        float yCGposMargined = 0;
        
        
        if(rangeOfYourString.location == NSNotFound)
        {
            // error condition — the text searchKeyword wasn't in 'string'
        }
        else{
            
            xCGpos = [ [Xstring substringToIndex:rangeOfYourString.location] floatValue];
            yCGpos = [ [Xstring substringFromIndex:rangeOfYourString.location+1] floatValue];
            
            xCGposNext = [ [XstringNext substringToIndex:rangeOfYourStringNext.location] floatValue];
            yCGposNext = [ [XstringNext substringFromIndex:rangeOfYourStringNext.location+1] floatValue];

            
            int caseIsFound = 0;
            
            if (xCGpos < xCGposNext & yCGpos < yCGposNext) {
                caseIsFound = 1;
                //NSLog(@"moving to the right and up" );
                xCGposMargined = xCGpos + marginCGx ;
                yCGposMargined = yCGpos;
            }
            
            if (xCGpos == xCGposNext & yCGpos < yCGposNext) {
                caseIsFound = 1;
                //NSLog(@"not moving and up" );
                xCGposMargined = xCGpos + marginCGx ;
                yCGposMargined = yCGpos;
            }
            
            if (xCGpos == xCGposNext & yCGpos > yCGposNext) {
                caseIsFound = 1;
                //NSLog(@"not moving and down" );
                xCGposMargined = xCGpos - marginCGx;
                yCGposMargined = yCGpos;
            }
            
            
            if (xCGpos < xCGposNext & yCGpos == yCGposNext) {
                caseIsFound = 1;
                //NSLog(@"moving to the right and steady" );
                xCGposMargined = xCGpos + marginCGx;
                yCGposMargined = yCGpos;
                if (flagfirstMoveToRight == 0) {
                    //NSLog(@"moving to the right and steady first time" );
                    xCGposMargined = xCGpos + marginCGx;
                    yCGposMargined = yCGpos;
                    flagfirstMoveToRight = 1;
                }else{
                    //NSLog(@"moving to the right and steady second time " );
                    xCGposMargined = xCGpos - marginCGx;
                    yCGposMargined = yCGpos;
                }
            }
            
            
            if (xCGpos < xCGposNext & yCGpos > yCGposNext) {
                caseIsFound = 1;
                //NSLog(@"moving to the right and down" );
                xCGposMargined = xCGpos - marginCGx;
                yCGposMargined = yCGpos;
            }
            
            if (xCGpos > xCGposNext & yCGpos == yCGposNext) {
                caseIsFound = 1;
                //NSLog(@"moving to the left  and steady" );
                xCGposMargined = xCGpos - marginCGx;
                yCGposMargined = yCGpos;
            }
            
            if (xCGpos > xCGposNext & yCGpos < yCGposNext) {
                caseIsFound = 1;
                //NSLog(@"moving to the left and up" );
                xCGposMargined = xCGpos + marginCGx;
                yCGposMargined = yCGpos;
            }
            
            if (xCGpos > xCGposNext & yCGpos > yCGposNext) {
                caseIsFound = 1;
                //NSLog(@"moving to the left and down" );
                xCGposMargined = xCGpos - marginCGx;
                yCGposMargined = yCGpos;
            }
            
            
            if (xCGpos == xCGposNext & yCGpos == yCGposNext) {
                caseIsFound = 1;
                //NSLog(@"moving back to start" );
                xCGposMargined = xCGpos + marginCGx;
                yCGposMargined = yCGpos;
            }
            

            if (caseIsFound == 0) {
               //NSLog(@"---------------------------------------------- FREAK caseIsFound 0");
            }
            
            if (numberOfPoints == 0) { // first point only
                [pathCGenvelope moveToPoint:CGPointMake( xCGposMargined, yCGposMargined )];
                
                 //NSLog(@"xCGposMargined %f " ,xCGposMargined );
            }else{
                 [pathCGenvelope addLineToPoint:CGPointMake( xCGposMargined, yCGposMargined )];
            }
            
            
            numberOfPoints = numberOfPoints + 1;
            
            
        }// end add to path
        
        
        
    }// end for next make path
    
    
    
    shapeLayerFreakViewCG1Margin = [CAShapeLayer layer];
    shapeLayerFreakViewCG1Margin.path = [pathCGenvelope CGPath];
    shapeLayerFreakViewCG1Margin.strokeColor = [[UIColor colorWithRed:255.0/255.0f green:218.0/255.0f blue:0.0/255.0f alpha:1.0f] CGColor];
    if (colorModeForCGenvelope == 0) {  shapeLayerFreakViewCG1Margin.strokeColor =[[UIColor colorWithRed:255.0/255.0f green:218.0/255.0f blue:0.0/255.0f alpha:1.0f] CGColor];  }else{ shapeLayerFreakViewCG1Margin.strokeColor = [[UIColor redColor] CGColor];    }
    shapeLayerFreakViewCG1Margin.lineWidth = 5.5;
    shapeLayerFreakViewCG1Margin.fillColor = [[UIColor clearColor] CGColor];
    //[self.cgFreakView.layer addSublayer:shapeLayerFreakViewCG1];
    
    return;
    
    
    
}




- (void) calculateCGLimits {
    
    
    
    //forward
    
    float cgFWDlimit = 0;
    
    if (weightTOW >= 8800) { cgFWDlimit = ( weightTOW - -70219.6078431373 ) / 607.843137254903  ;  ;}
    
    if (weightTOW < 8800) { cgFWDlimit = 130.0 ;}
    
    
    _cgFWDlimit.text =  [ [NSString alloc] initWithFormat:@"%.1f", cgFWDlimit  ];
    
    
    float cgAftlimit = 0;
    
    if (weightTOW >= 8800) { cgAftlimit = ( weightTOW - 180492.307692308 ) / -1192.30769230769  ; ;}
    
    
    if (weightTOW < 8800) {cgAftlimit = 144.0 ;}
    
    _cgAFTlimit.text =  [ [NSString alloc] initWithFormat:@"%.1f", cgAftlimit  ];

    
    
    //NSLog(@"_cgFWDlimit  %@f", _cgFWDlimit.text);
    
    //NSLog(@"_cgAFTlimit  %@f", _cgAFTlimit.text);
    
}


- (void) findMaxEnternalLoad {
    
    // this is not calcMaxEnternalLoad !!!!!!!!!!!
    
    //NSLog(@"findMaxEnternalLoad");
          
    float merkerWeightTOW = weightTOW;
    float merkerCGLongTOW = CGLongTOW;
    
    int lineUsedForExternalLoad = lineHoistLoad;
    
    // check "Depends on Display Button"
    if ([[_arrayName25 objectAtIndex:27]length]> 3) {
        lineUsedForExternalLoad = lineRelevantForExternalLoad;
    }
    //NSLog(@"lineUsedForExternalLoad %.1d", lineUsedForExternalLoad);
    //NSLog(@"lineHoistLoad %.1f", lineHoistLoad);
    
    // get current externalLoad
    float currentExternalLoadWeight = [[_arrayName2 objectAtIndex:lineUsedForExternalLoad] floatValue]; // weight
    float currentExternalLoadArm = [[_arrayName3 objectAtIndex:lineUsedForExternalLoad] floatValue]; // arm
    float currentExternalLoadMoment = currentExternalLoadWeight * currentExternalLoadArm;
        
    //NSLog(@"currentExternalLoadArm %.1f", currentExternalLoadArm);
    //NSLog (@"mostFWDCGpoint %.0f", mostFWDCGpoint);
    // take external load out of equation
    //float startTOW = merkerWeightTOW - currentExternalLoadWeight;
    //float startTOMoment = merkerMomTOW - currentExternalLoadMoment;
    
    float startTOW = mostFWDweight - currentExternalLoadWeight;
    float startTOMoment = (mostFWDweight * mostFWDCGpoint) - currentExternalLoadMoment;
    
    int totalStepsHoistCheck = 0;
    float searchWeightFactor = 1;
    flagReportEnvelopeExceeded = 0;
    
    maxMTOWforHoist = MTOWfromEnvelope - (merkerWeightTOW - currentExternalLoadWeight);
    
    //NSLog(@"MTOWfromEnvelope %.1f", MTOWfromEnvelope);
    //NSLog(@"merkerWeightTOW %.1f", merkerWeightTOW);
    //NSLog(@"currentExternalLoadWeight %.1f", currentExternalLoadWeight);    
    //NSLog(@"1 maxMTOWforHoist %f", maxMTOWforHoist);
    
    if (maxMTOWforHoist > restrictingHoistWeight) {
        maxMTOWforHoist = restrictingHoistWeight;
    }
    
    //NSLog(@"restrictingHoistWeight %f", restrictingHoistWeight);
    //NSLog(@"2 maxMTOWforHoist %f", maxMTOWforHoist);
    
    float availableHoistLoadCGCheck = 0;
    
    for (float searchWeight = 0; searchWeight < 10000; searchWeight++) {
        
        totalStepsHoistCheck = totalStepsHoistCheck + 1;
        //NSLog(@"searchWeight %.1f", searchWeight * searchWeightFactor);
        float searchMoment = (searchWeight * searchWeightFactor) * currentExternalLoadArm;
        float checkWeightTOW = startTOW + (searchWeight * searchWeightFactor) ;
        float checkMoment = startTOMoment + searchMoment;
        float checkCG = checkMoment / checkWeightTOW;
        weightTOW = checkWeightTOW;
        CGLongTOW = checkCG;
        //NSLog(@"TOW  %.1f", weightTOW);
        //NSLog(@"CGLongTOW  %.1f", CGLongTOW);
        
        // go check ******************************************************************************
        [self checkCGwarningLongitudinalForHOIST: CGLongTOW transferWeightTOW:weightTOW ];
        // ***************************************************************************************
        
        if (flagReportEnvelopeExceeded == 1 ) {
            availableHoistLoadCGCheck = (searchWeight * searchWeightFactor) -  searchWeightFactor;
            //NSLog(@"found availableHoistLoadCGCheck %.1f",availableHoistLoadCGCheck);
            break;
        }
        
    }// end loop
    
    
    //NSLog(@"****************");
    
  
    
    // take lowest
    
    NSString *maxAvailLoadName = @"Max. Hoist:";
    if ([[_arrayName25 objectAtIndex:29]length] > 3) {        
        maxAvailLoadName = [_arrayName25 objectAtIndex:29];
    }
    
    //NSLog(@"maxMTOWforHoist %f", maxMTOWforHoist);    
    //NSLog(@"maxHoistLoad %f", maxHoistLoad);    
    //NSLog(@"availableHoistLoadCGCheck %f", availableHoistLoadCGCheck);
   
    _labelAvailableExternalLoad.adjustsFontSizeToFitWidth = YES;
    
    if (maxMTOWforHoist < availableHoistLoadCGCheck) {
       //NSLog(@"h1");
        availableExternalLoad = maxMTOWforHoist;
        _labelAvailableExternalLoad.text = [ [NSString alloc] initWithFormat:@"%@ %.0f%@", maxAvailLoadName, availableExternalLoad - currentExternalLoadWeight, selectedUnitForItems];
    }else{
        //NSLog(@"h2");
        availableExternalLoad = availableHoistLoadCGCheck;
        _labelAvailableExternalLoad.text = [ [NSString alloc] initWithFormat:@"%@ %.0f%@", maxAvailLoadName, availableExternalLoad - currentExternalLoadWeight, selectedUnitForItems ];
    }
    
    if (maxHoistLoad < maxMTOWforHoist & maxHoistLoad < availableHoistLoadCGCheck) {
        //NSLog(@"h3");
        availableExternalLoad = maxHoistLoad;
        _labelAvailableExternalLoad.text = [ [NSString alloc] initWithFormat:@"%@ %.0f%@", maxAvailLoadName, availableExternalLoad - currentExternalLoadWeight, selectedUnitForItems ];
    }
    
    
    if (maxHoistLoad < maxMTOWforHoist & maxHoistLoad < availableHoistLoadCGCheck & OAT < 0) {
        //NSLog(@"h4");
        availableExternalLoad = maxHoistLoad;
        _labelAvailableExternalLoad.text = [ [NSString alloc] initWithFormat:@"%@ %.0f%@", maxAvailLoadName, availableExternalLoad - currentExternalLoadWeight, selectedUnitForItems ];
    }
    
    
    if (flagReportEnvelopeExceeded == 2) {
        //NSLog(@"h5");
        availableExternalLoad = availableHoistLoadCGCheck;
        _labelAvailableExternalLoad.text = [ [NSString alloc] initWithFormat:@"%@: %.0f%@ (LATERAL)", maxAvailLoadName, availableExternalLoad - currentExternalLoadWeight, selectedUnitForItems];
    }
    
    
    
    //NSLog(@"availableExternalLoad %.0f", availableExternalLoad);
    
    
    
    
    
    if (currentExternalLoadWeight > availableExternalLoad ) {
        _labelAvailableExternalLoad.backgroundColor = [UIColor redColor];        
        _labelAvailableExternalLoad.text = [ [NSString alloc] initWithFormat:@"%@: Exceeded!", maxAvailLoadName ];
        _labelAvailableExternalLoad.textColor = [UIColor whiteColor];
        if (currentExternalLoadWeight < 1) {            
            _labelAvailableExternalLoad.text = [ [NSString alloc] initWithFormat:@"%@: 0%@", maxAvailLoadName, selectedUnitForItems ];
            _labelAvailableExternalLoad.backgroundColor = [UIColor greenColor];
            _labelAvailableExternalLoad.textColor = [UIColor blackColor];
        }
    }else{
        _labelAvailableExternalLoad.backgroundColor = [UIColor greenColor];
        _labelAvailableExternalLoad.textColor = [UIColor blackColor];
    }
    
    
    
    // restore
    CGLongTOW = merkerCGLongTOW;
    weightTOW = merkerWeightTOW;
    [self checkCGwarningLongitudinal: CGLongTOW transferWeightTOW:weightTOW ];
    
    
}



- (void) calcMaxEnternalLoad {
    
    //NSLog(@"calcMaxEnternalLoad *********");
    
 
    // get current externalLoad
    float currentExternalLoadWeight = [[_arrayName2 objectAtIndex:lineRelevantForExternalLoad] floatValue]; // weight 
        
    availableExternalLoad = MTOWfromEnvelope - (weightTOW - currentExternalLoadWeight); // was = availableExternalLoad = MTOWfromEnvelope - (weightTOW - currentExternalLoadWeight);
       
    if (MTOWfromEnvelope - weightTOW > [[_arrayName9 objectAtIndex:lineRelevantForExternalLoad]floatValue]) {  
       
        availableExternalLoad = [[_arrayName9 objectAtIndex:lineRelevantForExternalLoad]floatValue];        
        _labelAvailableExternalLoad.text = [ [NSString alloc] initWithFormat:@"%@:> %.0fkg", maxExternalLoadString, [[_arrayName9 objectAtIndex:lineRelevantForExternalLoad]floatValue]  ];        
    }else{     
        
        _labelAvailableExternalLoad.text = [ [NSString alloc] initWithFormat:@"%@: %.0fkg", maxExternalLoadString, MTOWfromEnvelope - weightTOW  ];        
    }
     
    
    //_labelAvailableExternalLoad.text = [ [NSString alloc] initWithFormat:@"%@: %.0fkg!", maxExternalLoadString, MTOWfromEnvelope - weightTOW  ];   
    
    if (currentExternalLoadWeight > availableExternalLoad ) {        
        _labelAvailableExternalLoad.backgroundColor = [UIColor redColor];
        _labelAvailableExternalLoad.textColor = [UIColor whiteColor];
    }else{       
        _labelAvailableExternalLoad.backgroundColor = [UIColor greenColor];
        _labelAvailableExternalLoad.textColor = [UIColor blackColor];
    }
  
    
    
}


- (void) calcSecondMaxExternalLoad {
    
    //NSLog(@"calcSecondMaxExternalLoad *********");
    _label2AvailableExternalLoad.hidden = NO;
 
    // get current externalLoad
    float currentExternalLoadWeight = [[_arrayName2 objectAtIndex:lineRelevantForExternalLoad] floatValue]; // weight   
    
    // limiting chart:
    UILabel *dL = [[UILabel alloc] init];  dL = (UILabel *)[_viewUniversalButtons viewWithTag:   [[_arrayName25 objectAtIndex:27]intValue] + 200  ];      
    availableExternalLoad = [dL.text floatValue] - (weightTOW - currentExternalLoadWeight);
    
    //NSLog(@"[dL.text floatValue] %.0f ", [dL.text floatValue] );
    //NSLog(@"weightTOW %.0f ", weightTOW );
    //NSLog(@"availableExternalLoad %.0f ", availableExternalLoad );
    
    
    if ([dL.text floatValue] - weightTOW > [[_arrayName9 objectAtIndex:lineRelevantForExternalLoad]floatValue]) {
        //NSLog(@"1");
        availableExternalLoad = [[_arrayName9 objectAtIndex:lineRelevantForExternalLoad]floatValue];        
        _label2AvailableExternalLoad.text = [ [NSString alloc] initWithFormat:@"%@:> %.0fkg", [_arrayName25 objectAtIndex:25], [dL.text floatValue] - weightTOW ];        
    }else{
          //NSLog(@"2");
        _label2AvailableExternalLoad.text = [ [NSString alloc] initWithFormat:@"%@: %.0fkg", [_arrayName25 objectAtIndex:25], [dL.text floatValue] - weightTOW ];        
    }
    
    if (currentExternalLoadWeight > availableExternalLoad ) {
        _label2AvailableExternalLoad.backgroundColor = [UIColor redColor];
        _label2AvailableExternalLoad.textColor = [UIColor whiteColor];
    }else{
        _label2AvailableExternalLoad.backgroundColor = [UIColor greenColor];
        _label2AvailableExternalLoad.textColor = [UIColor blackColor];
    }
    
    //[self checkCGwarningLongitudinal: CGLongTOW transferWeightTOW:weightTOW ];
    
    
}





- (void) checkCGwarningLongitudinal: (float)receivedCGlong  transferWeightTOW:(float)receivedWeightTOW  {
    
    
    // check CG
    flagWarningWeight = 0; flagWarningCG = 0;
    _labelCGinExtendedEnvelope.hidden = YES;
    _labelCGoutsideSafetyMargin.hidden = YES;
    CGwithinEnvelope1 = 0;
    CGwithinEnvelope2 = 0;
    CGwithinMargin = 0;
    
    CGPoint pointCG = {receivedCGlong, receivedWeightTOW};
    //NSLog(@"checking receivedCGlong %f", receivedCGlong);
    
    // check margin takeoff weight
    if ([[_arrayName23 objectAtIndex:21] isEqualToString:@"yes"]) {
        if (CGPathContainsPoint(shapeLayerFreakViewCG1Margin.path, NULL, pointCG, FALSE)) {
            CGwithinMargin = 1;
        }
    }
    
    if (CGPathContainsPoint(shapeLayerFreakViewCG1.path, NULL, pointCG, FALSE)) {
        CGwithinEnvelope1 = 1;
    }else{
        
    }
    
    //second cg envelope
    if ( [[_arrayName23 objectAtIndex:25] isEqualToString:@"yes"]) {
        if (CGPathContainsPoint(shapeLayerFreakViewCG2.path, NULL, pointCG, FALSE)) {
            CGwithinEnvelope2 = 1;
        }
    }
    /*
    if ([AC_Type isEqualToString:@"H175"] || [AC_Type isEqualToString:@"H145"]) {
        if (CGPathContainsPoint(shapeLayerFreakViewCG2.path, NULL, pointCG, FALSE)) {
            CGwithinEnvelope2 = 1;
        }
    }
     */
    
    return;
   
}


- (void) checkCGwarningLongitudinalForHOIST: (float)receivedCGlong  transferWeightTOW:(float)receivedWeightTOW  {
        
    //NSLog(@"receivedCGlong %.0f", receivedCGlong);
    //NSLog(@"receivedWeightTOW %.0f", receivedWeightTOW);
    
      
   //Depends on Display Butt
    
   if ( [AC_Type isEqualToString:@"H145"]) {
       
       // special H145 density Hoist rule
       
       if (densityalt < 12000 || Hp < 12000) {
           //NSLog(@"2");
           CGPoint pointCG = {receivedCGlong, receivedWeightTOW};
           if (CGPathContainsPoint(shapeLayerFreakViewCG1Margin.path, NULL, pointCG, FALSE)) {  
               //NSLog(@"3");
           }else{
               //NSLog(@"4");
               flagReportEnvelopeExceeded = 1;
           }        
       }else{ 
           //NSLog(@"5");
           
           CGPoint pointCG = {receivedCGlong, receivedWeightTOW};
           if (CGPathContainsPoint(shapeLayerFreakViewCG1.path, NULL, pointCG, FALSE)) {     
               //NSLog(@"6");
           }else{
               //NSLog(@"7");
               flagReportEnvelopeExceeded = 1;
           }       
           
       } 
       
   }else{
       CGPoint pointCG = {receivedCGlong, receivedWeightTOW};
       if (CGPathContainsPoint(shapeLayerFreakViewCG1.path, NULL, pointCG, FALSE)) {    
           
       }else{
           
           flagReportEnvelopeExceeded = 1;
       }    
       
       
   }
    
    
    
    
    
    
    return;
    
}








- (void) makeFreakViewLateral {
    
    //make cg envelope just for checking
    
    
    float numberOfPoints = 0;
    
    pathCGenvelope = [UIBezierPath bezierPath];
    for (int i = 7; i < _arrayCG1_LAT.count ; i++) { /// make path
        
        // get point coordinates
        NSString *Xstring     = [_arrayCG1_LAT objectAtIndex: i ];
        NSString *searchKeyword = @"/";
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        
        float xCGpos = 0;
        float yCGpos = 0;
        
        if(rangeOfYourString.location == NSNotFound){
            // error condition — the text searchKeyword wasn't in 'string'
        }else{
            if (numberOfPoints == 0) { // first point only
                xCGpos = [ [Xstring substringToIndex:rangeOfYourString.location] floatValue];
                yCGpos = [ [Xstring substringFromIndex:rangeOfYourString.location+1] floatValue];
                [pathCGenvelope moveToPoint:CGPointMake( xCGpos, yCGpos )];
            }else{
                xCGpos = [ [Xstring substringToIndex:rangeOfYourString.location] floatValue];
                yCGpos = [ [Xstring substringFromIndex:rangeOfYourString.location+1] floatValue];
                [pathCGenvelope addLineToPoint:CGPointMake( xCGpos, yCGpos )];
            }
            numberOfPoints = numberOfPoints + 1;
            
        }// end add to path
        
    }// end for next make path
    
    shapeLayerFreakViewCG1Lat = [CAShapeLayer layer];
    shapeLayerFreakViewCG1Lat.path = [pathCGenvelope CGPath];
    shapeLayerFreakViewCG1Lat.strokeColor = [[UIColor colorWithRed:255.0/255.0f green:218.0/255.0f blue:0.0/255.0f alpha:1.0f] CGColor];
    if (colorModeForCGenvelope == 0) {  shapeLayerFreakViewCG1Lat.strokeColor =[[UIColor colorWithRed:255.0/255.0f green:218.0/255.0f blue:0.0/255.0f alpha:1.0f] CGColor];  }else{ shapeLayerFreakViewCG1Lat.strokeColor = [[UIColor redColor] CGColor];    }
    shapeLayerFreakViewCG1Lat.lineWidth = 3.5;
    shapeLayerFreakViewCG1Lat.fillColor = [[UIColor clearColor] CGColor];
    //[self.cgFreakView.layer addSublayer:shapeLayerFreakViewCG1Lat];
    
    return;
    
    
}



- (void) checkButtonTimer {
    
    if (displayWindow == 15  ) {
        
        [_displayButtonTimers setImage:buttonBlue forState:UIControlStateNormal];
        
        return;
        
    } else {
        
        [_displayButtonTimers setImage:buttonGrey forState:UIControlStateNormal];
        
        return;
        
    }
    
    
    
    return;
    
    
}


- (void) checkButtonFlight {   
    if (displayWindow == 12  ) {        
        [buttonDisplayFlight setImage:buttonBlue forState:UIControlStateNormal];        
        return;        
    } else {        
        [buttonDisplayFlight setImage:buttonGrey forState:UIControlStateNormal];        
        return;        
    }    
    return;
}


- (void) checkButtonMainPage {
    
    if (displayWindow == 0  ) {
        [_buttonDisplayMainPage setImage:buttonBlue forState:UIControlStateNormal];
        return;
    } else {
        [_buttonDisplayMainPage setImage:buttonGrey forState:UIControlStateNormal];
        return;
    }
    
}




- (void) checkButtonSetup {
    
    if (displayWindow == 10  ) {
        [buttonSetup setImage:buttonBlue forState:UIControlStateNormal];
        return;
    } else {
        [buttonSetup setImage:buttonGrey forState:UIControlStateNormal];
        return;
    }
    
}

- (void) checkButtonManifeest {    
    
    if (displayWindow == 11  ) {
        
        [buttonLoadManifest setImage:buttonBlue forState:UIControlStateNormal];
        
        return;
        
    } else {
        
        [buttonLoadManifest setImage:buttonGrey forState:UIControlStateNormal];
        
        return;
        
    }   
    
    
    return;
    
    
}

- (void) checkButtonSummaryManifest {
    
    
    if (displayWindow == 14  ) {
        
        [_buttonSummaryManifest setImage:buttonBlue forState:UIControlStateNormal];
        
        return;
        
    } else {
        
        [_buttonSummaryManifest setImage:buttonGrey forState:UIControlStateNormal];
        
        return;
        
    }
    
    
    return;
    
    
}






// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------









// calc all performance values check button warnings

- (IBAction)sliderActionHp:(id)sender {    
    int dummy = sliderHp.value/100;
    sliderHp.value = dummy * 100;    
    [self MainRoutine];
    
    
}




- (IBAction)sliderActionMSL:(id)sender {    
    int dummy = _sliderMSL.value/100;
    _sliderMSL.value = dummy * 100;
    [self MainRoutine];
}


- (IBAction)sliderActionHeadwind2:(id)sender {
    
    int dummy = _sliderHeadwind2.value/incrementVariSlider1;
    _sliderHeadwind2.value = dummy * incrementVariSlider1;
    
    flagClimbEndMustBeHigherThanElevation = 1;
            
    [self MainRoutine];
    
}


- (IBAction)sliderActionIAS:(id)sender {
    
    int dummy = _sliderIAS.value/incrementVariSlider2;
    _sliderIAS.value = dummy * incrementVariSlider2;
    
    [self MainRoutine];
    
    
}
- (IBAction)sliderActionRatingIndex:(id)sender {
    
    int dummy = _sliderRatingIndex.value/incrementVariSlider3;
    _sliderRatingIndex.value = dummy * incrementVariSlider3;
    
    [self MainRoutine];
}

- (IBAction)sliderActionPROPRPM:(id)sender {
    
    int dummy = _sliderPROPRPM.value/incrementVariSlider4;
    _sliderPROPRPM.value = dummy * incrementVariSlider4;
    
    [self MainRoutine];
}







- (void) iEnviCalcALL {
    
    calcisa = 15 - (1.98 * (sliderHp.value/1000));
    float actualOAT = sliderOATforOGE.value;    
    ISAdif = actualOAT - calcisa;    
    if (ISAdif > 0.5) {        
        labelISAAnsage.textColor =  [UIColor orangeColor];        
        labelISAAnsage.text = [ [NSString alloc] initWithFormat:@"%.0fºC warmer than ISA", ISAdif];        
    }
    
    if (ISAdif < -0.5) {        
        labelISAAnsage.textColor = [UIColor colorWithRed:196.0f/255.0f green:221.0f/255.0f blue:250.0f/255.0f alpha:1.0f];
        labelISAAnsage.text = [ [NSString alloc] initWithFormat:@"%.0fºC cooler than ISA", ISAdif];
    }    
    if (ISAdif >= -0.5 & ISAdif <= 0.5) {
        labelISAAnsage.textColor = [UIColor whiteColor];
        labelISAAnsage.text = [ [NSString alloc] initWithFormat:@"ISA temperature"];
    }   
    OATinISA = calcisa + sliderISADiff.value;
    float fahrenheit = (OAT * 1.8) + 32;    
    labelActualOAT.text = [ [NSString alloc] initWithFormat:@"%.0fºC / %.0fºF", OATinISA, fahrenheit];
    labelISAdiff.text = [ [NSString alloc] initWithFormat:@"%.0f", sliderISADiff.value];
    
    
    if (OATinput == 0) {        
        OAT = sliderOATforOGE.value;        
        sliderISADiff.value = ISAdif;
        
    } else {        
        OAT = OATinISA;        
        sliderOATforOGE.value = OATinISA;
    }
    
    // density alt    
    int   PressAltforDensity = sliderHp.value;    
    float TKelvin = 273.15 + OAT;    
    float TSuper = 273.15 + ( 15 - ( 0.0019812 * PressAltforDensity) );    
    densityalt = PressAltforDensity + (TSuper / 0.0019812) * ( 1- ( powf (TSuper / TKelvin, .2349690) ) ) ;
     
    labelDisplayOAT.text = [ [NSString alloc] initWithFormat:@"%.0fºC", OAT];
    
    Hp = sliderHp.value;    
    inputPressureAlt = [ [NSString alloc] initWithFormat:@"%.0f", sliderHp.value];    
    labelOATforOGE.text = [ [NSString alloc] initWithFormat:@"%.0f", sliderOATforOGE.value];    
        
    
    _labelMainPressureAlt.text = [ [NSString alloc] initWithFormat:@"%.0f ft", sliderHp.value]; 
    labelDensityAlt.text = [ [NSString alloc] initWithFormat:@"%.0f ft", densityalt];
    labelDisplayPA.text = [ [NSString alloc] initWithFormat:@"%.0f'", sliderHp.value];
    
   /* 
   if ( [unitsElevation isEqualToString:@"ft"]) {
       _labelMainPressureAlt.text = [ [NSString alloc] initWithFormat:@"%.0f ft", sliderHp.value]; 
       labelDensityAlt.text = [ [NSString alloc] initWithFormat:@"%.0f ft", densityalt];
       labelDisplayPA.text = [ [NSString alloc] initWithFormat:@"%.0f'", sliderHp.value];
   }else{
       _labelMainPressureAlt.text = [ [NSString alloc] initWithFormat:@"%.0f m", sliderHp.value * 0.3048]; 
       labelDensityAlt.text = [ [NSString alloc] initWithFormat:@"%.0f m", densityalt * 0.3048];
       labelDisplayPA.text = [ [NSString alloc] initWithFormat:@"%.0fm", sliderHp.value * 0.3048];       
   } 
    */
    return;    
    
} // calc Environment








// /*/*//*/*/*/*/*/*/*/*/*/*/*//*/*/*/*/*/*/*/*/*/*/*//*/*/*/*/*/*/*/*/*/*/*//*/*/*/*/*/*/*/*/*/*/*//*/*/*/*/*/*/*/*/*/*/*//*/*/*/*/*/*/*/*/*/*/*//*/*/*/*/*/*/*/*/*
//                                                                                      LOAD SAVE
// /*/*//*/*/*/*/*/*/*/*/*/*/*//*/*/*/*/*/*/*/*/*/*/*//*/*/*/*/*/*/*/*/*/*/*//*/*/*/*/*/*/*/*/*/*/*//*/*/*/*/*/*/*/*/*/*/*//*/*/*/*/*/*/*/*/*/*/*//*/*/*/*/*/*/*/*/*





- (void) LoadValues {
    
    //NSLog (@"LoadValues");
    
    [tempArraySeatWgt removeAllObjects];
    [tempArraySeatName removeAllObjects];


    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    vFlightID   = [defaults  stringForKey:@"vFlightID"];
    
    
    
    callsignArray = [[NSMutableArray alloc] init];
    callsignArray = [[NSMutableArray alloc] initWithArray:[[[NSUserDefaults standardUserDefaults] objectForKey:@"callsignArray"] mutableCopy]];
    
    //NSLog(@"callsignArray %@", callsignArray);
    
    _dropDownAvailablePHIEquipLists.items  = callsignArray;
    _dropDownAvailablePHIEquipListsOverride.items  = callsignArray;
 
    //************************************************************************************************************************
    //************************************************************************************************************************
    
    
   //NSLog(@"loading flight %@, leg %@ ", vFlightID, vLegID );
    
    arrayDictAllAircraft = [[NSMutableArray alloc] init];
    arrayDictAllAircraft = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"] mutableCopy];

    
    
    allFlightsMasterArray = [[NSMutableArray alloc] init];
    allFlightsMasterArray = [[[NSUserDefaults standardUserDefaults] objectForKey:@"allFlightsMasterArray"] mutableCopy];
 

    
    //NSLog(@"allFlightsMasterArray.count %d", allFlightsMasterArray.count);
    
    allLegsPerFlightArray = [[NSMutableArray alloc] init];
    
    //NSLog (@"vFlightID %@", vFlightID);
    //NSLog (@"allFlightsMasterArray.count %lu", allFlightsMasterArray.count);
  
    if ([vFlightID integerValue] >= allFlightsMasterArray.count  || allFlightsMasterArray.count < 2 ) {
        //NSLog (@"error in previous flight!");
        float newFlightID = allFlightsMasterArray.count - 1 ;
        if (newFlightID < 1 & MBpagevisit < 100) {
            //NSLog (@"--- trying new load");
            [[NSUserDefaults standardUserDefaults]  setFloat:  0   forKey:@"MBpagevisit"];
            [self arrangeWindows];
            [self didLoadInitialStartUp];
            return;
        }
        //NSLog (@"newFlightID %.0f", newFlightID);
        allLegsPerFlightArray = [[allFlightsMasterArray objectAtIndex: newFlightID] mutableCopy];
        vFlightID =  [ [NSString alloc] initWithFormat:@"%f", newFlightID -1];
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        [defaults  setObject: vFlightID  forKey:@"vFlightID"];
    }else{
        allLegsPerFlightArray = [[allFlightsMasterArray objectAtIndex: [vFlightID integerValue] ] mutableCopy];
    }
    
    legSettingsDictionary = [[NSMutableDictionary alloc] init];
    
    if ([allLegsPerFlightArray count] > [vLegID integerValue]) {
        legSettingsDictionary = [allLegsPerFlightArray objectAtIndex: [vLegID integerValue] ];
    }
   
    
    //************************************************************************************************************************
    //************************************************************************************************************************
    
    

    
    //************************************************************************************************************************
    // flight settings
    
    flightSettingsDictionary = [[NSMutableDictionary alloc] init];
    flightSettingsDictionary = [[allLegsPerFlightArray objectAtIndex: 0 ] mutableCopy];
    flagLoadManifestSentForThisFlight = [[flightSettingsDictionary objectForKey: @"flagLoadManifestSentForThisFlight"] intValue];
    //NSLog(@"loading flagLoadManifestSentForThisFlight %d", flagLoadManifestSentForThisFlight); 
    
    //NSLog(@"loading flightSettingsDictionary %@", flightSettingsDictionary);
    
    
    
    //************************************************************************************************************************
    // basics
    
    _inputSliderIncrement.text                      = [defaults  stringForKey:@"_inputSliderIncrement"];
    _inputQuickLoadPreset.text                      = [defaults  stringForKey:@"_inputQuickLoadPreset"];
    _defaultEmailAddress.text                       = [defaults  stringForKey:@"_defaultEmailAddress"];
    _defaultEmailAddressCC.text                     = [defaults  stringForKey:@"_defaultEmailAddressCC"];
    _inputSpecificFuelMassPerVolume.text            = [defaults  stringForKey:@"_inputSpecificFuelMassPerVolume"];
    connectedToFleetControl                         = [defaults  floatForKey:@"connectedToFleetControl"];
    warningPercentMargin                            = [defaults  floatForKey:@"warningPercentMargin"];
    warningsOnOff                                   = [defaults  floatForKey:@"warningsOnOff"];
    nvgMode                                         = [defaults  floatForKey:@"nvgMode"];
    _sliderNVG.value                                = [defaults  floatForKey:@"_sliderNVG"];
    datepickInterval                                = [defaults  floatForKey:@"datepickInterval"];
    _segmentCGAutoCheck.selectedSegmentIndex        = [defaults  integerForKey:@"_segmentCGAutoCheck"];
    _segmentFlightLegMode.selectedSegmentIndex      = [defaults  integerForKey:@"_segmentFlightLegMode"];
    _segmentPlanMode.selectedSegmentIndex           = [defaults  integerForKey:@"_segmentPlanMode"];
    _segmentSeatLoadOptions.selectedSegmentIndex    = [defaults  integerForKey:@"_segmentSeatLoadOptions"];
    _segmentNamesOnSeats.selectedSegmentIndex       = [defaults  integerForKey:@"_segmentNamesOnSeats"];
    _segmentSwapMode.selectedSegmentIndex           = [defaults  integerForKey:@"_segmentSwapMode"];
    _inputSafetyMargin.text                         = [defaults  stringForKey:@"_inputSafetyMargin"];
    
    

    _mani_IntegrityCariedOutOn.text                 = [defaults  stringForKey:@"_mani_IntegrityCariedOutOn"];
    _mani_IntegrityCarriedOutBy.text                = [defaults  stringForKey:@"_mani_IntegrityCarriedOutBy"]; 
    
    previousOriginalFuelUnits                       = [defaults  stringForKey:@"previousOriginalFuelUnits"];
    previousOriginalWeightUnits                     = [defaults  stringForKey:@"previousOriginalWeightUnits"];
    
     //NSLog (@"L3");
    
    arrayAvailableListIDs = [[NSMutableArray alloc] initWithArray:[[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayAvailableListIDs"] mutableCopy]];
    
    _switchGuidance.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"_switchGuidance"];

    
   
    // enter Arrays  ************************************************************************************************************************
    
    
    NSMutableArray *LOADtableViewDataName = [[[NSUserDefaults standardUserDefaults] objectForKey:@"tableViewDataName"] mutableCopy];
    
    [self.tableViewDataName setArray:LOADtableViewDataName];
    
    NSMutableArray *LOADtableViewDataWeight = [[[NSUserDefaults standardUserDefaults] objectForKey:@"tableViewDataWeight"] mutableCopy];
    
    [self.tableViewDataWeight setArray:LOADtableViewDataWeight];
     //NSLog (@"L4");
    //LOAD helicopter objects into array    
    arrayDictAllAircraft = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"] mutableCopy];

    //NSLog(@"load helis %@", helicopters);    
    [self addHelicopterButtons];    
    lastupdate_helicopters = [defaults objectForKey:@"lastupdate_helicopters"];
    lastupdate_crew = [defaults objectForKey:@"lastupdate_crew"];
    crew_lastLocation = [defaults objectForKey:@"crew_lastLocation"];
    
    
    //LOAD crew objects into array
    
    NSData *dataRepresentingSavedArray = [defaults objectForKey:@"crew_sectioned"];
    if (dataRepresentingSavedArray != nil)
    {
        NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
        if (oldSavedArray != nil)
            crew_sectioned = [[NSMutableArray alloc] initWithArray:oldSavedArray];
        else
            crew_sectioned = [[NSMutableArray alloc] init];
    }
    
    //LOAD crew types into array
    
    crew_types = [[NSMutableArray alloc] initWithArray:[[[NSUserDefaults standardUserDefaults] objectForKey:@"crew_types"] mutableCopy]];

    CrewDataLoaded = [defaults  floatForKey:@"CrewDataLoaded"];
    
    
    //NSLog (@"load values");
    [calculatePerformanceClass_ triggerLoadSliderData];
    
    
    
    // load legSettingsDictionary   *****************************************************************       
     //NSLog (@"L5");
    
    internalFlightID = [legSettingsDictionary objectForKey: @"internalFlightRandomNumber"];
    [defaults  setObject: internalFlightID   forKey:@"InternalFlightID"];
    //NSLog(@"loading internalFlightRandomNumber = %@ for flightID %@", internalFlightID , vFlightID );
        
    specialdata1 = [legSettingsDictionary objectForKey: @"specialdata1"];
    specialdata2 = [legSettingsDictionary objectForKey: @"specialdata2"];
    dateOfWeighing = [legSettingsDictionary objectForKey: @"dateOfWeighing"];
    weighingRemarks = [legSettingsDictionary objectForKey: @"weighingRemarks"];
    ACCategory = [legSettingsDictionary objectForKey: @"_legACCategory"];
    ACmanufacturer = [legSettingsDictionary objectForKey: @"_legACmanufacturer"];
    AC_Type = [legSettingsDictionary objectForKey: @"_legAC_Type"];
    ACVariant = [legSettingsDictionary objectForKey: @"_legACVariant"];
    
    _dropDownAvailableACTypes.text = [legSettingsDictionary objectForKey: @"_dropDownAvailableACTypes"];
    _dropDownAvailableCallsigns.text = [legSettingsDictionary objectForKey: @"_dropDownAvailableCallsigns"];
    flagUsingAlternateEquipment = [[legSettingsDictionary objectForKey: @"flagUsingAlternateEquipment"] intValue];
    
    // change global setting
    [[NSUserDefaults standardUserDefaults]  setObject:ACCategory                    forKey:@"ACCategory"];
    [[NSUserDefaults standardUserDefaults]  setObject:ACmanufacturer                forKey:@"ACmanufacturer"];
    [[NSUserDefaults standardUserDefaults]  setObject:AC_Type                       forKey:@"AC_Type"];
    [[NSUserDefaults standardUserDefaults]  setObject:ACVariant                     forKey:@"ACVariant"];    

    _dropDownAvailablePHIEquipLists.text = [legSettingsDictionary objectForKey: @"_dropDownAvailablePHIEquipLists"];  
    _dropDownAvailablePHIEquipListsOverride.text = [legSettingsDictionary objectForKey: @"_dropDownAvailablePHIEquipLists"]; 
    _inputOverrideBEW.text = [legSettingsDictionary objectForKey: @"_inputOverrideBEW"];                     
    _inputOverrideMoment.text = [legSettingsDictionary objectForKey: @"_inputOverrideMoment"];                       
    _inputOverrideMomentLat.text = [legSettingsDictionary objectForKey: @"_inputOverrideMomentLat"];                   
    _inputOverrideRegistration.text = [legSettingsDictionary objectForKey: @"_inputOverrideRegistration"];  
    
    _inputPHIOverrideBEW.text = [legSettingsDictionary objectForKey: @"_inputPHIOverrideBEW"];                     
    _inputPHIOverrideMoment.text = [legSettingsDictionary objectForKey: @"_inputPHIOverrideMoment"];                       
    _inputPHIOverrideMomentLat.text = [legSettingsDictionary objectForKey: @"_inputPHIOverrideMomentLat"];                   
    _inputPHIOverrideRegistration.text = [legSettingsDictionary objectForKey: @"_inputPHIOverrideRegistration"];  
    _inputPHIOverrideBase.text = [legSettingsDictionary objectForKey: @"_inputPHIOverrideBase"];  
    _inputPHIOverrideFuelFlow.text = [legSettingsDictionary objectForKey: @"_inputPHIOverrideFuelFlow"];  
    _phiFuelFlowUnit.text = [legSettingsDictionary objectForKey: @"_phiFuelFlowUnit"]; 
    _inputPHIOverrideACtype.text = [legSettingsDictionary objectForKey: @"_inputPHIOverrideACtype"]; 
    _inputPHIOverrideSledWeight.text = [legSettingsDictionary objectForKey: @"_inputPHIOverrideSledWeight"]; 
    
    _vFlightIDName.text = [legSettingsDictionary objectForKey: @"_vFlightIDName"];
    _vFlightRemarks.text = [legSettingsDictionary objectForKey: @"_vFlightRemarks"];
    [ arrayACType setArray: [[legSettingsDictionary objectForKey: @"arrayACType"]  mutableCopy]];
    [ arrayACRegistration setArray: [[legSettingsDictionary objectForKey: @"arrayACRegistration"]  mutableCopy]];
    [ arrayBaseName setArray: [[legSettingsDictionary objectForKey: @"arrayBaseName"]  mutableCopy]];
    [ arrayConfigurationName setArray: [[legSettingsDictionary objectForKey: @"arrayConfigurationName"]  mutableCopy]];
    [ arrayPackageName setArray: [[legSettingsDictionary objectForKey: @"arrayPackageName"]  mutableCopy]];
    [ arrayUnitseName setArray: [[legSettingsDictionary objectForKey: @"arrayUnitseName"]  mutableCopy]];
    [ arrayConfigItemName setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemName"]  mutableCopy]];
    [ arrayConfigItemWeight setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemWeight"]  mutableCopy]];
    [ arrayConfigItemArmLong setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemArmLong"]  mutableCopy]];
    [ arrayConfigItemMomLong setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemMomLong"]  mutableCopy]];
    [ arrayConfigItemArmLat setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemArmLat"]  mutableCopy]];
    [ arrayConfigItemMomLat setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemMomLat"]  mutableCopy]];
    [ arrayConfigIteminOut setArray: [[legSettingsDictionary objectForKey: @"arrayConfigIteminOut"]  mutableCopy]];
    [ arrayConfigItemLocked setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemLocked"]  mutableCopy]];
    [ arrayConfigItemData setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemData"]  mutableCopy]];
    [ arrayConfigItemMoved setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemMoved"]  mutableCopy]];
    [ arrayConfigItemAltLong setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemAltLong"]  mutableCopy]];
    [ arrayConfigItemAltLat setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemAltLat"]  mutableCopy]];
    [ arrayConfigItemMovable setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemMovable"]  mutableCopy]];
    [ arrayConfigItemTrigger setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemTrigger"]  mutableCopy]];
    [ arrayConfigItemItemR1 setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemItemR1"]  mutableCopy]];
    [ arrayConfigItemItemR2 setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemItemR2"]  mutableCopy]];
    [ arrayConfigItemItemR3 setArray: [[legSettingsDictionary objectForKey: @"arrayConfigItemItemR3"]  mutableCopy]]; 
    [ arrayCustomFlightDataElements setArray: [[legSettingsDictionary objectForKey: @"arrayCustomFlightDataElements"]  mutableCopy]]; 
    //NSLog(@"loading arrayCustomFlightDataElements %@", arrayCustomFlightDataElements);    
   
    _inputDocumentPreparedTime.text = [legSettingsDictionary objectForKey: @"_inputDocumentPreparedTime"];
    _inputDocumentPreparedDate.text = [legSettingsDictionary objectForKey: @"_inputDocumentPreparedDate"];
    _input_documentPreparedBy.text = [legSettingsDictionary objectForKey: @"_input_documentPreparedBy"];
    inputFuelFlowOverride.text = [legSettingsDictionary objectForKey: @"inputFuelFlowOverride"];
    _vFlightTimeMinInput.text = [legSettingsDictionary objectForKey: @"_vFlightTimeMinInput"];
    vFlightRegistration.text = [legSettingsDictionary objectForKey: @"vFlightRegistration"];
    _manifestTimeStamp.text = [legSettingsDictionary objectForKey: @"_manifestTimeStamp"];
    timeStampForPDF = [legSettingsDictionary objectForKey: @"timeStampForPDF"];
    _labelDepartureTimeLocal.text = [legSettingsDictionary objectForKey: @"_labelDepartureTimeLocal"];
    _labellandingtimeLocal.text = [legSettingsDictionary objectForKey: @"_labellandingtimeLocal"];
    _labelDepartureTimeGMT.text = [legSettingsDictionary objectForKey: @"labelDepartureTimeGMT"];
    _inputPaxOnBoard.text = [legSettingsDictionary objectForKey: @"_inputPaxOnBoard"];
    vBEW.text = [legSettingsDictionary objectForKey: @"vBEW"];
    vBEWMom.text = [legSettingsDictionary objectForKey: @"vBEWMom"];
    vBEWMomLat.text = [legSettingsDictionary objectForKey: @"vBEWMomLat"];
    vFlightDeparture.text = [legSettingsDictionary objectForKey: @"vFlightDeparture"];
    vFlightDestination.text = [legSettingsDictionary objectForKey: @"vFlightDestination"];
    _labelFlightTimeMinutes.text = [legSettingsDictionary objectForKey: @"_labelFlightTimeMinutes"];
    sliderOATforOGE.value = [[legSettingsDictionary objectForKey: @"sliderOATforOGE"] floatValue];
    sliderHp.value = [[legSettingsDictionary objectForKey: @"sliderHp"] floatValue];
    sliderISADiff.value = [[legSettingsDictionary objectForKey: @"sliderISADiff"] floatValue];
    _sliderMSL.value = [[legSettingsDictionary objectForKey: @"_sliderMSL"] floatValue];
    sliderQNH.value = [[legSettingsDictionary objectForKey: @"sliderQNH"] floatValue];
     
    
    activeConfigButton = [[legSettingsDictionary objectForKey: @"activeConfigButton"] floatValue];
    listEnd = [[legSettingsDictionary objectForKey: @"listEnd"] floatValue];
    configuration = [[legSettingsDictionary objectForKey: @"configuration"] floatValue];
    guidanceLegCheckOK = [[legSettingsDictionary objectForKey: @"guidanceLegCheckOK"] intValue];
    guidanceDictionary = [[legSettingsDictionary objectForKey: @"guidanceDictionary"] mutableCopy];
    
    fuelEnterMode= [legSettingsDictionary objectForKey: @"fuelEnterMode"]; 
    //NSLog(@"loading fuelEnterMode %@", fuelEnterMode);
    
    
    
    _vFlightTimeMinutes.text = [legSettingsDictionary objectForKey: @"_vFlightTimeMinutes"];
    _vFlightTimeHours.text = [legSettingsDictionary objectForKey: @"_vFlightTimeHours"];
    selectedUnitForItems = [legSettingsDictionary objectForKey: @"selectedUnitForItems"];
    selectedUnitForFuel = [legSettingsDictionary objectForKey: @"selectedUnitForFuel"];
    
    _vEngineStarts1.text = [legSettingsDictionary objectForKey: @"_vEngineStarts1"];
    _vEngineStarts2.text = [legSettingsDictionary objectForKey: @"_vEngineStarts2"];
    _vRIN.text = [legSettingsDictionary objectForKey: @"_vRIN"];
    _vCockpitSeatLeft.text = [legSettingsDictionary objectForKey: @"_vCockpitSeatLeft"];
    _vCockpitSeatRight.text = [legSettingsDictionary objectForKey: @"_vCockpitSeatRight"];
    _vFlightTypeField.text = [legSettingsDictionary objectForKey: @"_vFlightTypeField"];
    _vFuelPresetField.text = [legSettingsDictionary objectForKey: @"_vFuelPresetField"];
    _vReserveTimeField.text = [legSettingsDictionary objectForKey: @"_vReserveTimeField"];    
    loadedSignatureImage = [UIImage imageWithData:[legSettingsDictionary objectForKey: @"signatureImage"] ];
    loadedSignature2Image = [UIImage imageWithData:[legSettingsDictionary objectForKey: @"signature2Image"] ];
    linePilot = [[legSettingsDictionary objectForKey: @"linePilot"] intValue];
    
    _sliderHeadwind2.value = [[legSettingsDictionary objectForKey: @"_sliderHeadwind2"] floatValue];
    _sliderIAS.value = [[legSettingsDictionary objectForKey: @"_sliderIAS"] floatValue];
    _sliderRatingIndex.value = [[legSettingsDictionary objectForKey: @"_sliderRatingIndex"] floatValue];
    _sliderPROPRPM.value = [[legSettingsDictionary objectForKey: @"_sliderPROPRPM"] floatValue];
     
    autoLandingFuelSetting = [legSettingsDictionary objectForKey: @"autoLandingFuelSetting"] ;
    if ([autoLandingFuelSetting isEqualToString:@"on"]) {
        _switchAutoLandingFuel.on = YES;
    }else{
        _switchAutoLandingFuel.on = NO;
    }
    
    
    [self mountSignatureImageToLoadManifest];
    [self mountSignatureImageToPowerCheck];
   
  
    [ _arrayName1 setArray: [[legSettingsDictionary objectForKey: @"_arrayName1"]  mutableCopy]];
    [ _arrayName2 setArray: [[legSettingsDictionary objectForKey: @"_arrayName2"]  mutableCopy]];
    [ _arrayName3 setArray: [[legSettingsDictionary objectForKey: @"_arrayName3"]  mutableCopy]];
    [ _arrayName4 setArray: [[legSettingsDictionary objectForKey: @"_arrayName4"]  mutableCopy]];
    [ _arrayName5 setArray: [[legSettingsDictionary objectForKey: @"_arrayName5"]  mutableCopy]];
    [ _arrayName6 setArray: [[legSettingsDictionary objectForKey: @"_arrayName6"]  mutableCopy]];
    [ _arrayName7 setArray: [[legSettingsDictionary objectForKey: @"_arrayName7"]  mutableCopy]];
    [ _arrayName8 setArray: [[legSettingsDictionary objectForKey: @"_arrayName8"]  mutableCopy]];
    [ _arrayName9 setArray: [[legSettingsDictionary objectForKey: @"_arrayName9"]  mutableCopy]];
    [ _arrayName10 setArray: [[legSettingsDictionary objectForKey: @"_arrayName10"]  mutableCopy]];
    [ _arrayName11 setArray: [[legSettingsDictionary objectForKey: @"_arrayName11"]  mutableCopy]];
    [ _arrayName12 setArray: [[legSettingsDictionary objectForKey: @"_arrayName12"]  mutableCopy]];
    [ _arrayName13 setArray: [[legSettingsDictionary objectForKey: @"_arrayName13"]  mutableCopy]];
    [ _arrayName14 setArray: [[legSettingsDictionary objectForKey: @"_arrayName14"]  mutableCopy]];
    [ _arrayName15 setArray: [[legSettingsDictionary objectForKey: @"_arrayName15"]  mutableCopy]];
    [ _arrayName16 setArray: [[legSettingsDictionary objectForKey: @"_arrayName16"]  mutableCopy]];
    [ _arrayName17 setArray: [[legSettingsDictionary objectForKey: @"_arrayName17"]  mutableCopy]];
    [ _arrayName18 setArray: [[legSettingsDictionary objectForKey: @"_arrayName18"]  mutableCopy]];
    [ _arrayName19 setArray: [[legSettingsDictionary objectForKey: @"_arrayName19"]  mutableCopy]];
    [ _arrayName20 setArray: [[legSettingsDictionary objectForKey: @"_arrayName20"]  mutableCopy]];
    [ _arrayName21 setArray: [[legSettingsDictionary objectForKey: @"_arrayName21"]  mutableCopy]];
    [ _arrayName22 setArray: [[legSettingsDictionary objectForKey: @"_arrayName22"]  mutableCopy]];
    [ _arrayName23 setArray: [[legSettingsDictionary objectForKey: @"_arrayName23"]  mutableCopy]];
    [ _arrayName24 setArray: [[legSettingsDictionary objectForKey: @"_arrayName24"]  mutableCopy]];
    [ _arrayName25 setArray: [[legSettingsDictionary objectForKey: @"_arrayName25"]  mutableCopy]];
    
    [self setBasicsForConfiguration];
   
    [self loadFuelTankSettings];
    
    [self addLegButtons];

    
    // *************************************************************************************************************************
    
    
     //NSLog (@"L6");
    
    [self makeConfigButtons];

    //NSLog (@"1 replacing");
    [_arrayName2 replaceObjectAtIndex:3 withObject: vBEW.text];
    [_arrayName4 replaceObjectAtIndex:3 withObject: vBEWMom.text];
    [_arrayName6 replaceObjectAtIndex:3 withObject: vBEWMomLat.text];

    
    
    armlong = [vBEWMom.text doubleValue] / [vBEW.text doubleValue];
    armlat  = [vBEWMomLat.text doubleValue]   / [vBEW.text doubleValue];
    lBEWArm.text = [NSString stringWithFormat:@"%.2f",armlong];
    lBEWArmLat.text = [NSString stringWithFormat:@"%.3f",armlat];
    [_arrayName3 replaceObjectAtIndex:3 withObject: lBEWArm.text];
    [_arrayName5 replaceObjectAtIndex:3 withObject: lBEWArmLat.text];
    
    
 
    
    inputPressureAlt = [ [NSString alloc] initWithFormat:@"%.0f", sliderHp.value];
    
    labelOATforOGE.text = [ [NSString alloc] initWithFormat:@"%.0f", sliderOATforOGE.value];
    
    labelISAdiff.text = [ [NSString alloc] initWithFormat:@"%.0f", sliderISADiff.value];
    
    
    if (warningsOnOff == 1) {
        switchWarnings.on = YES;
    } else {
        switchWarnings.on = NO;
    }
    

    // *************************************************************************************************************************

    
    
    if (flagMakeNewFlgtNow == 0) {
        [self createListoItemsSlidersAndInterior];
    }
        
   
    

    [self createSpecialEquipListItems];
    
    return;
    


    
    
    
    
    
}




- (void) SaveValues {
   
    //NSLog(@"SaveValues");
    
    
    
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    [defaults  setObject: [NSKeyedArchiver archivedDataWithRootObject:crew_sectioned] forKey:@"crew_sectioned"];
    
    
    NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"];
    if (dedicatedCustomerData.length < 2) {
        dedicatedCustomerData = @"";
    }   
    if ([dedicatedCustomerData rangeOfString:@"loadTOemail"].location != NSNotFound  ) {         
         _defaultEmailAddress.text                       = [defaults  stringForKey:@"_defaultEmailAddress"];        
    }
    if ([dedicatedCustomerData rangeOfString:@"loadCCemail"].location != NSNotFound  ) {         
        _defaultEmailAddressCC.text                       = [defaults  stringForKey:@"_defaultEmailAddressCC"];       
    }
    
    [defaults  setObject: _defaultEmailAddress.text                     forKey:@"_defaultEmailAddress"]; 
    [defaults  setObject: _defaultEmailAddressCC.text                   forKey:@"_defaultEmailAddressCC"]; 
    
    
   
    [defaults  setObject: vFlightID                                     forKey:@"vFlightID"];
    [defaults  setObject: _inputSliderIncrement.text                    forKey:@"_inputSliderIncrement"];
    [defaults  setObject: _inputQuickLoadPreset.text                    forKey:@"_inputQuickLoadPreset"];
    [defaults  setObject: self.tableViewDataName                        forKey:@"tableViewDataName"];
    [defaults  setObject: self.tableViewDataWeight                      forKey:@"tableViewDataWeight"];
    [defaults  setObject: _inputSpecificFuelMassPerVolume.text          forKey:@"_inputSpecificFuelMassPerVolume"];
    [defaults  setObject: lastupdate_helicopters                        forKey:@"lastupdate_helicopters"];
    [defaults  setObject: lastupdate_crew                               forKey:@"lastupdate_crew"];
    [defaults  setObject: crew_lastLocation                             forKey:@"crew_lastLocation"];
    [defaults  setObject: crew_types                                    forKey:@"crew_types"];
    [defaults  setObject: arrayAvailableListIDs                         forKey:@"arrayAvailableListIDs"];
    [defaults  setFloat:  connectedToFleetControl                       forKey:@"connectedToFleetControl"];
    [defaults  setFloat:  warningPercentMargin                          forKey:@"warningPercentMargin"];
    [defaults  setFloat:  warningsOnOff                                 forKey:@"warningsOnOff"];
    [defaults  setFloat:  nvgMode                                       forKey:@"nvgMode"];
    [defaults  setFloat:  _sliderNVG.value                              forKey:@"_sliderNVG"];
    [defaults  setFloat:  datepickInterval                              forKey:@"datepickInterval"];
    [defaults  setObject: _inputSafetyMargin.text                       forKey:@"_inputSafetyMargin"];
    [defaults  setObject: previousOriginalWeightUnits                   forKey:@"previousOriginalWeightUnits"];
    [defaults  setObject: previousOriginalFuelUnits                     forKey:@"previousOriginalFuelUnits"];    
       
    [defaults setBool:[_switchGuidance isOn] forKey:@"_switchGuidance"];    
    [defaults  setInteger: _segmentCGAutoCheck.selectedSegmentIndex             forKey:@"_segmentCGAutoCheck"];
    [defaults  setInteger: _segmentFlightLegMode.selectedSegmentIndex           forKey:@"_segmentFlightLegMode"];
    [defaults  setInteger: _segmentPlanMode.selectedSegmentIndex                forKey:@"_segmentPlanMode"];
    [defaults  setInteger: _segmentSeatLoadOptions.selectedSegmentIndex         forKey:@"_segmentSeatLoadOptions"];
    [defaults  setInteger: _segmentNamesOnSeats.selectedSegmentIndex            forKey:@"_segmentNamesOnSeats"];
    [defaults  setInteger: _segmentSwapMode.selectedSegmentIndex                forKey:@"_segmentSwapMode"];    
    [defaults  setObject: _mani_IntegrityCarriedOutBy.text                      forKey:@"_mani_IntegrityCarriedOutBy"];
    [defaults  setObject: _mani_IntegrityCariedOutOn.text                       forKey:@"_mani_IntegrityCariedOutOn"];
    legSettingsDictionary = [[NSMutableDictionary alloc] init];  
    //save custom flight data elements
    //NSLog(@"[[_viewCustomFlightDataElements subviews] count]  %lu " , [[_viewCustomFlightDataElements subviews] count] );
    NSMutableArray *tempArrayCustomFlightDataElements = [[NSMutableArray alloc] init];
    for (int i = 0; i < [[_viewCustomFlightDataElements subviews] count]/2; i++) {        
        UITextField *viewElement = (UITextField*)[_viewCustomFlightDataElements viewWithTag: 17 + i ];        
        //NSLog(@"viewElement %@", viewElement.text);
        [tempArrayCustomFlightDataElements addObject:viewElement.text];       
    }
    legSettingsDictionary[@"arrayCustomFlightDataElements"] = tempArrayCustomFlightDataElements;      
    //NSLog(@"saving tempArrayCustomFlightDataElements %@", tempArrayCustomFlightDataElements);    
    
    legSettingsDictionary[@"_dropDownAvailablePHIEquipLists"] = _dropDownAvailablePHIEquipLists.text;  
    
    
    legSettingsDictionary[@"internalFlightRandomNumber"] = internalFlightID;
    [defaults  setObject: internalFlightID   forKey:@"InternalFlightID"];    
    //NSLog(@"saving internalFlightRandomNumber  %@ for Flight ID %@" , internalFlightID, vFlightID );
    legSettingsDictionary[@"specialdata1"] = specialdata1;
    //NSLog(@"saving specialdata1  %@ " ,specialdata1);
    legSettingsDictionary[@"specialdata2"] = specialdata2;
    legSettingsDictionary[@"dateOfWeighing"] = dateOfWeighing;
    legSettingsDictionary[@"weighingRemarks"] = weighingRemarks;
    legSettingsDictionary[@"_legACCategory"] = ACCategory; // Heli
    legSettingsDictionary[@"_legACmanufacturer"] = ACmanufacturer; // Airbus
    legSettingsDictionary[@"_legAC_Type"] = AC_Type ; // H175
    legSettingsDictionary[@"_legACVariant"] = ACVariant; // NONE    
    legSettingsDictionary[@"_inputOverrideBEW"] = _inputOverrideBEW.text; 
    legSettingsDictionary[@"_inputOverrideMoment"] = _inputOverrideMoment.text; 
    legSettingsDictionary[@"_inputOverrideMomentLat"] = _inputOverrideMomentLat.text; 
    legSettingsDictionary[@"_inputOverrideRegistration"] = _inputOverrideRegistration.text;
    legSettingsDictionary[@"_inputPHIOverrideBEW"] = _inputPHIOverrideBEW.text; 
    legSettingsDictionary[@"_inputPHIOverrideMoment"] = _inputPHIOverrideMoment.text; 
    legSettingsDictionary[@"_inputPHIOverrideMomentLat"] = _inputPHIOverrideMomentLat.text; 
    legSettingsDictionary[@"_inputPHIOverrideSledWeight"] = _inputPHIOverrideSledWeight.text; 
    legSettingsDictionary[@"_inputPHIOverrideRegistration"] = _inputPHIOverrideRegistration.text; 
    legSettingsDictionary[@"_inputPHIOverrideBase"] = _inputPHIOverrideBase.text;
    legSettingsDictionary[@"_inputPHIOverrideFuelFlow"] = _inputPHIOverrideFuelFlow.text;
    legSettingsDictionary[@"_phiFuelFlowUnit"] = _phiFuelFlowUnit.text;
    legSettingsDictionary[@"_inputPHIOverrideACtype"] = _inputPHIOverrideACtype.text; 
    legSettingsDictionary[@"_dropDownAvailableACTypes"] = _dropDownAvailableACTypes.text;
    legSettingsDictionary[@"_dropDownAvailableCallsigns"] = _dropDownAvailableCallsigns.text;
    legSettingsDictionary[@"flagUsingAlternateEquipment"] = [NSString stringWithFormat:@"%d", flagUsingAlternateEquipment  ];
    legSettingsDictionary[@"trialCheck"] = trialCheck;
    legSettingsDictionary[@"_vFlightIDName"] = _vFlightIDName.text ;
    legSettingsDictionary[@"_vFlightRemarks"] = _vFlightRemarks.text ;
    legSettingsDictionary[@"arrayACType"] = arrayACType ;
    legSettingsDictionary[@"arrayACRegistration"] = arrayACRegistration ;
    legSettingsDictionary[@"arrayBaseName"] = arrayBaseName ;
    legSettingsDictionary[@"arrayConfigurationName"] = arrayConfigurationName ;
    legSettingsDictionary[@"arrayPackageName"] = arrayPackageName ;
    legSettingsDictionary[@"arrayUnitseName"] = arrayUnitseName ;
    legSettingsDictionary[@"arrayConfigItemName"] = arrayConfigItemName ;
    legSettingsDictionary[@"arrayConfigItemWeight"] = arrayConfigItemWeight ;
    legSettingsDictionary[@"arrayConfigItemArmLong"] = arrayConfigItemArmLong ;
    legSettingsDictionary[@"arrayConfigItemMomLong"] = arrayConfigItemMomLong ;
    legSettingsDictionary[@"arrayConfigItemArmLat"] = arrayConfigItemArmLat ;
    legSettingsDictionary[@"arrayConfigItemMomLat"] = arrayConfigItemMomLat ;
    legSettingsDictionary[@"arrayConfigIteminOut"] = arrayConfigIteminOut ;
    legSettingsDictionary[@"arrayConfigItemLocked"] = arrayConfigItemLocked ;
    legSettingsDictionary[@"arrayConfigItemData"] = arrayConfigItemData ;
    legSettingsDictionary[@"arrayConfigItemMoved"] = arrayConfigItemMoved ;
    legSettingsDictionary[@"arrayConfigItemAltLong"] = arrayConfigItemAltLong ;
    legSettingsDictionary[@"arrayConfigItemAltLat"] = arrayConfigItemAltLat ;
    legSettingsDictionary[@"arrayConfigItemMovable"] = arrayConfigItemMovable ;
    legSettingsDictionary[@"arrayConfigItemTrigger"] = arrayConfigItemTrigger ;
    legSettingsDictionary[@"arrayConfigItemItemR1"] = arrayConfigItemItemR1 ;
    legSettingsDictionary[@"arrayConfigItemItemR2"] = arrayConfigItemItemR2 ;
    legSettingsDictionary[@"arrayConfigItemItemR3"] = arrayConfigItemItemR3 ;   
    legSettingsDictionary[@"_inputDocumentPreparedTime"] = _inputDocumentPreparedTime.text ;
    legSettingsDictionary[@"_inputDocumentPreparedDate"] = _inputDocumentPreparedDate.text ;
    legSettingsDictionary[@"_input_documentPreparedBy"] = _input_documentPreparedBy.text ;
    legSettingsDictionary[@"inputFuelFlowOverride"] = inputFuelFlowOverride.text ;
    legSettingsDictionary[@"_vFlightTimeMinInput"] = _vFlightTimeMinInput.text ;
    legSettingsDictionary[@"vFlightRegistration"] = vFlightRegistration.text ;
    legSettingsDictionary[@"_manifestTimeStamp"] = _manifestTimeStamp.text ;
    legSettingsDictionary[@"timeStampForPDF"] = timeStampForPDF ;
    legSettingsDictionary[@"_labelDepartureTimeLocal"] = _labelDepartureTimeLocal.text ;
    legSettingsDictionary[@"_labellandingtimeLocal"] = _labellandingtimeLocal.text ;
    legSettingsDictionary[@"labelDepartureTimeGMT"] = _labelDepartureTimeGMT.text ;
    legSettingsDictionary[@"_inputPaxOnBoard"] = _inputPaxOnBoard.text ;
    legSettingsDictionary[@"vBEW"] = vBEW.text ;
    legSettingsDictionary[@"vBEWMom"] = vBEWMom.text ;
    legSettingsDictionary[@"vBEWMomLat"] = vBEWMomLat.text ;
    legSettingsDictionary[@"vFlightDeparture"] = vFlightDeparture.text ;
    legSettingsDictionary[@"vFlightDestination"] = vFlightDestination.text ;
    legSettingsDictionary[@"_labelFlightTimeMinutes"] = _labelFlightTimeMinutes.text ;
    legSettingsDictionary[@"sliderOATforOGE"] = [NSString stringWithFormat:@"%.4f", sliderOATforOGE.value  ];
    legSettingsDictionary[@"sliderHp"] = [NSString stringWithFormat:@"%.4f", sliderHp.value  ];
    legSettingsDictionary[@"sliderISADiff"] = [NSString stringWithFormat:@"%.4f", sliderISADiff.value  ]; 
    legSettingsDictionary[@"_sliderMSL"] = [NSString stringWithFormat:@"%.4f", _sliderMSL.value  ];
    legSettingsDictionary[@"sliderQNH"] = [NSString stringWithFormat:@"%.4f", sliderQNH.value  ];
    legSettingsDictionary[@"_sliderFuelMain1"] = [NSString stringWithFormat:@"%.4f", _sliderFuelMain1.value  ];
    legSettingsDictionary[@"_sliderFuelLanding"] = [NSString stringWithFormat:@"%.4f", _sliderFuelLanding.value  ];
    legSettingsDictionary[@"activeConfigButton"] = [NSString stringWithFormat:@"%.4f", activeConfigButton  ];
    legSettingsDictionary[@"listEnd"] = [NSString stringWithFormat:@"%.4f", listEnd  ];
    legSettingsDictionary[@"configuration"] = [NSString stringWithFormat:@"%d", configuration  ];
    legSettingsDictionary[@"guidanceLegCheckOK"] = [NSString stringWithFormat:@"%d", guidanceLegCheckOK  ]; 
    legSettingsDictionary[@"_vFlightTimeHours"] = _vFlightTimeHours.text ;
    legSettingsDictionary[@"_vFlightTimeMinutes"] = _vFlightTimeMinutes.text ;
    legSettingsDictionary[@"selectedUnitForItems"] = selectedUnitForItems ;
    legSettingsDictionary[@"selectedUnitForFuel"] = selectedUnitForFuel ;
    legSettingsDictionary[@"fuelEnterMode"] = fuelEnterMode ;
    legSettingsDictionary[@"labelCGTakeoff"] = labelCGTakeoff.text;   
    legSettingsDictionary[@"MTOW"] = [_arrayName21 objectAtIndex:9];
    legSettingsDictionary[@"legFlightTimeMinutes"] = [NSString stringWithFormat:@"%d", legFlightTimeMinutes  ];
    legSettingsDictionary[@"_labelGuidanceLegTime"] = _labelGuidanceLegTime.text;
    legSettingsDictionary[@"_vEngineStarts1"] = _vEngineStarts1.text ;
    legSettingsDictionary[@"_vEngineStarts2"] = _vEngineStarts2.text ;
    legSettingsDictionary[@"_vRIN"] = _vRIN.text ;
    legSettingsDictionary[@"_cgFWDlimit"] = _cgFWDlimit.text;
    legSettingsDictionary[@"_cgAFTlimit"] = _cgAFTlimit.text;
    legSettingsDictionary[@"_labelGuidanceFuel"] = _labelGuidanceFuel.text;
    legSettingsDictionary[@"_vCockpitSeatLeft"] = _vCockpitSeatLeft.text ;
    legSettingsDictionary[@"_vCockpitSeatRight"] = _vCockpitSeatRight.text; 
    legSettingsDictionary[@"_vFlightTypeField"] = _vFlightTypeField.text ;
    legSettingsDictionary[@"_vFuelPresetField"] = _vFuelPresetField.text ;
    legSettingsDictionary[@"_vReserveTimeField"] = _vReserveTimeField.text ;
    
    legSettingsDictionary[@"_labelConfigurationName2"] = _labelConfigurationName2.text ;    
    legSettingsDictionary[@"_labelSEtotalWeight2"] = _labelSEtotalWeight2.text ;
    
    if ([[_arrayName7 objectAtIndex:linePilot]length] > 3) {
        legSettingsDictionary[@"PICofLeg"] =  [NSString stringWithFormat:@"%@ %.0flbs", [_arrayName7 objectAtIndex:linePilot],  [[_arrayName2 objectAtIndex:linePilot]floatValue] ];
    }else{
         legSettingsDictionary[@"PICofLeg"] =  [NSString stringWithFormat:@"%.0flbs",   [[_arrayName2 objectAtIndex:linePilot]floatValue] ];        
    }
    NSString *SICname = @"";
    if ([[_arrayName1 objectAtIndex:linePilot+1] isEqualToString:@"SIC"] || [[_arrayName1 objectAtIndex:linePilot+1] isEqualToString:@"CoPilot"] || [[_arrayName1 objectAtIndex:linePilot+1] isEqualToString:@"SICofLeg"]) {
        SICname = [NSString stringWithFormat:@"%@ %.0flbs", [_arrayName7 objectAtIndex:linePilot+1],  [[_arrayName2 objectAtIndex:linePilot+1]floatValue] ];
    }
    legSettingsDictionary[@"vSICname"] =  SICname;     
    legSettingsDictionary[@"linePilot"] = [NSString stringWithFormat:@"%d", linePilot  ];    
    legSettingsDictionary[@"_sliderHeadwind2"] = [NSString stringWithFormat:@"%.1f", _sliderHeadwind2.value  ];
    legSettingsDictionary[@"_sliderIAS"] = [NSString stringWithFormat:@"%.1f", _sliderIAS.value  ];
    legSettingsDictionary[@"_sliderRatingIndex"] = [NSString stringWithFormat:@"%.1f", _sliderRatingIndex.value  ];
    legSettingsDictionary[@"_sliderPROPRPM"] = [NSString stringWithFormat:@"%.1f", _sliderPROPRPM.value  ];
    if (_switchAutoLandingFuel.on == YES) {
        legSettingsDictionary[@"autoLandingFuelSetting"] = @"on";
    }else{
         legSettingsDictionary[@"autoLandingFuelSetting"] = @"off";
    }
    
    // get PersonsOnBoard    
    arrayPersonsOnBoard = [[NSMutableArray alloc] init];    
    for (int i = 0; i < lineOptions ; i++) {
        
        if ([[_arrayName10 objectAtIndex: i  ] rangeOfString:@"seat"].location != NSNotFound ) {            
            
            if ( [[_arrayName7 objectAtIndex:i] isEqualToString:@"-"] || [[_arrayName7 objectAtIndex:i] isEqualToString:@""] ) {
                continue;
            }            
            if ( [[_arrayName1 objectAtIndex:i] isEqualToString:@"PIC"] || [[_arrayName1 objectAtIndex:i] isEqualToString:@"Pilot"] ) {
                continue;
            }            
            if ( [[_arrayName1 objectAtIndex:i] isEqualToString:@"SIC"] ||  [[_arrayName1 objectAtIndex:i] isEqualToString:@"Co-Pilot"]) {
                continue;
            }
            if (flagSpecialPHIFlightSettingPage == 1) {
                [arrayPersonsOnBoard addObject:[NSString stringWithFormat:@"%@ %.0flbs", [_arrayName7 objectAtIndex:i],  [[_arrayName2 objectAtIndex:i]floatValue] ]];                 
            }else{
                [arrayPersonsOnBoard addObject:[_arrayName7 objectAtIndex:i]];                
            }
        }        
    }
    
    //NSLog(@"arrayPersonsOnBoard %@", arrayPersonsOnBoard);    
    _labelPaxOnBoard.text = @"";    
    for(int i=0; i<arrayPersonsOnBoard.count; i++) {        
        _labelPaxOnBoard.text = [_labelPaxOnBoard.text stringByAppendingString:[arrayPersonsOnBoard objectAtIndex: i ]   ];
        _labelPaxOnBoard.text = [_labelPaxOnBoard.text stringByAppendingString:@" / "   ];
    }
    //NSLog(@"_labelPaxOnBoard.text %@", _labelPaxOnBoard.text  );
    legSettingsDictionary[@"arrayPersonsOnBoard"] = arrayPersonsOnBoard;
    legSettingsDictionary[@"_labelPaxOnBoard"] = _labelPaxOnBoard.text;
    legSettingsDictionary[@"vTOW"] = [NSString stringWithFormat:@"%.1f", vTOW  ];
    legSettingsDictionary[@"vLDW"] = [NSString stringWithFormat:@"%.1f", vLDW  ];
    legSettingsDictionary[@"legID"] = vLegID ;    
    legSettingsDictionary[@"signatureImage"] = signatureImageData ;
    legSettingsDictionary[@"signature2Image"] = signature2ImageData ;    
    legSettingsDictionary[@"guidanceDictionary"] = guidanceDictionary ;    
    legSettingsDictionary[@"_arrayName1"] = _arrayName1 ;
    legSettingsDictionary[@"_arrayName2"] = _arrayName2 ;
    legSettingsDictionary[@"_arrayName3"] = _arrayName3 ;
    legSettingsDictionary[@"_arrayName4"] = _arrayName4 ;
    legSettingsDictionary[@"_arrayName5"] = _arrayName5 ;
    legSettingsDictionary[@"_arrayName6"] = _arrayName6 ;
    legSettingsDictionary[@"_arrayName7"] = _arrayName7 ;
    legSettingsDictionary[@"_arrayName8"] = _arrayName8 ;
    legSettingsDictionary[@"_arrayName9"] = _arrayName9 ;
    legSettingsDictionary[@"_arrayName10"] = _arrayName10 ;
    legSettingsDictionary[@"_arrayName11"] = _arrayName11 ;
    legSettingsDictionary[@"_arrayName12"] = _arrayName12 ;
    legSettingsDictionary[@"_arrayName13"] = _arrayName13 ;
    legSettingsDictionary[@"_arrayName14"] = _arrayName14 ;
    legSettingsDictionary[@"_arrayName15"] = _arrayName15 ;
    legSettingsDictionary[@"_arrayName16"] = _arrayName16 ;
    legSettingsDictionary[@"_arrayName17"] = _arrayName17 ;
    legSettingsDictionary[@"_arrayName18"] = _arrayName18 ;
    legSettingsDictionary[@"_arrayName19"] = _arrayName19 ;
    legSettingsDictionary[@"_arrayName20"] = _arrayName20 ;
    legSettingsDictionary[@"_arrayName21"] = _arrayName21 ;
    legSettingsDictionary[@"_arrayName22"] = _arrayName22 ;
    legSettingsDictionary[@"_arrayName23"] = _arrayName23 ;
    legSettingsDictionary[@"_arrayName24"] = _arrayName24 ;
    legSettingsDictionary[@"_arrayName25"] = _arrayName25 ;
   
    
     
    
    
    if (flagResetAllLegs == 1) {
        allLegsPerFlightArray = [[NSMutableArray alloc] init];
         //NSLog(@"allLegsPerFlightArray vLegID %@", vLegID);
         [allLegsPerFlightArray addObject:@"-"];
         [allLegsPerFlightArray addObject:@"-"];
        flagResetAllLegs = 0;
    }
   
    
    //NSLog(@"saving guidanceDictionary  %@", guidanceDictionary);
    
    // save flight settings    
    flightSettingsDictionary = [[NSMutableDictionary alloc] init];    
    flightSettingsDictionary[@"keyFlightDate"] =  [_arrayName7 objectAtIndex:linePilot]; // pilot name   
    
    flightSettingsDictionary[@"flagLoadManifestSentForThisFlight"] = [NSString stringWithFormat:@"%d", flagLoadManifestSentForThisFlight  ]; 
    
    flightSettingsDictionary[@"numberOfLegsThisFlight"] = [NSString stringWithFormat:@"%d", allLegsPerFlightArray.count -1 ];
    //NSLog(@"saving numberOfLegsThisFlight %d", allLegsPerFlightArray.count -1);
    
    [allLegsPerFlightArray replaceObjectAtIndex:0 withObject:flightSettingsDictionary];    
    //NSLog(@"saving for leg  %@", vLegID);    
    //NSLog(@"saving tempFlightSettingsDictionary %@", flightSettingsDictionary);     
    [allLegsPerFlightArray replaceObjectAtIndex:[vLegID integerValue] withObject:legSettingsDictionary];    
    [allFlightsMasterArray replaceObjectAtIndex:[vFlightID integerValue] withObject:allLegsPerFlightArray];
    [defaults  setObject: allFlightsMasterArray  forKey:@"allFlightsMasterArray"];
    
  
    return;
    
    
    
      
      
 }






// top bar BUttons

- (void) arrangeWindows {
    
   
    [viewMain bringSubviewToFront:_viewHelicopterInCenter];
    [viewMain bringSubviewToFront:_viewStationsWindow];
    [viewMain bringSubviewToFront:_viewStationsWindowRight];
    [viewMain bringSubviewToFront:_viewFuelPanel];
    [viewMain bringSubviewToFront:_viewConfigurations];
    [_scrollViewTopDisplayButton bringSubviewToFront:viewTopDisplayButtons];
    [viewOne bringSubviewToFront:_scrollViewTopDisplayButton];
    [viewOne bringSubviewToFront:viewTopTop];
    [viewMain bringSubviewToFront:_viewCGLong];
    
    
    
}

- (void) displayWindows {
    
    
    if (configMode == 1) {
        [self setConfigWindow];
    }
    
    //NSLog(@"displayWindow flagShowCGEnvelopeValues %.0d", flagShowCGEnvelopeValues);
    
    if (flagShowCGEnvelopeValues == 1) {
        flagShowCGEnvelopeValues = 0;
         [self setCGwindows];
        [self setCGenvelope];
    }
    
    
    
    
    
    //NSLog(@"displayWindow %.0f", displayWindow);
    UIButton *prevButt = (UIButton *)[self.viewTopDisplayButtons viewWithTag:previousdButton];
    prevButt.selected = NO;
    
    [self addLegButtons];    
    [self.view endEditing:TRUE];
    
   
    
    configMode = 0;
   
    _scrollViewTopDisplayButton.hidden = NO;
    _viewLegButtons.hidden = YES;
    _labelNotePlanMode.hidden = YES;
    _viewHeliCenterLabels.userInteractionEnabled = YES;
    _viewEquipmentOnHeli.userInteractionEnabled = NO;
    _scrollViewHeliCenter.userInteractionEnabled = YES;
    
    // set config mode to off
    
    _buttonRefreshInterior.hidden = YES;
    _viewCGLong.hidden = NO;
    //_viewCGlat.hidden = NO;
    
    _scrollViewConfiguratorItems.hidden = NO;
    _scrollViewInteriorMaker.hidden = YES;
    _viewConfiguratorTotals.hidden = NO;
    _buttonRefreshInterior.hidden = YES;
    [_viewConfigurator bringSubviewToFront:_viewConfiguratorTotals];
    
    _viewPowerCheck.hidden = YES;
    _viewConfigurator.hidden = YES;
    _viewPilotList.hidden = YES;
    _viewSpecialEquiplist.hidden = YES;
    _viewSignature.hidden = YES;
    _viewFlightManager.hidden = YES;
    _viewDispatch.hidden = YES;
    _viewSetupOptionsForAdmin.hidden = YES;
    viewSetup.hidden = YES;
    _viewFleetManager.hidden = YES;
    _viewEquipmentListOverManifest.hidden = YES;

    
    [self arrangeWindows];
    
    if (flagIsLandscape == 1) {
         _viewTrennerTop.frame = CGRectMake(645, 115, 3, 634);
    }else{
        _viewTrennerTop.frame = CGRectMake(643, 55, 3, 630);
    }
    
    [viewOne bringSubviewToFront:_viewTrennerTop];
    _viewSummaryManifest.hidden = YES;
    viewEnvironment.hidden = YES;   enterPad.hidden = YES;   viewSetup.hidden = YES;
    viewLoadManifest.hidden = YES;   _viewTimers.hidden= YES; _viewAltimetry.hidden = YES;
    _viewLowerButtons.hidden  = NO;
    [viewOne bringSubviewToFront:_viewLowerButtons];
    
    if (flagIsLandscape == 1) {
        _viewLowerButtons.frame         = CGRectMake( 637, 701, 390, 50 ); // landscape
    }else{
        _viewLowerButtons.frame         = CGRectMake( 380, 957, 390, 50 ); // portrait
    }
    
    
    
    if (_segmentFlightLegMode.selectedSegmentIndex == 0) {
        _viewFlightManagment.hidden  = NO;
        _viewFlightManagment2.hidden  = YES;
        _labelLegManagement.hidden = YES;
        _viewButtonFlightSummary.hidden = YES;
        _displayButtonFlightSummary.hidden = YES;
    }else{
        _viewFlightManagment.hidden  = YES;
        _viewFlightManagment2.hidden  = NO;
        _labelLegManagement.hidden = NO;
        _viewButtonFlightSummary.hidden = NO;
        _displayButtonFlightSummary.hidden = NO;
    }
    
 
    if (displayWindow == 1 || displayWindow == 1000) { // environment
        [viewMain bringSubviewToFront:viewEnvironment]; viewEnvironment.hidden = NO;
    }
    
    
    if (displayWindow == 10) { //  Setup page
        viewSetup.hidden = NO;
        NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];
        _labelAccountName.text  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"activeCustomerName"];
        
        if ( [[NSUserDefaults standardUserDefaults]  stringForKey: @"licenseKey"].length > 3) {
            _labelAccountName.text  =  [ [NSString alloc] initWithFormat:@"%@ %@",  [[NSUserDefaults standardUserDefaults]  stringForKey: @"activeCustomerName"] ,  [[NSUserDefaults standardUserDefaults]  stringForKey: @"licenseKey"] ];
        }else{
            _labelAccountName.text  =  [ [NSString alloc] initWithFormat:@"%@",  [[NSUserDefaults standardUserDefaults]  stringForKey: @"activeCustomerName"]  ];
        }
            
        
         
        
        if ([customerFolderName isEqualToString:@"Test User"] || [customerFolderName isEqualToString:@"Tester"] ) {
             _viewSetupOptionsForAdmin.hidden = NO;
        }
        [viewOne bringSubviewToFront:viewSetup];  [viewOne bringSubviewToFront:viewTopTop];
        
    }
    
    
    if (displayWindow == 11) { //  Load Manifest
        [self copyLabelsManifest];
         viewLoadManifest.hidden= NO;
        _scrollViewTopDisplayButton.hidden = YES;  
        _viewLegButtons.hidden = YES;
        [viewOne bringSubviewToFront:viewLoadManifest];   [viewOne bringSubviewToFront:_viewLowerButtons];
        if (flagIsLandscape == 0) {
            _viewLowerButtons.center = CGPointMake( _viewLowerButtons.center.x , _viewLowerButtons.center.y - 46);
        }
    }
    
    
    if (displayWindow == 12) { //  FLIGHT MANAGER
        _viewFlightManager.hidden = NO;
        [viewOne bringSubviewToFront:_viewFlightManager];    [viewOne bringSubviewToFront:viewTopTop];
        [viewOne bringSubviewToFront:_viewSelectHelicopter];
        
        NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];    
        if ([customerFolderName isEqualToString:@"noAccount"] ) { 
            _viewSelectHelicopter.hidden = YES;
            [viewOne bringSubviewToFront:_viewFleetManager]; 
        }
        
        
        [self SaveValues];
        [self createFlightButtons];
    }
    
  
    
    
    

    if (displayWindow == 14) { // summary
        [self copyLabelsManifest];
        _viewSummaryManifest.hidden= NO;
        [self createSummaryLabels];
        [viewOne bringSubviewToFront:_viewSummaryManifest];   _viewLowerButtons.hidden = YES;
        [_viewSummaryManifest bringSubviewToFront:_viewSummaryLowerButtons]; _viewSummaryLowerButtons.hidden = NO;
    }


    if (displayWindow == 15) { //  Timers
        _viewTimers.hidden= NO;
        [viewOne bringSubviewToFront:_viewTimers];    [viewOne bringSubviewToFront:viewTopTop]; [viewOne bringSubviewToFront:_viewLowerButtons];
    }
    
    if (displayWindow == 99) { //  Generic
        _viewFleetManager.hidden = NO;
        [viewOne bringSubviewToFront:_viewFleetManager]; 
        
    }
    
    
 
    
     if (displayWindow == 0) {
         triggerDoNotShowPerfChart = 0;
         viewEnvironment.hidden = YES;
         
         if (_segmentFlightLegMode.selectedSegmentIndex == 1) {
             _viewLegButtons.hidden = NO;
             [_scrollViewTopDisplayButton bringSubviewToFront:viewTopDisplayButtons];
             [viewOne bringSubviewToFront: _scrollViewTopDisplayButton];
             
         }
         
         if (flagSpecialPHIFlightSettingPage == 1) {
             _viewLegData.hidden = NO; 
             [viewOne bringSubviewToFront:_viewLegData];
           
            
         }
         
     }
    
     [self MainRoutine];
    
   
    
    
}

- (IBAction)buttonActionDisplaySetup:(id)sender {
    
    _viewDlist.hidden = YES;
    
    displayWindow = 10;
    
    [self displayWindows];
    
}






- (IBAction)buttonActionOpenFlightPage:(id)sender {
    
     displayWindow = 12;
    
    [self displayWindows];  
    
    
}


- (IBAction)buttonActionOpenMainPage:(id)sender {
    
    displayWindow = 0;
    
    [self displayWindows];
    
    
}



// Manifest

- (IBAction)buttonActionLoadManifest:(id)sender {
    
    displayWindow = 11;
    [self displayWindows];
    
    
}

- (IBAction)buttonActionCloseLoadManifest:(id)sender {
    
    viewLoadManifest.hidden = YES;
    
     displayWindow = 0;
    
     [self displayWindows]; 
    
}





// ENVIRONMENT sliders

- (IBAction)sliderActionOATforOGE:(id)sender {
    
    int dummy = sliderOATforOGE.value/1;
    sliderOATforOGE.value = dummy * 1;
    
    
    
    [self MainRoutine];

    
}

- (IBAction)sliderActionISAdiff:(id)sender {
    
    int dummy = sliderISADiff.value/1;
    sliderISADiff.value = dummy * 1;
    [self MainRoutine];
}


- (IBAction)sliderActionNVG:(id)sender {
    
    int dummy = _sliderNVG.value/1;
    _sliderNVG.value = dummy * 1;
    [self MainRoutine];
}

- (void) createLabelsForSetupPage {
    
    //NSLog(@"createLabelsForSetupPage");
    
    _setupOptionQuickLoad.hidden = YES;
    _setupOptionFuelDensity.hidden = YES;
    _setupOptionPeformanceWarnings.hidden = YES;
    _setupOptionDataEntryCheck.hidden = YES;
    _setupOptionSliderIncrement.hidden = YES;
    
    _segmentFlightLegMode.hidden = YES;
    _segmentFuelVolumeOrMass.hidden = NO;
    _segmentCGAutoCheck.hidden = YES;
    _segmentSeatLoadOptions.hidden = YES;
    _segmentSwapMode.hidden = YES;
    _segmentNamesOnSeats.hidden = YES;
    _viewNVGFilterSettings.hidden = YES;
    
    
    NSMutableArray *arraySetupOptions = [[NSMutableArray alloc] init];
    if ([[_arrayName22 objectAtIndex:47] isEqualToString:@""] ) {
        [arraySetupOptions addObject:@"_setupOptionQuickLoad;1"];
        [arraySetupOptions addObject:@"_setupOptionFuelDensity;1"];
        [arraySetupOptions addObject:@"_setupOptionPeformanceWarnings;1"];
        [arraySetupOptions addObject:@"_setupOptionDataEntryCheck;0"];
        [arraySetupOptions addObject:@"_setupOptionSliderIncrement;0"];
        [arraySetupOptions addObject:@"_segmentFlightLegMode;0"];
        [arraySetupOptions addObject:@"_segmentFuelVolumeOrMass;0"];
        [arraySetupOptions addObject:@"_segmentCGAutoCheck;0"];
        [arraySetupOptions addObject:@"_segmentSeatLoadOptions;0"];
        [arraySetupOptions addObject:@"_segmentSwapMode;0"];
        [arraySetupOptions addObject:@"_segmentNamesOnSeats;0"];
        [arraySetupOptions addObject:@"_viewNVGFilterSettings;0"];
    }else{
        // read special load manifest data
        NSString *allManifestData = @"";
        //NSLog(@"allManifestData %@", allManifestData);
        allManifestData = [_arrayName22 objectAtIndex:47];
        NSCharacterSet*charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"+"];
        NSArray *arrayComponentsManifestData = [allManifestData componentsSeparatedByCharactersInSet:charSet1];
        
        for(int i=0; i<arrayComponentsManifestData.count; i++) {
            if ([[arrayComponentsManifestData objectAtIndex:i]length] > 4) {
                [arraySetupOptions addObject: [arrayComponentsManifestData objectAtIndex:i]];
            }
        }
    }
    
   
    
  
    
    float yPosSetupElement = 0;
    float lineIncrement = 45;
    float yStart = -20;
 
    for(int i=0; i<arraySetupOptions.count; i++) {
       
        
        NSCharacterSet*charSet1 = [NSCharacterSet characterSetWithCharactersInString:@";"];
        NSArray *arrayComponents = [[arraySetupOptions objectAtIndex:i] componentsSeparatedByCharactersInSet:charSet1];
        
        NSString *sertupElement = arrayComponents[0];
        float onOff = [arrayComponents[1] floatValue];
        
        if (onOff == 1) {
             yPosSetupElement = yPosSetupElement + 1;
        }
        
        if ([sertupElement isEqualToString:@"_setupOptionQuickLoad"]) {
            if (onOff == 1) {
                _setupOptionQuickLoad.hidden = NO;
                _setupOptionQuickLoad.frame = CGRectMake(0, yStart + yPosSetupElement * lineIncrement , 335, 29);
            }
        }
        
        if ([sertupElement isEqualToString:@"_setupOptionFuelDensity"]) {
            if (onOff == 1) {
                _setupOptionFuelDensity.hidden = NO;
                _setupOptionFuelDensity.frame = CGRectMake(0, yStart + yPosSetupElement * lineIncrement , 335, 29);
            }
        }
        if ([sertupElement isEqualToString:@"_setupOptionPeformanceWarnings"]) {
            if (onOff == 1) {
                _setupOptionPeformanceWarnings.hidden = NO;
                _setupOptionPeformanceWarnings.frame = CGRectMake(0, yStart + yPosSetupElement * lineIncrement , 335, 29);
            }
        }
        if ([sertupElement isEqualToString:@"_setupOptionDataEntryCheck"]) {
            if (onOff == 1) {
                _setupOptionDataEntryCheck.hidden = NO;
                _setupOptionDataEntryCheck.frame = CGRectMake(0, yStart + yPosSetupElement * lineIncrement , 335, 29);
            }
        }
        if ([sertupElement isEqualToString:@"_setupOptionSliderIncrement"]) {
            if (onOff == 1) {
                _setupOptionSliderIncrement.hidden = NO;
                _setupOptionSliderIncrement.frame = CGRectMake(0, yStart + yPosSetupElement * lineIncrement , 335, 29);
            }
        }
        if ([sertupElement isEqualToString:@"_segmentFlightLegMode"]) {
            if (onOff == 1) {
                _segmentFlightLegMode.hidden = NO;
                _segmentFlightLegMode.frame = CGRectMake(0, yStart + yPosSetupElement * lineIncrement , 335, 29);
            }
        }
        if ([sertupElement isEqualToString:@"_segmentFuelVolumeOrMass"]) {
            if (onOff == 1) {
                _segmentFuelVolumeOrMass.hidden = NO;
                
            }
        }
        if ([sertupElement isEqualToString:@"_segmentCGAutoCheck"]) {
            if (onOff == 1) {
                _segmentCGAutoCheck.hidden = NO;
                _segmentCGAutoCheck.frame = CGRectMake(0, yStart + yPosSetupElement * lineIncrement , 335, 29);
            }
        }
        if ([sertupElement isEqualToString:@"_segmentSeatLoadOptions"]) {
            if (onOff == 1) {
                _segmentSeatLoadOptions.hidden = NO;
                _segmentSeatLoadOptions.frame = CGRectMake(0, yStart + yPosSetupElement * lineIncrement , 335, 29);
            }
        }
        if ([sertupElement isEqualToString:@"_segmentSwapMode"]) {
            if (onOff == 1) {
                _segmentSwapMode.hidden = NO;
                _segmentSwapMode.frame = CGRectMake(0, yStart + yPosSetupElement * lineIncrement , 335, 29);
            }
        }
        if ([sertupElement isEqualToString:@"_segmentNamesOnSeats"]) {
            if (onOff == 1) {
                _segmentNamesOnSeats.hidden = NO;
                _segmentNamesOnSeats.frame = CGRectMake(0, yStart + yPosSetupElement * lineIncrement , 335, 29);
            }
        }
        if ([sertupElement isEqualToString:@"_viewNVGFilterSettings"]) {
            if (onOff == 1) {
                _viewNVGFilterSettings.hidden = NO;
                _viewNVGFilterSettings.frame = CGRectMake(0, yStart + yPosSetupElement * lineIncrement , 343, 93);
            }
        }
        
        
    }
    
    [_scrollViewSetupItems setScrollEnabled:YES];
    [_scrollViewSetupItems setContentSize:CGSizeMake(_viewSetupItems.frame.size.width, 250 + yPosSetupElement * (lineIncrement + 5) )];

    
    
  
    
}

- (void) createLabelsForLoadManifest {
    
    _mani_flightTime.text = [ [NSString alloc] initWithFormat:@"%@h : %@min", _vFlightTimeHours.text , _vFlightTimeMinutes.text ];
    
    _mani_PilotsName.text = [_arrayName7 objectAtIndex:linePilot];
    
    
     NSMutableArray *arrayManifestItems = [[NSMutableArray alloc] init];
    if ([[_arrayName22 objectAtIndex:45] isEqualToString:@""] ) {
        [arrayManifestItems addObject:@"Registration;flightRegistration;93;140;152;21;17;1"];
        [arrayManifestItems addObject:@"Flight ID;flightID;275;140;152;21;17;1"];
        [arrayManifestItems addObject:@"Leg ID;legID;275;140;152;21;17;0"];
        [arrayManifestItems addObject:@"AC Type;acType;457;140;142;21;17;1"];
        [arrayManifestItems addObject:@"Configuration;configuration;600;140;180;21;17;1"];
        [arrayManifestItems addObject:@"Flight Type;flightType;820;140;152;21;17;1"];
        [arrayManifestItems addObject:@"Flight Date and Time;fligthDateAndTime;690;237;300;21;16;1"];
        [arrayManifestItems addObject:@"Departure;departure;690;280;145;21;16;1"];
        [arrayManifestItems addObject:@"Destination;destination;844;280;145;21;16;1"];
        [arrayManifestItems addObject:@"Remarks;remarks;690;1133;300;21;14;1"];
        [arrayManifestItems addObject:@"Flight Duration;flightDuration;690;280;145;21;16;0"];
        [arrayManifestItems addObject:@"Pilot;pilotName;93;140;152;21;17;0"];
        [arrayManifestItems addObject:@"Co Pilot;copilotName;275;140;152;21;17;0"];
        [arrayManifestItems addObject:@"Flight Data;headerFlightData;674;188;328;44;17;1"];
        [arrayManifestItems addObject:@"CG Envelope;headerCGEnvelope;674;381;328;44;17;1"];
        [arrayManifestItems addObject:@"Performance;headerPerformance;674;881;328;44;17;1"];
        [arrayManifestItems addObject:@";viewCGenvelopes;680;434;321;430;0;1"];
        [arrayManifestItems addObject:@";viewPerformanceData;680;927;319;297;0;1"];
        [arrayManifestItems addObject:@"SOB;paxOnBoard;638;140;152;21;17;0"];
        [arrayManifestItems addObject:@"Calculations based on weighing report dated: ;dateOfWeighing;690;330;299;21;13;0"];
        [arrayManifestItems addObject:@"Weighing Remarks;weighingRemarks;690;386;299;21;15;0"];
        [arrayManifestItems addObject:@"documentPreparedBy;documentPreparedBy;680;1200;311;123;0;1"];    
        [arrayManifestItems addObject:@"integrityVerification;integrityVerification;680;1200;311;123;0;0"];
        [arrayManifestItems addObject:@"extraSpruchManifest;extraSpruchManifest;0;0;0;0;0;0"];
       
    }else{
        // read special load manifest data
        NSString *allManifestData = @"";
        //NSLog(@"allManifestData %@", allManifestData);
        allManifestData = [_arrayName22 objectAtIndex:45];
        NSCharacterSet*charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"+"];
        NSArray *arrayComponentsManifestData = [allManifestData componentsSeparatedByCharactersInSet:charSet1];
        
        for(int i=0; i<arrayComponentsManifestData.count; i++) {
            if ([[arrayComponentsManifestData objectAtIndex:i]length] > 4) {
                [arrayManifestItems addObject: [arrayComponentsManifestData objectAtIndex:i]];
            }
        }
    }
    
    //NSLog(@"arrayManifestItems %@", arrayManifestItems);
    for(UIView *subview in [_viewManifestLabels subviews]) {
        [subview removeFromSuperview];
    }
    [ScrollViewManifest bringSubviewToFront:_viewManifestLabels ];
    
    
    _viewDocumentPreparedBy.hidden = YES;    
    _viewIntegrityVerification.hidden = YES;
    
    for(int i=0; i<arrayManifestItems.count; i++) {
        NSCharacterSet*charSet1 = [NSCharacterSet characterSetWithCharactersInString:@";"];
        NSArray *arrayComponents = [[arrayManifestItems objectAtIndex:i] componentsSeparatedByCharactersInSet:charSet1];
        //NSLog(@"arrayComponents %@", arrayComponents);
        
        //NSLog(@"[arrayComponents[7] %@ %@", arrayComponents[0], arrayComponents[7] );
        
        
        float onOff = [arrayComponents[7] floatValue];
        if (onOff == 0) {
            continue;
        }
        NSString *labelName = arrayComponents[0];
        NSString *labelVariabel = arrayComponents[1];
        float xPosLabel = [arrayComponents[2] floatValue];
        float yPosLabel = [arrayComponents[3] floatValue];
        float widthLabel = [arrayComponents[4] floatValue];
        float heightLabel = [arrayComponents[5] floatValue];
        float fontSize = [arrayComponents[6] floatValue];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xPosLabel, yPosLabel, widthLabel, heightLabel)];
        label.font = [UIFont systemFontOfSize:fontSize];
        label.textAlignment = NSTextAlignmentLeft;
        label.adjustsFontSizeToFitWidth = YES;
        
        if ([_vFlightTypeField.text rangeOfString:@"("].location != NSNotFound) {
          NSArray *listItems = [_vFlightTypeField.text componentsSeparatedByString:@"("];
            _vFlightTypeField.text = [listItems objectAtIndex:0];
        }
        
        
      
        
        //NSLog(@"labelName %@", labelName);
        //NSLog(@"labelVariabel %@", labelVariabel);
        
        // get variable
        NSString *resultLabel;
        UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(xPosLabel, yPosLabel + 20, widthLabel, heightLabel)];
        label2.font = [UIFont boldSystemFontOfSize:fontSize];
        label2.textAlignment = NSTextAlignmentLeft;
        label2.adjustsFontSizeToFitWidth = YES;
        
        if ([labelVariabel isEqualToString:@"flightRegistration"]) {
            resultLabel = vFlightRegistration.text;
        }
        if ([labelVariabel isEqualToString:@"flightID"]) {
            resultLabel = _vFlightIDName.text;
        }
        if ([labelVariabel isEqualToString:@"legID"]) {
            resultLabel = vLegID;
        }
        if ([labelVariabel isEqualToString:@"acType"]) {
           
            NSString *ACTypeForLogoOnly = AC_Type;
            if (ACTypeForLogoOnly.length > 0) {
                if ([[ACTypeForLogoOnly substringFromIndex: [ACTypeForLogoOnly length] - 3] isEqualToString:@"P2P"] || [[ACTypeForLogoOnly substringFromIndex: [ACTypeForLogoOnly length] - 3] isEqualToString:@"T2P"]) {            
                    ACTypeForLogoOnly = [ACTypeForLogoOnly substringToIndex:[ACTypeForLogoOnly length] - 2];  
                    ACTypeForLogoOnly = [ACTypeForLogoOnly stringByAppendingString:@"2+"]; 
                }
            }
             resultLabel = ACTypeForLogoOnly;
            
        }
        if ([labelVariabel isEqualToString:@"configuration"]) {
            resultLabel = arrayConfigurations[configuration];
        }
        if ([labelVariabel isEqualToString:@"flightType"]) {
            resultLabel = _vFlightTypeField.text;
        }
        if ([labelVariabel isEqualToString:@"fligthDateAndTime"]) {
            resultLabel = _labelDepartureTimeLocal.text;
        }
        if ([labelVariabel isEqualToString:@"departure"]) {
            resultLabel = vFlightDeparture.text;
        }
        if ([labelVariabel isEqualToString:@"destination"]) {
            resultLabel = vFlightDestination.text;
        }
        if ([labelVariabel isEqualToString:@"remarks"]) {
            resultLabel = _vFlightRemarks.text;
        }
        if ([labelVariabel isEqualToString:@"flightDuration"]) {
            resultLabel = _mani_flightTime.text;
        }
        if ([labelVariabel isEqualToString:@"pilotName"]) {
            resultLabel = [_arrayName7 objectAtIndex:linePilot];
        }
        if ([labelVariabel isEqualToString:@"copilotName"]) {
            resultLabel = [_arrayName7 objectAtIndex:linePilot+1];
        }
        if ([labelVariabel isEqualToString:@"headerFlightData"]) {
            _viewManifestHeaderFlightData.frame = CGRectMake(xPosLabel, yPosLabel, widthLabel, heightLabel);
            label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont boldSystemFontOfSize:fontSize];
            resultLabel = @"";
        }
        if ([labelVariabel isEqualToString:@"headerCGEnvelope"]) {
            _viewManifestHeaderCGEnvelope.frame = CGRectMake(xPosLabel, yPosLabel, widthLabel, heightLabel);
           label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont boldSystemFontOfSize:fontSize];
           resultLabel = @"";
        }
        if ([labelVariabel isEqualToString:@"headerPerformance"]) {
            _viewManifestHeaderPerformance.frame = CGRectMake(xPosLabel, yPosLabel, widthLabel, heightLabel);
            label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont boldSystemFontOfSize:fontSize];
            resultLabel = @"";
        }
        if ([labelVariabel isEqualToString:@"viewCGenvelopes"]) {
            _viewCGenvelopesManifest.frame = CGRectMake(xPosLabel, yPosLabel, widthLabel, heightLabel);
            labelName = @"";
            resultLabel = @"";
        }
        if ([labelVariabel isEqualToString:@"viewPerformanceData"]) {
            _viewPerformanceData.frame = CGRectMake(xPosLabel, yPosLabel, widthLabel, heightLabel);
            labelName = @"";
            resultLabel = @"";
        }
        
        if ([labelVariabel isEqualToString:@"dateOfWeighing"]) {
            resultLabel = dateOfWeighing;
            //NSLog(@"resultLabel %@", resultLabel);
            
        }
        
        
        if ([labelVariabel isEqualToString:@"weighingRemarks"]) {
            resultLabel = weighingRemarks;
        }
        
        if ([labelVariabel isEqualToString:@"paxOnBoard"]) {
            resultLabel = _inputPaxOnBoard.text;
        }
        
        if ([labelVariabel isEqualToString:@"documentPreparedBy"]) {
            _viewDocumentPreparedBy.frame = CGRectMake(xPosLabel, yPosLabel, widthLabel, heightLabel);
            _viewDocumentPreparedBy.hidden = NO;
            labelName = @"";
            resultLabel = @"";
        }
        
        if ([labelVariabel isEqualToString:@"integrityVerification"]) {
            _viewIntegrityVerification.frame = CGRectMake(xPosLabel, yPosLabel, widthLabel, heightLabel);
            _viewIntegrityVerification.hidden = NO;
            labelName = @"";
            resultLabel = @"";
        }
        
        if ([labelVariabel isEqualToString:@"extraSpruchManifest"]) {                     
            resultLabel = @""; 
            labelName  = [ labelName stringByReplacingOccurrencesOfString:@"'" withString:@","];            
            label.frame = CGRectMake(xPosLabel, yBottomManifest, widthLabel, heightLabel);
            label.numberOfLines = 6;
        }
        
        if ([labelVariabel isEqualToString:@"enduranceHoursMin"]) {
            resultLabel = @"endurance";
            resultLabel = [ [NSString alloc] initWithFormat:@"%dh : %dmin", enduranceHours , enduranceMinutesOnly ];
        }
        
        if ([labelVariabel isEqualToString:@"flightTimeHoursMin"]) {
            resultLabel = [ [NSString alloc] initWithFormat:@"%@h : %@min", _vFlightTimeHours.text , _vFlightTimeMinutes.text ];
        }
        
        // add the custom items
         //NSLog(@"labelVariabel %@", labelVariabel);
        
        if ([labelVariabel rangeOfString:@"custom"].location != NSNotFound  ) { 
            if ([labelVariabel intValue] > 0) {
                UITextField *viewElement = (UITextField*)[_viewCustomFlightDataElements viewWithTag: 16 + [labelVariabel intValue] ]; 
                //NSLog(@"viewElement %@", viewElement.text);                
                resultLabel = viewElement.text;
            }
        }
        
       
        
        
        
        //NSLog(@"resultLabel %@", resultLabel);
        if (resultLabel.length > 12) {
            label2.font = [UIFont boldSystemFontOfSize:14];
        }
        
        [_viewManifestBackground bringSubviewToFront:_viewDocumentPreparedBy];
        
        //add label1
        label.text = labelName;
        [_viewManifestLabels addSubview:label];
       
        //add label 2
        label2.text = resultLabel;
        [_viewManifestLabels addSubview:label2];
        
    }
}


- (void) copyLabelsManifest {
    
    flagManifestOpen = 1;
    [self calcPerformance];
    flagManifestOpen = 0;
    
    [self createItemListForLoadManifest];
    [self createTimeStamp];
    [self animateFuelPathManifest];
    
    [self createLabelsForLoadManifest];

    _input_documentPreparedBy.text = [_arrayName7 objectAtIndex:linePilot];
    
    //NSLog(@"makePerfLabels1 ");
    for(UIView *subview in [_viewPerformanceData subviews]) {
        [subview removeFromSuperview];
    }
    
    [self makePerfLabels];
    return;
    
}

- (void) makePerfLabels {
    
    // make performance data labels    
    //NSLog(@"makePerfLabels ");    
    
    NSMutableArray *enviDataArray = [[NSMutableArray alloc] init];
    [enviDataArray removeAllObjects];
    [enviDataArray setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:@"resultsAllEnviSettings"] mutableCopy]];
    
    
   
    
    if ([[_arrayName25 objectAtIndex:29] isEqualToString:@"yes"] || [[_arrayName25 objectAtIndex:29]length] > 3) {
        // add max avail to manifest        
        //NSLog(@"1 enviDataArray@");
        NSString *addString = [ [NSString alloc] initWithFormat:@"%@| |15|0|0|standard", _labelAvailableExternalLoad.text ];          
        [enviDataArray addObject:addString];
        
        //second max avail
        if (![[_arrayName25 objectAtIndex:25] isEqualToString:@""]) {
            //NSLog(@"2 enviDataArray@");
            addString = [ [NSString alloc] initWithFormat:@"%@| |15|0|0|standard", _label2AvailableExternalLoad.text ];          
            [enviDataArray addObject:addString];            
        }
       
    }
    
    //NSLog(@"enviDataArray %@", enviDataArray);
    
    float labelIncr = 22;    
    float labelBreite = 300; float labelHoehe = 20;    
    float topSpace = -20;
    float yPos = 0;
    
    float triggerAddParameters = 0;
    
    
        
    for (int i = 0; i<enviDataArray.count; ++i) {
        
        NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"|"];
        NSArray *components = [[enviDataArray objectAtIndex:i] componentsSeparatedByCharactersInSet:charSet]; 
        NSString *perfName = [components objectAtIndex:0];       
        perfName = [perfName stringByReplacingOccurrencesOfString:@"_" withString:@" "];
        NSString *result = [components objectAtIndex:1];
        NSString *OATused = [components objectAtIndex:2];
        NSString *PAused = [components objectAtIndex:3];
        NSString *Windused = [components objectAtIndex:4];   
        NSString *compType = [components objectAtIndex:5];
        
        NSString *itemText =  perfName;
        NSString *resultext =   result;
        
        
        if ( [compType isEqualToString:@"CustomFixedWingOLD"]) {
                              
            if ([perfName isEqualToString:@"TOGroundRoll"]) {   
                perfName = @"Takeoff";
            }
            if ([perfName isEqualToString:@"ClimbComp"]) {   
                perfName = @"Climb";
            }
            if ([perfName isEqualToString:@"LDGGroundRoll"]) {   
                perfName = @"Landing";
            }
            if ([perfName isEqualToString:@"CruiseComp"]) {   
                perfName = @"Cruise";
            }
            
            triggerAddParameters = 1;    
            labelIncr = 45;
        }
        
        if ([compType isEqualToString:@"FXX"]) {
            
                   
            if ([perfName isEqualToString:@"Takeoff"]) {   
                perfName = @"Takeoff";
            }
            if ([perfName isEqualToString:@"ClimbComp"]) {   
                perfName = @"Climb";
            }
            if ([perfName isEqualToString:@"Landing"]) {   
                perfName = @"Landing";
            }
            if ([perfName isEqualToString:@"CruiseComp"]) {   
                perfName = @"Cruise";
            }
            
            if (i > 3) {
                continue;
            }
            
            triggerAddParameters = 1;    
            labelIncr = 45;
        }
        
        
        yPos = yPos + labelIncr; 
        
        
        
        
        NSString *parameters1;
        NSString *parameters2;
        
        NSString *parametersFixedWing =  [[NSString alloc] initWithFormat:@"OAT: %@ºC, PA: %@ft, Wind: %@kts", OATused, PAused, Windused];
        
       if ( [unitsAltimeter isEqualToString:@"US"]) { 
           parameters1 =   [ [NSString alloc] initWithFormat:@"OAT: %@ºC, PA: %@ft / %@ IN.Hg", OATused, PAused, labelQNH.text];
           parameters2 =   [ [NSString alloc] initWithFormat:@"Wind: %@kts",  Windused ];
       }else{
           parameters1 =   [ [NSString alloc] initWithFormat:@"OAT: %@ºC, PA: %@ft / %@ hPa", OATused, PAused, labelQNHEuro.text];
           parameters2 =   [ [NSString alloc] initWithFormat:@"Wind: %@kts",  Windused ];
       }
          
        if (amountofButtonsNeeded < 1) {
            parameters1 = @"";
            parameters2 = @"";
        }
      
        
       
        
        
        if (triggerAddParameters == 0 & i == 0) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(7,  topSpace + yPos, labelBreite, labelHoehe)];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textColor = [UIColor blackColor];
            label.textAlignment = NSTextAlignmentLeft;        
            [label  setText: parameters1 ];
            [_viewPerformanceData addSubview: label];
            yPos = yPos + labelIncr; 
            
            label = [[UILabel alloc] initWithFrame:CGRectMake(7,  topSpace + yPos, labelBreite, labelHoehe)];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textColor = [UIColor blackColor];
            label.textAlignment = NSTextAlignmentLeft;        
            [label  setText: parameters2 ];
            [_viewPerformanceData addSubview: label];
            yPos = yPos + labelIncr;  
            
        }
            
            
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(7,  topSpace + yPos, labelBreite, labelHoehe)];
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentLeft;
        [label  setText: itemText  ];
        [_viewPerformanceData addSubview: label];
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(7,  topSpace + yPos, labelBreite, labelHoehe)];
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentRight;
        [label  setText: resultext  ];
        [_viewPerformanceData addSubview: label];
                
        
        
        if (triggerAddParameters == 1) {
            label = [[UILabel alloc] initWithFrame:CGRectMake(7,  topSpace + yPos + 18, labelBreite, labelHoehe)];
            label.font = [UIFont systemFontOfSize:14];
            label.textColor = [UIColor blackColor];
            label.textAlignment = NSTextAlignmentLeft;        
            [label  setText: parametersFixedWing ];
             [_viewPerformanceData addSubview: label];
         
        }
       
        
        
    }
    return;
    
}







- (IBAction)buttonActionToggleOATinput:(id)sender {
    
    if (OATinput == 0) {        
        OATinput =1; viewSliderISA.hidden = NO;
        [self iEnviCalcALL];
    } else {        
        OATinput =0; viewSliderISA.hidden = YES;
        [self iEnviCalcALL];
        
    }
    
    [self MainRoutine];
    
}






// close keyboard

- (IBAction)closeKeyboard:(id)sender {        
    [self.view endEditing:TRUE];    
    [self checkGuidance];    
    [self MainRoutine];  
    [self MainRoutine];
}

- (IBAction)closeKeyboardAndSaveFuelDensity:(id)sender {        
    [self.view endEditing:TRUE]; 
    
    if ([fuelUnits isEqualToString:@"lbs"]) {        
        [_arrayName21 replaceObjectAtIndex:20 withObject:_inputSpecificFuelMassPerVolume.text]; 
    }else{
        [_arrayName21 replaceObjectAtIndex:22 withObject:_inputSpecificFuelMassPerVolume.text]; 
    }  
    
    [self checkGuidance];    
    [self MainRoutine];    
}


- (IBAction)closeKeyboardAndConvertFuelDensity:(id)sender {        
    [self.view endEditing:TRUE]; 
    
  
     if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) {
         float convertedSpecific = [_inputFuelDensityConverted.text floatValue] * 2.2046 * 3.78541;
         //NSLog(@"convertedSpecific %.3f", convertedSpecific);
         _inputSpecificFuelMassPerVolume.text = [[NSString alloc] initWithFormat:@"%.3f", convertedSpecific];
     }
    
    if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) {
        float convertedSpecific = [_inputFuelDensityConverted.text floatValue] / 2.2046 / 3.78541;
        //NSLog(@"convertedSpecific %.3f", convertedSpecific);
        _inputSpecificFuelMassPerVolume.text = [[NSString alloc] initWithFormat:@"%.3f", convertedSpecific];
    }
    
    
    
    [self MainRoutine];    
}



- (IBAction)closeKeyboardSafetyMargin:(id)sender {
    
    
    [self.view endEditing:TRUE];
  
    [self setCGenvelope];
    
    [self MainRoutine];
    
}


- (IBAction)closeKeyboardPaxEntry:(id)sender {
    
    
    
    [self.view endEditing:TRUE];
    
    [self setPaxOnBoard];
    
    [self MainRoutine];
    
}




- (void) setPaxOnBoard {
    
    //NSLog(@"setPaxOnBoard");
    
    NSCountedSet *set = [[NSCountedSet alloc] initWithArray:_arrayName10];
    int numberOfSeats = (unsigned long)[set countForObject:@"seat"];
    //NSLog(@"fwd numberOfSeats %d", numberOfSeats);
    
    int configStationsStart = 0;
    int configStationsEnd = 0;
    configStationsStart = [[_arrayName23 objectAtIndex:11] intValue];
    configStationsEnd = configStationsStart + numberOfSeats-2;
    
    
    NSString *averagePaxWeight;
    
    if ([[_arrayName1 objectAtIndex:0] isEqualToString:@"Offshore"]) {
        averagePaxWeight = @"98";
    }else{
        averagePaxWeight = @"86";
    }
    
    
    int availableSeats = 0;
    int allocatedSeats = 0;
    
    for (int i = configStationsStart; i < configStationsEnd ; i++) {
        if ( [[_arrayName8 objectAtIndex:i] floatValue] == 1) {
            availableSeats = availableSeats +1;
        }
    }
    // sanitizing
    if ([_inputPaxOnBoard.text intValue] > availableSeats) {
        _inputPaxOnBoard.text = [ [NSString alloc] initWithFormat:@"%d", availableSeats];
    }
    if ([_inputPaxOnBoard.text intValue] < 0) {
        _inputPaxOnBoard.text = @"0";
    }
    
    int desiredSeats = [_inputPaxOnBoard.text intValue];
    
    for (int i = configStationsStart; i < configStationsEnd ; i++) {
        // check if seat is available
        if ( [[_arrayName8 objectAtIndex:i] floatValue] == 1) {
            // check if we need it
            if (allocatedSeats < desiredSeats) {
                NSString *usedPaxWeight =  averagePaxWeight;
                [_arrayName2 replaceObjectAtIndex:i  withObject:usedPaxWeight ];
                float momentLong = [usedPaxWeight floatValue] * [[_arrayName3 objectAtIndex:i] floatValue];
                [_arrayName4 replaceObjectAtIndex:i  withObject: [[NSString alloc] initWithFormat:@"%.0f", momentLong]  ];
                float momentLat = [usedPaxWeight floatValue] * [[_arrayName5 objectAtIndex:i] floatValue];
                [_arrayName6 replaceObjectAtIndex:i  withObject: [[NSString alloc] initWithFormat:@"%.0f", momentLat]  ];
                [_arrayName7 replaceObjectAtIndex:i  withObject:@"-" ];
                allocatedSeats = allocatedSeats + 1;
            }else{
                NSString *usedPaxWeight = @"0";
                [_arrayName2 replaceObjectAtIndex:i  withObject:usedPaxWeight ];
                float momentLong = [usedPaxWeight floatValue] * [[_arrayName3 objectAtIndex:i] floatValue];
                [_arrayName4 replaceObjectAtIndex:i  withObject: [[NSString alloc] initWithFormat:@"%.0f", momentLong]  ];
                float momentLat = [usedPaxWeight floatValue] * [[_arrayName5 objectAtIndex:i] floatValue];
                [_arrayName6 replaceObjectAtIndex:i  withObject: [[NSString alloc] initWithFormat:@"%.0f", momentLat]  ];
                [_arrayName7 replaceObjectAtIndex:i  withObject:@"-" ];
            }
            
            
            
        }else{
            continue;
        }
    }
    
    [self MainRoutine];
}



- (IBAction)actionBringAllPaxFWD:(id)sender {
    
    if (flagRecallSeat == 0) {
        flagRecallSeat = 1;
        
        [self memorizeSeating];
    }
    
    [self setPaxFWD];
    flagDoNOTheckFWDAFTCG = 1;
    [self MainRoutine];
    
}

- (IBAction)actionBringAllPaxAFT:(id)sender {
    
    if (flagRecallSeat == 0) {
        flagRecallSeat = 1;
        
        [self memorizeSeating];
    }
    
    [self setPaxAFT];
    flagDoNOTheckFWDAFTCG = 1;
    [self MainRoutine];
    
    
    
}

- (void) autoCheckFWDAFTCG {
    
    //NSLog(@"autoCheckFWDAFTCG");
    
    if (flagDoNOTheckFWDAFTCG == 1) {
        
        flagDoNOTheckFWDAFTCG = 0;
        
        return;
    }
    
    _labelCGWarning.hidden = YES;
    
    
    [self memorizeSeating];
    
    
    counterAutoCheckFlagStatus = 0;
    
    
    
    //NSLog(@"totalSeatWeight %.0f", totalSeatWeight);
    
    if (totalSeatWeight < 1) {
        return;
    }
    
    [self setPaxFWD];
    [self calculateListo];
    
    if (warningCGoutsideEnvelope.hidden == NO) {
        counterAutoCheckFlagStatus = 1;
    }
    
    if (counterAutoCheckFlagStatus == 3) {
        _labelCGWarning.hidden = NO;
        _labelCGWarning.text = @"SAFETY MARGIN EXCEEDED\nWITH ALL PAX FWD";
        _labelCGWarning.backgroundColor = yellowSpecialColor;
        _labelCGWarning.textColor = [UIColor blackColor];
        
    }
    
    
    if (counterAutoCheckFlagStatus == 1) {
        _labelCGWarning.hidden = NO;
        _labelCGWarning.text = @"CG EXCEEDED\nWITH ALL PAX FWD";
        _labelCGWarning.backgroundColor = [UIColor redColor];
        
    }
    if (counterAutoCheckFlagStatus == 2) {
        _labelCGWarning.hidden = NO;
        _labelCGWarning.text = @"TO IN EXT. ENV.\nWITH ALL PAX FWD";
        _labelCGWarning.backgroundColor = [UIColor orangeColor];
        _labelCGWarning.textColor = [UIColor blackColor];
        
    }
    
    //NSLog(@"1 counterAutoCheckFlagStatus %d", counterAutoCheckFlagStatus);
    
    
    
    counterAutoCheckFlagStatus = 0;
    
    [self setPaxAFT];
    [self calculateListo];
    
    if (warningCGoutsideEnvelope.hidden == NO) {
        counterAutoCheckFlagStatus = 1;
    }
    
    
    if (counterAutoCheckFlagStatus == 3) {
        _labelCGWarning.hidden = NO;
        _labelCGWarning.text = @"SAFETY MARGIN EXCEEDED\nWITH ALL PAX AFT";
        _labelCGWarning.backgroundColor = yellowSpecialColor;
        _labelCGWarning.textColor = [UIColor blackColor];
        
    }
    
    if (counterAutoCheckFlagStatus == 1) {
        _labelCGWarning.hidden = NO;
        _labelCGWarning.text = @"CG EXCEEDED\nWITH ALL PAX AFT";
        _labelCGWarning.backgroundColor = [UIColor redColor];
        _labelCGWarning.textColor = [UIColor whiteColor];
        
    }
    if (counterAutoCheckFlagStatus == 2) {
        _labelCGWarning.hidden = NO;
        _labelCGWarning.text = @"IN EXTENDED ENVELOPE\nWITH ALL PAX AFT";
        _labelCGWarning.backgroundColor = [UIColor orangeColor];
        _labelCGWarning.textColor = [UIColor blackColor];
        
    }
    
    /*
     if (_labelCGWarning.hidden == NO) {
     _labelCGWarning.alpha = 1;
     [UIView animateWithDuration:1.5 delay:0.5 options:UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse animations:^{
     _labelCGWarning.alpha = 0;
     } completion:nil];
     }
     */
    
    
    //NSLog(@"2 counterAutoCheckFlagStatus %d", counterAutoCheckFlagStatus);
    
    
    [self recallSeating];
    
    [self calculateListo];
}


- (IBAction)actionBringAllRecall:(id)sender {
    
    
    
    
    [self recallSeating];
    [self MainRoutine];
    
    
    
}


- (void) memorizeSeating {
    
    //NSLog(@"memorizeSeating");
    
    NSCountedSet *set = [[NSCountedSet alloc] initWithArray:_arrayName10];
    int numberOfSeats = (unsigned long)[set countForObject:@"seat"];
    //NSLog(@"fwd numberOfSeats %d", numberOfSeats);
    
    int configStationsStart = 0;
    
    
    configStationsStart = [[_arrayName23 objectAtIndex:11] intValue];
    int configStationsEnd = configStationsStart + numberOfSeats-2;
    tempArraySeatWgt = [[NSMutableArray alloc] init];
    tempArraySeatName = [[NSMutableArray alloc] init];
    
    totalSeatWeight = 0;
    
    for (int i = configStationsStart; i < configStationsEnd ; i++) {
        
        [tempArraySeatWgt  addObject: [_arrayName2 objectAtIndex:i] ];
        [tempArraySeatName addObject: [_arrayName7 objectAtIndex:i] ];
        
        totalSeatWeight = totalSeatWeight + [[_arrayName2 objectAtIndex:i] floatValue];
    }
    
    return;
}


- (void) recallSeating {
    
    flagRecallSeat = 0;
    
    //NSLog(@"recallSeating");
    
    if (tempArraySeatWgt.count < 1) {
        
        //NSLog(@"recallSeating return");
        return;
    }
    
    NSCountedSet *set = [[NSCountedSet alloc] initWithArray:_arrayName10];
    int numberOfSeats = (unsigned long)[set countForObject:@"seat"];
    //NSLog(@"fwd numberOfSeats %d", numberOfSeats);
    
    int configStationsStart = 0;
    int configStationsEnd = 0;
    configStationsStart = [[_arrayName23 objectAtIndex:11] intValue];
    configStationsEnd = configStationsStart + numberOfSeats-2;
    
    
    for (int i = configStationsStart; i < configStationsEnd ; i++) {
        
        NSString *replacementWeight = [tempArraySeatWgt objectAtIndex:i-configStationsStart];
        
        [_arrayName2 replaceObjectAtIndex:i  withObject:replacementWeight ];
        
        [_arrayName7 replaceObjectAtIndex:i  withObject:[tempArraySeatName objectAtIndex:i-configStationsStart] ];
        
        float momentLong = [replacementWeight floatValue] * [[_arrayName3 objectAtIndex:i] floatValue];
        [_arrayName4 replaceObjectAtIndex:i  withObject: [[NSString alloc] initWithFormat:@"%.0f", momentLong]  ];
        float momentLat = [replacementWeight floatValue] * [[_arrayName5 objectAtIndex:i] floatValue];
        [_arrayName6 replaceObjectAtIndex:i  withObject: [[NSString alloc] initWithFormat:@"%.0f", momentLat]  ];
    }
    
    return;
    
    
}

- (void) setPaxFWD {
    
    NSMutableArray *tempArraySeatWgtONLY = [[NSMutableArray alloc] init];
    NSMutableArray *tempArraySeatNameONLY = [[NSMutableArray alloc] init];
    for (int i = 0; i < tempArraySeatWgt.count ; i++) {
        if ([[tempArraySeatWgt objectAtIndex:i] floatValue] > 1) {
            [tempArraySeatWgtONLY  addObject: [tempArraySeatWgt objectAtIndex:i] ];
            [tempArraySeatNameONLY addObject: [tempArraySeatName objectAtIndex:i] ];
        }
    }
    //NSLog(@"tempArraySeatWgtONLY %@", tempArraySeatWgtONLY);
    //NSLog(@"tempArraySeatNameONLY %@", tempArraySeatNameONLY);
    
    NSCountedSet *set = [[NSCountedSet alloc] initWithArray:_arrayName10];
    int numberOfSeats = (unsigned long)[set countForObject:@"seat"];
    int configStationsStart = [[_arrayName23 objectAtIndex:11] intValue];
    int configStationsEnd = configStationsStart + numberOfSeats-2;
    
    
    int counterSeatAllocated =  0;
    
    for (int i = configStationsStart; i < configStationsEnd; i++) {
        
        if ([[_arrayName8 objectAtIndex:i]floatValue] == 0) {
            
            //NSLog(@"i is null this seat can not be used %d", i);
            continue;
        }
        
        
        
        
        NSString *replacementWeight;
        NSString *replacementName;
        
        if (counterSeatAllocated < tempArraySeatWgtONLY.count) {
            replacementWeight = [tempArraySeatWgtONLY objectAtIndex:counterSeatAllocated];
            replacementName   = [tempArraySeatNameONLY objectAtIndex:counterSeatAllocated];
        }else{
            replacementWeight = @"0";
            replacementName = @"-";
        }
        
        //NSLog(@"replacementWeight %@", replacementWeight);
        //NSLog(@"replacementWeight %@", replacementName);
        
        [_arrayName2 replaceObjectAtIndex:i  withObject:replacementWeight ];
        [_arrayName7 replaceObjectAtIndex:i  withObject:replacementName ];
        float momentLong = [replacementWeight floatValue] * [[_arrayName3 objectAtIndex:i] floatValue];
        [_arrayName4 replaceObjectAtIndex:i  withObject: [[NSString alloc] initWithFormat:@"%.0f", momentLong]  ];
        float momentLat = [replacementWeight floatValue] * [[_arrayName5 objectAtIndex:i] floatValue];
        [_arrayName6 replaceObjectAtIndex:i  withObject: [[NSString alloc] initWithFormat:@"%.0f", momentLat]  ];
        
        counterSeatAllocated = counterSeatAllocated + 1;
    }
    
    
    
}

- (void) setPaxAFT {
    
    NSMutableArray *tempArraySeatWgtONLY = [[NSMutableArray alloc] init];
    NSMutableArray *tempArraySeatNameONLY = [[NSMutableArray alloc] init];
    for (int i = 0; i < tempArraySeatWgt.count ; i++) {
        if ([[tempArraySeatWgt objectAtIndex:i] floatValue] > 1) {
            [tempArraySeatWgtONLY  addObject: [tempArraySeatWgt objectAtIndex:i] ];
            [tempArraySeatNameONLY addObject: [tempArraySeatName objectAtIndex:i] ];
        }
    }
    //NSLog(@"tempArraySeatWgtONLY %@", tempArraySeatWgtONLY);
    
    NSCountedSet *set = [[NSCountedSet alloc] initWithArray:_arrayName10];
    int numberOfSeats = (unsigned long)[set countForObject:@"seat"];
    
    int configStationsStart = 0;
    int configStationsEnd = 0;
    configStationsStart = [[_arrayName23 objectAtIndex:11] intValue];
    configStationsEnd = configStationsStart + numberOfSeats-3;
    //NSLog(@"tempArraySeatWgtONLY.count %d", tempArraySeatWgtONLY.count);
    
    int counterSeatAllocated =  0;
    
    
    for (int i = configStationsEnd; i >= configStationsStart; i--) {
        
        if ([[_arrayName8 objectAtIndex:i]floatValue] == 0) {
            
            //NSLog(@"i is null this seat can not be used %d", i);
            continue;
        }
        
        NSString *replacementWeight;
        NSString *replacementName;
        
        //NSLog(@"configStationsEnd-i %d", configStationsEnd-i);
        
        if (counterSeatAllocated < tempArraySeatWgtONLY.count) {
            replacementWeight = [tempArraySeatWgtONLY objectAtIndex:counterSeatAllocated];
            replacementName   = [tempArraySeatNameONLY objectAtIndex:counterSeatAllocated];
        }else{
            replacementWeight = @"0";
            replacementName = @"-";
        }
        
        //NSLog(@"replacementWeight %@", replacementWeight);
        //NSLog(@"replacementWeight %@", replacementName);
        
        [_arrayName2 replaceObjectAtIndex:i  withObject:replacementWeight ];
        [_arrayName7 replaceObjectAtIndex:i  withObject:replacementName ];
        float momentLong = [replacementWeight floatValue] * [[_arrayName3 objectAtIndex:i] floatValue];
        [_arrayName4 replaceObjectAtIndex:i  withObject: [[NSString alloc] initWithFormat:@"%.0f", momentLong]  ];
        float momentLat = [replacementWeight floatValue] * [[_arrayName5 objectAtIndex:i] floatValue];
        [_arrayName6 replaceObjectAtIndex:i  withObject: [[NSString alloc] initWithFormat:@"%.0f", momentLat]  ];
        
        counterSeatAllocated = counterSeatAllocated + 1;
        
    }
    
    
    
}


- (IBAction)closeKeyboardLegData:(id)sender {    
    
    [self.view endEditing:TRUE];
    [self MainRoutine];
}


- (IBAction)closeKeyboardFlightType:(id)sender {    
    
    [self.view endEditing:TRUE];
    [self MainRoutine];
    
    if ([_vFlightTypeField.text rangeOfString:@"("].location != NSNotFound  ) {
       //contains info for reserve fuel time       
        NSArray *componentItems = [[NSArray alloc] init];
        componentItems  = [_vFlightTypeField.text componentsSeparatedByString:@"("];        
        NSString *reserveTimeToUse = [componentItems objectAtIndex:1];
        _vReserveTimeField.text = [[NSString alloc] initWithFormat:@"%.0f", [reserveTimeToUse floatValue]];
        
   }
    [self MainRoutine];
}

- (IBAction)closeKeyboardFuelPreset:(id)sender {    
    
    [self.view endEditing:TRUE];
    [self MainRoutine];
    
    
}



- (IBAction)closeKeyboardManifest:(id)sender {
    
    [self.view endEditing:TRUE];
    
}


- (IBAction)moveDocPreparedView:(id)sender {  
    
}

- (IBAction)actionSaveValues:(id)sender {
    
    alertFlag = 5;
    
    UIAlertView *alert = [[UIAlertView alloc]
                          
                          initWithTitle:@"SETTINGS SAVED"
                          
                          message:@"Settings and values saved successfully. "
                          
                          delegate:self
                          
                          cancelButtonTitle: nil
                          
                          
                          
                          otherButtonTitles:@"OK", nil];
    
    [alert show];
    
    
    
}



- (IBAction)closeKeyboardPressureAlt:(id)sender {
    
    
    [self.view endEditing:TRUE];
    
        
    
    
    if ([inputPressureAlt doubleValue] > 20000) {
        inputPressureAlt   = [ [NSString alloc] initWithFormat:@"%.0f", 20000.0];
    } 
    
    if ([inputPressureAlt doubleValue] < -2000) {
        inputPressureAlt   = [ [NSString alloc] initWithFormat:@"%.0f", -2000.0];
    } 
    
      
    sliderHp.value = [inputPressureAlt doubleValue];
    
        
    [self MainRoutine];
    
}





- (IBAction)buttonActionEnterOAT:(id)sender {
    
    if (flagButtonPressed == 0) {
        
          [self setListoButtonsNeutral];
        
        enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;
        
        UIImage *buttonmark = [UIImage imageNamed:@"Klammern YelGlow.png"];
        
        [buttonOAT setImage:buttonmark forState:UIControlStateNormal];
        
         EnterPadString = @"0"; calculatorscreen.text = @"0"; EnterValueTwo = 0;
        
        selectedItem = 16;
        
       
        
    } else {[self setButtonMarksNeutral];}
    
}

- (IBAction)buttonActionEnterISA:(id)sender {
    
    if (flagButtonPressed == 0) {
        
        [self setListoButtonsNeutral];

        
        enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;
        
        UIImage *buttonmark = [UIImage imageNamed:@"Klammern YelGlow.png"];
        
        [buttonISA setImage:buttonmark forState:UIControlStateNormal];
        
         EnterPadString = @"0"; calculatorscreen.text = @"0"; EnterValueTwo = 0;
        
        selectedItem = 17;
        
        
    } else {[self setButtonMarksNeutral];}
    
}


- (IBAction)buttonActionEnterPressureAlt:(id)sender {
    
    if (flagButtonPressed == 0) {
        
        [self setListoButtonsNeutral];
        
        enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;
        
        UIImage *buttonmark = [UIImage imageNamed:@"Klammern YelGlow.png"];
        
        [buttonPressureAlt setImage:buttonmark forState:UIControlStateNormal];
        
        
        EnterPadString = @"0"; calculatorscreen.text = @"0"; EnterValueTwo = 0;
        
        selectedItem = 18;
        
        
        
    } else {[self setButtonMarksNeutral];}
    
}



- (IBAction)buttonActionEnterMSLfeet:(id)sender {
    
    
    
    if (flagButtonPressed == 0) {
        
         [self setListoButtonsNeutral];
        
        enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;
        
        UIImage *buttonmark = [UIImage imageNamed:@"Klammern_Yel.png"];
        
        [_buttonEnterMSLfeet setImage:buttonmark forState:UIControlStateNormal];
        
        EnterPadString = @"0"; calculatorscreen.text = @"0"; EnterValueTwo = 0;
        
        
        
        selectedItem = 21;
        
    } else {[self setButtonMarksNeutral];}
    
    
    
    
    
}


- (IBAction)buttonActionEnterQNH:(id)sender {
    
    
    
    if (flagButtonPressed == 0) {
        
        
        [self setListoButtonsNeutral];

        
        enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;
        
        UIImage *buttonmark = [UIImage imageNamed:@"Klammern_Yel.png"];
        
        [_buttonEnterQNH setImage:buttonmark forState:UIControlStateNormal];
        
        EnterPadString = @"0"; calculatorscreen.text = @"0"; EnterValueTwo = 0;
        
        
        selectedItem = 22;
        
    } else { [self setButtonMarksNeutral]; [self setListoButtonsNeutral];}
    
    
    
    
    
}


- (IBAction)slideractionQNH:(UISlider *)sender {
    
    labelQNH.text = [ [NSString alloc] initWithFormat:@"%.2f", sliderQNH.value];
    
    
    
    
    [self MainRoutine];
    
    
    
}



- (IBAction)actionSetISA:(id)sender {
    
    sliderQNH.value = 29.92;
    
    calcisa = 15 - (1.98 * (_sliderMSL.value/1000));
    
    sliderOATforOGE.value = calcisa;
    
    sliderISADiff.value = 0;
    
    OAT = sliderOATforOGE.value;
    
    float OATCelsius = OAT;
    
    //float fahrenheit = (OATCelsius * 1.8) + 32;
    
    [self MainRoutine];
    
}



- (void) setButtonMarksNeutral {
    
    //[self setListoButtonsNeutral];
    
    
    
    selectedItem = 0;
    
    
    enterPad.hidden = YES; flagButtonPressed = 0; EnterPadString = @""; calculatorscreen.text = @""; EnterValueTwo = 0;
    
    UIImage *buttonmark = [UIImage imageNamed:@"Klammern.png"];
    
    [_buttonEnterFlightTimeMinutes setImage:buttonmark forState:UIControlStateNormal];
    
    [_buttonEnterFuelLanding setImage:buttonmark forState:UIControlStateNormal];
    
    [_buttonEnterFuelMain setImage:buttonmark forState:UIControlStateNormal];
    
    [_buttonEnterFuelMainPercent setImage:buttonmark forState:UIControlStateNormal];
    
    [_buttonEnterFuelLandingPercent setImage:buttonmark forState:UIControlStateNormal];
    
    
    
    [buttonOAT setImage:buttonmark forState:UIControlStateNormal];
    [buttonISA setImage:buttonmark forState:UIControlStateNormal];
    
    
    [buttonPressureAlt setImage:buttonmark forState:UIControlStateNormal];
    [_buttonEnterMSLfeet setImage:buttonmark forState:UIControlStateNormal];
    [_buttonEnterQNH setImage:buttonmark forState:UIControlStateNormal];
    
    
    [self MainRoutine];
    
}



// conversion KG / lbs


- (IBAction)buttonActionKilogram:(id)sender {
    
    
  
}









// ENTER PAD -----------------------------------------------------------------



- (IBAction)padCancelButton:(id)sender {
    
    currentNumber = 0;
    
    calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
    
    
    
    [self MainRoutine];  
   
    
    
    
}

- (IBAction)buttonDigitPressed:(id)sender {
    
    if (EnterValueTwo == 0) {
        calculatorscreen.text = @"0"; EnterPadString = @"";
    }
    
    currentNumber = 0;
    currentNumber = (float) [sender tag];
    //NSLog (@"buttonDigitPressed currentNumber %@ ", [ [NSString alloc] initWithFormat:@"%.1f ", currentNumber]);
    
    NSString *currentnumber = [NSString stringWithFormat:@"%.0f", currentNumber];
    EnterPadString = [EnterPadString  stringByAppendingString: currentnumber];  // attach number to help string
    EnterValueTwo = [EnterPadString doubleValue];  // define Enter Value
    
    if (EnterValueTwo > 14000 && EnterValueTwo < 14000) {
        EnterValueTwo = 14000; }
    
    if (commapressedTwo == 0) {
        calculatorscreen.text = [ [NSString alloc] initWithFormat:@"%.0f", EnterValueTwo];
    } else {
        calculatorscreen.text = [ [NSString alloc] initWithFormat:@"%.2f", EnterValueTwo];
    }
}




- (IBAction)buttonComma:(id)sender {
    
    if ([calculatorscreen.text isEqualToString:@"-147"]) {        
        calculatorscreen.text = @"";        
        enterPad.hidden = YES;  [self setListoButtonsNeutral];        
        if (_switchAdjustACTopView.on == YES) {
            _switchAdjustACTopView.on = NO;
        }else{
          _switchAdjustACTopView.on = YES;
        }        
        [self MainRoutine];        
        return;
    }
    
    
    if ([calculatorscreen.text isEqualToString:@"-1203"]) {
        calculatorscreen.text = @"";        
        enterPad.hidden = YES;  [self setListoButtonsNeutral];        
        [[NSUserDefaults standardUserDefaults]  setObject:@"GyronimoFlightPadCategory5"        forKey:@"purchasedProductID"];   
        [self checkAvailableCategory];
        return;
    }
    
    commapressedTwo = 1;
    
    EnterPadString = [EnterPadString stringByAppendingString: @"."];
    
    
    
}

- (IBAction)buttonMinus:(id)sender {
    
    minuspressedTwo = 1;
    
    EnterValueTwo =  EnterValueTwo * -1;
    
    if (commapressedTwo == 0) {
        calculatorscreen.text = [ [NSString alloc] initWithFormat:@"%.0f", EnterValueTwo];
    } else {
        calculatorscreen.text = [ [NSString alloc] initWithFormat:@"%.2f", EnterValueTwo];
    }
    
}

- (IBAction)padEnterButton:(id)sender {
    
    
    flagButtonListoPressed = 0;
    //NSLog (@"ENTER selectedItem %@ ", [ [NSString alloc] initWithFormat:@"%.1f ", selectedItem]);
    
    
    if (selectedItem < 16 || selectedItem == 40) {
        [self actionENTERpadListo];
    }
    
    
    currentNumber = 0;
    if (selectedItem == 16) {
        
        if ([labelOATforOGE.text floatValue] > 40.0) {
            labelOATforOGE.text   = @"40";
        }
        
        if ([labelOATforOGE.text floatValue] < -40.0) {
            labelOATforOGE.text   = @"-40";
        }
        
        
        sliderOATforOGE.value = EnterValueTwo;
        
        labelOATforOGE.text = [ [NSString alloc] initWithFormat:@"%.0f", EnterValueTwo];
        
        
        
        //NSLog(@"EnterPadString %@", EnterPadString);
        
        [self setListoButtonsNeutral];
        
        calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
        
        if (enterpadAutoHide == 1) { enterPad.hidden = YES; }
        
        [self closeEnterPad];
        
    }
    
    
    
    if (selectedItem == 17) {
        
        if ([labelISAdiff.text floatValue] > 40.0) {
            labelISAdiff.text   = @"40";
        }
        
        if ([labelISAdiff.text floatValue] < -40.0) {
            labelISAdiff.text   = @"-40";
        }
        
        
        sliderISADiff.value = EnterValueTwo;
        
        labelISAdiff.text = [ [NSString alloc] initWithFormat:@"%.0f", EnterValueTwo];
        
        
        [self setListoButtonsNeutral];
        
        
        calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
        
        if (enterpadAutoHide == 1) { enterPad.hidden = YES; }
        
        [self closeEnterPad];
        
    } 
    
    
    if (selectedItem == 18) {
        
        if ([inputPressureAlt doubleValue] > 20000.0) {
            inputPressureAlt   = @"20000";
        } 
        
        if ([inputPressureAlt doubleValue] < -2000.0) {
            inputPressureAlt   = @"-2000";
        } 
        
        
        
        
        sliderHp.value = EnterValueTwo;
        
        inputPressureAlt = [ [NSString alloc] initWithFormat:@"%.0f", EnterValueTwo];
        
        
        [self setListoButtonsNeutral];
        
        calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
        
        if (enterpadAutoHide == 1) { enterPad.hidden = YES; }
        
        [self closeEnterPad];
        
    }
    
    
    if (selectedItem == 19) {
        
      
        
        calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
        
        if (enterpadAutoHide == 1) { enterPad.hidden = YES; }
        
        [self closeEnterPad];
        
    }
    
    
    if (selectedItem == 21) { // msl
        
        _sliderMSL.value = EnterValueTwo;
        
        
        
        
        calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
        
        if (enterpadAutoHide == 1) { enterPad.hidden = YES; }
        
        [self closeEnterPad];
        
    }
    
    
    
    if (selectedItem == 22) {
        
         
            
         if ( [unitsAltimeter isEqualToString:@"US"]) {              
             sliderQNH.value =  [EnterPadString floatValue];
         }else{
             sliderQNH.value =  [EnterPadString floatValue] / 33.86530749;  // use this if input is in Millibar!!!             
         }
        
        calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
        
        if (enterpadAutoHide == 1) { enterPad.hidden = YES; }
        
        [self closeEnterPad];
        
    }


    
    
    if (selectedItem == 25) {
        
        // arie 2
   
        
        if ([fuelEnterMode isEqualToString:@"mass"]) {
            
            float enterValue = [EnterPadString floatValue] / factorApplyToNativeFuelWeight;
            
            
            if (enterValue > tankCapacityVolume * [_inputSpecificFuelMassPerVolume.text floatValue] ) {
                enterValue = tankCapacityVolume * [_inputSpecificFuelMassPerVolume.text floatValue];
            }
            
             _sliderFuelMain1.value =  enterValue / [_inputSpecificFuelMassPerVolume.text floatValue];
            
            if ([[_arrayName25 objectAtIndex:21] isEqualToString:@"yes"]) {
                _sliderFuelMain1.value =  (enterValue / [_inputSpecificFuelMassPerVolume.text floatValue]) + supplyFuelVolume;
            };
            
          
            
            if (_sliderFuelLanding.value >= _sliderFuelMain1.value ) {
                _sliderFuelLanding.value = _sliderFuelMain1.value - (_sliderFuelMain1.value * 0.05);
            }
            
        }else{
            
            float enterValue = [EnterPadString floatValue] / factorApplyToNativeFuelVolumeGalLiter;
            
            if (enterValue > tankCapacityVolume) {
                enterValue = tankCapacityVolume;
            }
            
             _sliderFuelMain1.value =  enterValue;
            
            if ([[_arrayName25 objectAtIndex:21] isEqualToString:@"yes"]) {
                _sliderFuelMain1.value =  enterValue  + supplyFuelVolume;
            };
            
            if (_sliderFuelLanding.value >= _sliderFuelMain1.value ) {
                _sliderFuelLanding.value = _sliderFuelMain1.value - (_sliderFuelMain1.value * 0.05);
            }
            
        }
        
        calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
        
        if (enterpadAutoHide == 1) { enterPad.hidden = YES; }
        
        [self closeEnterPad];
        
    }
    
    
    
    if (selectedItem == 26) {
        
        
        
        if ([fuelEnterMode isEqualToString:@"mass"]) {
            
            float enterValue = [EnterPadString floatValue] / factorApplyToNativeFuelWeight;
            
            if (enterValue > tankCapacityVolume * [_inputSpecificFuelMassPerVolume.text floatValue] ) {
                enterValue = tankCapacityVolume * [_inputSpecificFuelMassPerVolume.text floatValue];
            }
            
            if (enterValue > _sliderFuelMain1.value * [_inputSpecificFuelMassPerVolume.text floatValue]) {
                enterValue = (_sliderFuelMain1.value * [_inputSpecificFuelMassPerVolume.text floatValue]) - 30;
            }
            
            _sliderFuelLanding.value =  enterValue / [_inputSpecificFuelMassPerVolume.text floatValue];
            
            if ([[_arrayName25 objectAtIndex:21] isEqualToString:@"yes"]) {
                _sliderFuelLanding.value =  (enterValue / [_inputSpecificFuelMassPerVolume.text floatValue]) + supplyFuelVolume;
            };
            
            if (_sliderFuelLanding.value >= _sliderFuelMain1.value ) {
                _sliderFuelLanding.value = _sliderFuelMain1.value - (_sliderFuelMain1.value * 0.05);
            }
            
        }else{
            
            float enterValue = [EnterPadString floatValue] / factorApplyToNativeFuelVolumeGalLiter;
            
            if (enterValue > tankCapacityVolume) {
                enterValue = tankCapacityVolume;
            }
            
            
            if (enterValue > _sliderFuelMain1.value ) {
                enterValue = _sliderFuelMain1.value  - 30;
            }
            
            _sliderFuelLanding.value =  enterValue;
            
            if ([[_arrayName25 objectAtIndex:21] isEqualToString:@"yes"]) {
                _sliderFuelLanding.value =  enterValue  + supplyFuelVolume;
            };
            
            
            if (_sliderFuelLanding.value >= _sliderFuelMain1.value ) {
                _sliderFuelLanding.value = _sliderFuelMain1.value - (_sliderFuelMain1.value * 0.05);
            }
            
        }
       
        
        
        
        calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
        
        if (enterpadAutoHide == 1) { enterPad.hidden = YES; }
        
        [self closeEnterPad];
        
    }
    
    
    
    if (selectedItem == 27) {
        
        float enterValue = [EnterPadString floatValue];
        
        if (enterValue > 100) {
            enterValue = 100;
        }
        
        _sliderFuelMain1.value =  enterValue * (tankCapacityVolume/100.0);        
        
        calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
        
        if (enterpadAutoHide == 1) { enterPad.hidden = YES; }
        
        [self closeEnterPad];
        
    }
    
    
    
    if (selectedItem == 28) {
        
        float enterValue = [EnterPadString floatValue];
        
        if (enterValue > 100) {
            enterValue = 100;
        }
        
        _sliderFuelLanding.value =  enterValue * (tankCapacityVolume/100.0);
        
        
        
        calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
        
        if (enterpadAutoHide == 1) { enterPad.hidden = YES; }
        
        [self closeEnterPad];
        
    }
    
    
    
    
    
    if (selectedItem == 29) {
        
        _labelFlightTimeMinutes.text = [ [NSString alloc] initWithFormat:@"%.0f", EnterValueTwo ];
        
        calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
        
        if (enterpadAutoHide == 1) { enterPad.hidden = YES; }
        
        [self closeEnterPad];
        
    }

    
    if (selectedItem == 30) {
        
        _inputPaxOnBoard.text = [ [NSString alloc] initWithFormat:@"%.0f", EnterValueTwo ];
        
        calculatorscreen.text = @"0"; EnterPadString = @""; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
        
        if (enterpadAutoHide == 1) { enterPad.hidden = YES; }
        
      
        
        
        
        [self setPaxOnBoard];
        
        [self closeEnterPad];
        
        [self memorizeSeating]; flagRecallSeat = 0;
        
        [self MainRoutine];
        
    }

    
    
    
    
    
 // end enter pad



    
    
}


- (void) closeEnterPad {
    
    
    [self setListoButtonsNeutral];
    
    
    enterPad.hidden = YES; flagButtonPressed = 0;
    
    UIImage *buttonmark = [UIImage imageNamed:@"Klammern.png"];
    
    
    [_buttonEnterFlightTimeMinutes setImage:buttonmark forState:UIControlStateNormal];
    
    [_buttonEnterFuelLanding setImage:buttonmark forState:UIControlStateNormal];
    
    [_buttonEnterFuelMain setImage:buttonmark forState:UIControlStateNormal];
    
    [_buttonEnterFuelMainPercent setImage:buttonmark forState:UIControlStateNormal];
    
    [_buttonEnterFuelLandingPercent setImage:buttonmark forState:UIControlStateNormal];
    
    
    [buttonOAT setImage:buttonmark forState:UIControlStateNormal];
    [buttonISA setImage:buttonmark forState:UIControlStateNormal];
    
    
    [buttonPressureAlt setImage:buttonmark forState:UIControlStateNormal];
    [_buttonEnterMSLfeet setImage:buttonmark forState:UIControlStateNormal];
    [_buttonEnterQNH setImage:buttonmark forState:UIControlStateNormal];
    
    [self MainRoutine];
    [self MainRoutine];
    
    
}










// email **** ****  email **** ****  email **** ****  email **** ****  email **** ****  


// check for problems with email



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




// this is THE NEW method - create signature, capture scoll view and attach to email


- (IBAction)actionSendSummary:(id)sender {
    
     [self sendSummaryViaEmail];
}

- (IBAction)actionSendManifest:(id)sender {
    
    //NSLog(@"statusSignature %.0f ", statusSignature);
    //NSLog(@"ScrollViewManifest.subviews.count  %d ", ScrollViewManifest.subviews.count);
    [self sendManifestViaEmail];
}


- (void) createTimeStamp {
    
    
    // Get current  time
    
    NSDate *currentDateTime = [NSDate date];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    
    NSTimeZone *localTZ = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTZ];
    
    NSString *localTime = [dateFormatter stringFromDate:currentDateTime];
    
    
    [dateFormatter setDateFormat:@"MM"];    NSString *dateMonth = [dateFormatter stringFromDate:currentDateTime];
    [dateFormatter setDateFormat:@"dd"];    NSString *dateDay = [dateFormatter stringFromDate:currentDateTime];
    [dateFormatter setDateFormat:@"yyyy"];  NSString *dateYear = [dateFormatter stringFromDate:currentDateTime];
    
    if ( [[_arrayName23 objectAtIndex:5] isEqualToString:@"US"]) {
        
        // US
        _manifestTimeStamp.text = [NSString stringWithFormat:@"Print time & date: %@ / %@.%@.%@",  localTime, dateMonth, dateDay, dateYear];        
        _mani_IntegrityCariedOutOn.text = [NSString stringWithFormat:@"%@.%@.%@ at %@",  dateMonth, dateDay, dateYear, localTime];        
        _inputDocumentPreparedDate.text = [NSString stringWithFormat:@"%@-%@-%@",  dateMonth, dateDay, dateYear];        
        _inputDocumentPreparedTime.text = [NSString stringWithFormat:@"%@",  localTime];        
        timeStampForPDF = [NSString stringWithFormat:@"%@-%@-%@_%@",   dateMonth, dateDay, dateYear, localTime];
        
    }else{        
        
        // EU        
        _manifestTimeStamp.text = [NSString stringWithFormat:@"%@/%@.%@",  vFlightRegistration.text, dateDay, dateMonth];        
        _mani_IntegrityCariedOutOn.text = [NSString stringWithFormat:@"%@.%@.%@ at %@",  dateDay, dateMonth, dateYear, localTime];        
        _inputDocumentPreparedDate.text = [NSString stringWithFormat:@"%@.%@.%@",  dateDay, dateMonth, dateYear];        
        _inputDocumentPreparedTime.text = [NSString stringWithFormat:@"%@",  localTime];        
        timeStampForPDF = [NSString stringWithFormat:@"%@.%@.%@_%@",   dateDay, dateMonth, dateYear, localTime];

        
    }
    
    
}


- (void) createDateSummary {
    
    
    
    
    
    // Get current  time
    
    NSDate *currentDateTime = [NSDate date];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    
    NSTimeZone *localTZ = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTZ];
    
  
    
    
    
    [dateFormatter setDateFormat:@"MM"];    NSString *dateMonth = [dateFormatter stringFromDate:currentDateTime];
    [dateFormatter setDateFormat:@"dd"];    NSString *dateDay = [dateFormatter stringFromDate:currentDateTime];
    [dateFormatter setDateFormat:@"yyyy"];  NSString *dateYear = [dateFormatter stringFromDate:currentDateTime];
    
    if ([[_arrayName23 objectAtIndex:5] isEqualToString:@"US"]) {              
        // get date format US        
        summaryDateStamp = [NSString stringWithFormat:@"%@-%@-%@",  dateMonth, dateDay, dateYear];
    }else{
        
        summaryDateStamp = [NSString stringWithFormat:@"%@.%@.%@",  dateDay, dateMonth, dateYear];
        
    }
    
    
    
    
}



- (void) sendSummaryViaEmail {
    
    
    _viewSummaryLowerButtons.hidden = YES;
    
    
    int pixelWidth = _scrollViewSummaryManifest.contentSize.width;
    int pixelHeight = summaryBoxHeight +290;  // set hight of pdf page here (cut off the bottom)
    
    pdfData = [NSMutableData data];
    
    UIGraphicsBeginPDFContextToData( pdfData, CGRectMake(0, 0, pixelWidth, pixelHeight),  nil );
    UIGraphicsBeginPDFPage();
    CGPoint savedContentOffset = _scrollViewSummaryManifest.contentOffset;
    CGRect savedFrame = _scrollViewSummaryManifest.frame;
    
    _scrollViewSummaryManifest.contentOffset = CGPointZero;
    _scrollViewSummaryManifest.frame = CGRectMake(0, 0, pixelWidth, pixelHeight);
    
    [_scrollViewSummaryManifest.layer renderInContext: UIGraphicsGetCurrentContext()];
    
    _scrollViewSummaryManifest.contentOffset = savedContentOffset;
    _scrollViewSummaryManifest.frame = savedFrame;
    
    UIGraphicsEndPDFContext();
    
    
    MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
    
    [composer setMailComposeDelegate: self];
    NSString *MailSubject     = [NSString stringWithFormat:@"Flight Summary %@,   ", vFlightRegistration.text ];
    
    [composer setToRecipients:[NSArray arrayWithObjects: _defaultEmailAddress.text , nil]];
    [composer setCcRecipients:[NSArray arrayWithObjects: _defaultEmailAddressCC.text , nil]];
    
    [composer setSubject: MailSubject];
    [composer setMessageBody:@"Flight Summary attached as PDF document"  isHTML:NO];
    [composer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    
    [composer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:[NSString stringWithFormat:@"Summary_%@.pdf",  vFlightRegistration.text]];
    
    //[composer addAttachmentData:pdfData2 mimeType:@"application/pdf" fileName:[NSString stringWithFormat:@"Med. Equip. List.pdf"]];
    
    [self presentModalViewController:composer animated:YES];
    
    _viewSummaryLowerButtons.hidden = NO;
    
}




- (void) sendManifestViaEmail {
    
    _viewLowerButtons.hidden = YES;
    
    //NSLog(@"ScrollViewManifest.contentSize.width %f", ScrollViewManifest.contentSize.width);
    //NSLog(@"ScrollViewManifest.contentSize.height %f", ScrollViewManifest.contentSize.height);
    

    _manifestPageNumber.text = @"";
    _viewEquipmentListOverManifest.hidden = YES;
   
    NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"];
    if (dedicatedCustomerData.length < 2) {
        dedicatedCustomerData = @"";
    }
    if ([dedicatedCustomerData rangeOfString:@"createExtraEquipmentPage"].location != NSNotFound  ) {     
        if (equipmentItemsOnBoard > 0) {
            _manifestPageNumber.text = @"Page 1/2";
        }
    }


    int pixelWidth = ScrollViewManifest.contentSize.width*1.6;
    int pixelHeight = ScrollViewManifest.contentSize.height*0.8;  // set height of pdf page here (cut off the bottom)
   
    pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData( pdfData, CGRectMake(0, 0, pixelWidth, pixelHeight),  nil );
    UIGraphicsBeginPDFPage();
    CGPoint savedContentOffset = ScrollViewManifest.contentOffset;
    CGRect savedFrame = ScrollViewManifest.frame;    
    ScrollViewManifest.contentOffset = CGPointZero;
    ScrollViewManifest.frame = CGRectMake(0, 0, pixelWidth, pixelHeight);    
    [ScrollViewManifest.layer renderInContext: UIGraphicsGetCurrentContext()];    
    ScrollViewManifest.contentOffset = savedContentOffset;
    ScrollViewManifest.frame = savedFrame;
    
   
    
    if ([dedicatedCustomerData rangeOfString:@"createExtraEquipmentPage"].location != NSNotFound  ) {
        if (equipmentItemsOnBoard > 0) {
            _manifestPageNumber.text = @"Page 2/2";
            [self createSpecialEquipListItemsForManifest];                
            _viewEquipmentListOverManifest.hidden = NO;
            [ScrollViewManifest bringSubviewToFront:_viewEquipmentListOverManifest];        
            UIGraphicsBeginPDFPage();
            ScrollViewManifest.contentOffset = CGPointZero;
            ScrollViewManifest.frame = CGRectMake(0, 0, pixelWidth, pixelHeight);    
            [ScrollViewManifest.layer renderInContext: UIGraphicsGetCurrentContext()];    
            ScrollViewManifest.contentOffset = savedContentOffset;
            ScrollViewManifest.frame = savedFrame; 
        }
              
    }
    
	UIGraphicsEndPDFContext();    
    
    _viewEquipmentListOverManifest.hidden = YES;
    
    MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
    
    [composer setMailComposeDelegate: self];
    NSString *MailSubject;    
    
    if (![_labelDepartureTimeLocal.text isEqualToString:@""] ) {
        MailSubject     = [NSString stringWithFormat:@"Load Manifest %@ %@ %@ %@.pdf",  AC_Type, vFlightRegistration.text,  vFlightDeparture.text, _labelDepartureTimeLocal.text];
    }else{
        MailSubject     = [NSString stringWithFormat:@"Load Manifest %@, %@   ", AC_Type  , _manifestTimeStamp.text ];        
    }
    
    [composer setToRecipients:[NSArray arrayWithObjects: _defaultEmailAddress.text , nil]];
    [composer setCcRecipients:[NSArray arrayWithObjects: _defaultEmailAddressCC.text , nil]];    
    [composer setSubject: MailSubject];
    [composer setMessageBody:@"Load Manifest attached as PDF document"  isHTML:NO];
    [composer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    
    if (![_labelDepartureTimeLocal.text isEqualToString:@""] ) {
         [composer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:[NSString stringWithFormat:@"Load Manifest %@ %@ %@ %@.pdf",  AC_Type, vFlightRegistration.text,  vFlightDeparture.text, _labelDepartureTimeLocal.text]];
    }else{
         [composer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:[NSString stringWithFormat:@"Load Manifest %@.pdf",  _manifestTimeStamp.text]];        
    }    
      
    
    [self presentModalViewController:composer animated:YES];    
    _viewLowerButtons.hidden = NO;
   
}

- (IBAction)actionSaveUpdateACdata:(id)sender{
    
    _buttonSaveUpdateACdata.hidden = YES;
    _viewSelectHelicopter.hidden = YES;
    //NSLog (@"actionSaveUpdateACdata");
    
    [self saveUpdateACdata];
    
    [self SaveValues];
    [self LoadValues];
    [self MainRoutine];
    
    _viewLegData.hidden = NO;

}


- (IBAction)actionCreateNewPHIFlight:(id)sender {
    
    
    
    if (_inputPHIOverrideACtype.text.length < 1|| _inputPHIOverrideRegistration.text.length < 1|| _inputPHIOverrideBEW.text.length < 1 || _inputPHIOverrideMoment.text.length < 1 || _inputPHIOverrideMomentLat.text.length < 1||  _dropDownAvailablePHIEquipListsOverride.text.length < 1  || _inputPHIOverrideBase.text.length < 1 || _inputPHIOverrideFuelFlow.text.length < 1 || _inputPHIOverrideSledWeight.text.length < 1) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Please Enter All Required Data."
                                                                                 message:nil
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil];   
        return;
        
    } 
    
    vFlightRegistration.text = _inputPHIOverrideRegistration.text;  
    displayHeliRegistration.text = _inputPHIOverrideRegistration.text;
    AC_Type = _inputPHIOverrideACtype.text;
    
    inputFuelFlowOverride.text = _inputPHIOverrideFuelFlow.text;           
    
    
    
    int ACnumber = 0;
    int foundAC = 0;
    for (int i = 0; i < arrayDictAllAircraft.count  ; i++) {               
        if ([[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Callsign"] isEqualToString:vFlightRegistration.text] && [ [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"]isEqualToString:AC_Type]) {  
            foundAC = 1;
            break;
        }
        ACnumber = ACnumber +1;
    }
    
    if (foundAC == 1) { 
        
        //NSLog(@"no need to create a new one");
        
        [self.view endEditing:TRUE];
        [self stuffToDoInButtSelHeli: buttonIDbuttSel]; 
        [_arrayName21 replaceObjectAtIndex:27 withObject:_inputPHIOverrideFuelFlow.text];
        
    }else{
        
        //NSLog(@"creating a new one");
        
        NSString *setManu = @"Bell";
        NSString *setCat = @"Heli";
        NSString *setSpecial3 = @"Heli, Bell, B407i";
        
        if ([_inputPHIOverrideACtype.text isEqualToString:@"B407i"]) {
            setManu =@"Bell";
            setSpecial3 = @"Heli, Bell, B407i";
        }
        if ([_inputPHIOverrideACtype.text isEqualToString:@"AS350B3"] ) {
            setManu =@"Airbus";
            setSpecial3 = @"Heli, Airbus, AS350B3";
        }
        if ([_inputPHIOverrideACtype.text isEqualToString:@"AS350B3e"]) {
            setManu =@"Airbus";
            setSpecial3 = @"Heli, Airbus, AS350B3e";
        }
        
        AC_Type = _inputPHIOverrideACtype.text; 
        ACCategory = setCat;
        ACmanufacturer = setManu;
        ACVariant = @"NONE";
        
        NSMutableDictionary *myACsDictionary = [[NSMutableDictionary alloc] init];
        myACsDictionary[@"Callsign"] = _inputPHIOverrideRegistration.text; 
        myACsDictionary[@"fleetAC_Type"] = _inputPHIOverrideACtype.text;
        myACsDictionary[@"Variant"] = @"NONE";
        myACsDictionary[@"Manufacturer"] = setManu;
        myACsDictionary[@"downloadStatus"] = @"";
        myACsDictionary[@"fleetACCategory"] = setCat;
        myACsDictionary[@"loadedCustomFiles"] = @"configurations+availableCharts+logoManifestFIXED+CGenvelope+FuelInterpolation";      
        myACsDictionary[@"Units"] = @"lbs";
        myACsDictionary[@"BEW"] = _inputPHIOverrideBEW.text;
        myACsDictionary[@"MomLong"] = _inputPHIOverrideMoment.text;
        myACsDictionary[@"MomLat"] = _inputPHIOverrideMomentLat.text;
        myACsDictionary[@"SelectedUnits"] = @"lbs"; 
        myACsDictionary[@"backendID"] = @"";        
        myACsDictionary[@"ACdataSource"] = @"FleetControl";
        myACsDictionary[@"specialdata1"] = @""; 
        myACsDictionary[@"specialdata2"] = @"";
        myACsDictionary[@"specialdata3"] = @"Heli, Bell, B407i";  
        myACsDictionary[@"dateOfWeighing"] = @"";; 
        myACsDictionary[@"weighingRemarks"] = @"";
        myACsDictionary[@"sledWeight"] = _inputPHIOverrideSledWeight.text;
        
        [arrayDictAllAircraft addObject:myACsDictionary];
        [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft forKey:@"arrayDictAllAircraft"];
        
        [self.view endEditing:TRUE];      
        [self stuffToDoInButtSelHeli: buttonIDbuttSel];  
        
         
        
        [self SaveValues];
       
      
        //NSLog(@"result arrayDictAllAircraft %@", arrayDictAllAircraft);
                
    }
    
}

- (IBAction)actionACtypeWasEntered:(id)sender {
    _viewSelectACWindow.hidden = NO;
    _dropDownAvailablePHIEquipLists.text = @"";
    _dropDownAvailablePHIEquipListsOverride.text = @"";
    AC_Type = _inputPHIOverrideACtype.text;
    [self loadWebcall];
    [self addHelicopterButtons];
    equipWarningMessage = @"";
    [_viewSelectHelicopter bringSubviewToFront:_viewSelectACWindow];
    
}

- (IBAction)buttonActionUnlockBEWOverride:(id)sender {
    
    UIImage *btnImg = [UIImage imageNamed:@"lock - UNlocked-01.png"];
    [_buttonUnlockBEWOverride setBackgroundImage:btnImg forState:UIControlStateNormal];
   
    _inputPHIOverrideRegistration.enabled = YES; _inputPHIOverrideRegistration.backgroundColor = [UIColor whiteColor];
    _inputPHIOverrideBEW.enabled = YES; _inputPHIOverrideBEW.backgroundColor = [UIColor whiteColor];
    _inputPHIOverrideMoment.enabled = YES; _inputPHIOverrideMoment.backgroundColor = [UIColor whiteColor];
    _inputPHIOverrideFuelFlow.enabled = YES; _inputPHIOverrideFuelFlow.backgroundColor = [UIColor whiteColor];
    _inputPHIOverrideMomentLat.enabled = YES; _inputPHIOverrideMomentLat.backgroundColor = [UIColor whiteColor];
    _inputPHIOverrideSledWeight.enabled = YES; _inputPHIOverrideSledWeight.backgroundColor = [UIColor whiteColor];
    _buttonPHIchangeBackToOriginalFormC.hidden = NO;
    
    
}



- (void) saveUpdateACdata {
    
    
    //NSLog(@"saveUpdateACdata arrayDictAllAircraft %@", arrayDictAllAircraft);    
    //NSLog(@"AC_Type %@", AC_Type);    
    //NSLog(@"vFlightRegistration.text %@", vFlightRegistration.text);
        
    int ACnumber = 0; 
    int foundAC = 0;
    for (int i = 0; i < arrayDictAllAircraft.count  ; i++) {               
        if ([[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Callsign"] isEqualToString:vFlightRegistration.text] && [ [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"]isEqualToString:AC_Type]) {  
            foundAC = 1;
            break;
        }
        ACnumber = ACnumber +1;
    }
    
    if (foundAC == 1) {
        //NSLog(@"ACnumber %d", ACnumber);        
        NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
        NSDictionary *oldDict = (NSDictionary *)[arrayDictAllAircraft objectAtIndex:ACnumber];
        [newDict addEntriesFromDictionary:oldDict];         
        [newDict setObject:_inputPHIOverrideRegistration.text forKey:@"Callsign"];        
        [arrayDictAllAircraft replaceObjectAtIndex:ACnumber withObject:newDict];         
        [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft forKey:@"arrayDictAllAircraft"];        
        vFlightRegistration.text = _inputPHIOverrideRegistration.text;  
        displayHeliRegistration.text = _inputPHIOverrideRegistration.text;
    }else {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"ERROR - Aircraft Data Not Available"
                                                                                 message:nil
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
    
  
    
}



- (void) searchbutSelHeli {
    
    previousACType = AC_Type;    
    float ACnumber = 0;  
    int flagHeliFound = 0;    
    arrayDictAllAircraft = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"] mutableCopy];
    
   //NSLog (@"searchbutSelHeli arrayDictAllAircraftk %@", arrayDictAllAircraft);
        
    if (arrayDictAllAircraft.count > 0) {
        //NSLog (@"1 searchbutSelHeli %@", vFlightRegistration.text);
        for (int i = 0; i < arrayDictAllAircraft.count  ; i++) {               
            if ([[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Callsign"] isEqualToString:vFlightRegistration.text] && [ [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"]isEqualToString:AC_Type]) {
                flagHeliFound = 1;
                break;
            }
            ACnumber = ACnumber +1;
        }
        if (flagHeliFound == 0) {
             [self checkAvailableCategory];
            return;
        }                 
        ACCategory = [[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"fleetACCategory"];
        ACmanufacturer = [[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"Manufacturer"];
        AC_Type = [[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"fleetAC_Type"];
        ACVariant = [[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"Variant"];
        specialdata2 = [[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"specialdata2"];
        
        trialCheck = [[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"isATrial"];
        //NSLog (@"searchButsel AC_Type %@", AC_Type);
        
        [[NSUserDefaults standardUserDefaults]  setObject:ACCategory        forKey:@"ACCategory"];
        [[NSUserDefaults standardUserDefaults]  setObject:ACmanufacturer    forKey:@"ACmanufacturer"];
        [[NSUserDefaults standardUserDefaults]  setObject:AC_Type           forKey:@"AC_Type"];
        [[NSUserDefaults standardUserDefaults]  setObject:ACVariant         forKey:@"ACVariant"];
        
        loadedBEWUnits = [[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"Units"];
        // replace BEW  
        NSString *checkSelectedUnits =  [[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"SelectedUnits"]; 
        
        //forceUnitLBS
        if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"forceUnitLBS"].location != NSNotFound) {        
            // we have kg in fleet control and we need lbs            
            bew =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"BEW"] doubleValue] / 2.2046;
            momlong =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLong"] doubleValue] / 0.086795276 ;
            momlat =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLat"] doubleValue] / 0.086795276;            
        }else if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"forceUnitKG"].location != NSNotFound ) {         
            bew =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"BEW"] doubleValue] * 2.2046;
            momlong =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLong"] doubleValue] * 0.086795276 ;
            momlat =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLat"] doubleValue] * 0.086795276;
        }else{
            
            if ([checkSelectedUnits isEqualToString:loadedBEWUnits]) {                 
                bew =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"BEW"] doubleValue];
                momlong =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLong"] doubleValue];
                momlat =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLat"] doubleValue];
            }else if ([checkSelectedUnits isEqualToString:@"lbs"] && [loadedBEWUnits isEqualToString:@"kg"]) { 
                bew =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"BEW"] doubleValue] / 2.2046;                
                if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
                //NSLog(@"1 butsearch this is meter!");
                momlong =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLong"] doubleValue] / 0.086795276 /1000;
                momlat =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLat"] doubleValue] / 0.086795276 /1000;
                }else{
                  momlong =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLong"] doubleValue] / 0.086795276 ;
                  momlat =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLat"] doubleValue] / 0.086795276;
                }                
            }else if ([checkSelectedUnits isEqualToString:@"kg"] && [loadedBEWUnits isEqualToString:@"lbs"]) { 
                bew =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"BEW"] doubleValue] * 2.2046;                 
                if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
                     //NSLog(@"2 butsearch this is meter!");
                     momlong =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLong"] doubleValue] * 0.086795276 * 1000;
                     momlat =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLat"] doubleValue] * 0.086795276 * 1000;
                }else{
                    momlong =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLong"] doubleValue] * 0.086795276 ;
                    momlat =  [[[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"MomLat"] doubleValue] * 0.086795276;                    
                }
            }
        }
        
        armlong = momlong / bew;
        armlat = momlat   / bew;   
        
        
        NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"];
        if (dedicatedCustomerData.length < 2) {
            dedicatedCustomerData = @"";
        }        
        if ([dedicatedCustomerData rangeOfString:@"enableBEWoverride"].location != NSNotFound  ) {  
                        
       
            //NSLog(@"arrayDictAllAircraft %@", arrayDictAllAircraft);
            
            if (flagSpecialPHIFlightSettingPage == 1) {
                bew = [_inputPHIOverrideBEW.text floatValue];
                momlong = [_inputPHIOverrideMoment.text floatValue];
                momlat = [_inputPHIOverrideMomentLat.text floatValue];
                vFlightRegistration.text = _inputPHIOverrideRegistration.text;
                armlong = momlong / bew;
                armlat = momlat   / bew;             
            }else{
                bew = [_inputOverrideBEW.text floatValue];
                momlong = [_inputOverrideMoment.text floatValue];
                momlat = [_inputOverrideMomentLat.text floatValue];
                vFlightRegistration.text = _inputOverrideRegistration.text;
                armlong = momlong / bew;
                armlat = momlat   / bew; 
                
            }
           

        }
        
        vBEW.text = [NSString stringWithFormat:@"%.2f",bew  ];
        vBEWMom.text = [NSString stringWithFormat:@"%.2f",momlong ];
        vBEWMomLat.text = [NSString stringWithFormat:@"%.2f",momlat ];
        lBEWArm.text = [NSString stringWithFormat:@"%.4f",armlong ];
        lBEWArmLat.text = [NSString stringWithFormat:@"%.4f",armlat];
        
        
        [_arrayName2 replaceObjectAtIndex:3 withObject:vBEW.text];
        [_arrayName3 replaceObjectAtIndex:3 withObject:lBEWArm.text];
        [_arrayName4 replaceObjectAtIndex:3 withObject:vBEWMom.text];
        [_arrayName5 replaceObjectAtIndex:3 withObject:lBEWArmLat.text];
        [_arrayName6 replaceObjectAtIndex:3 withObject:vBEWMomLat.text];
        
        priceCategoryOfSelectedAircraft = [[arrayDictAllAircraft objectAtIndex:ACnumber] objectForKey:@"priceCategory"];
       
        
        [self checkAvailableCategory];
        
        
    }
    
    return;
}


- (void) checkAvailableCategory {
    
    //NSLog(@"checkAvailableCategory ");       
    NSString *availableCategory = [[NSUserDefaults standardUserDefaults]  stringForKey:@"purchasedProductID"]; 
    //NSLog(@"availableCategory %@", availableCategory);
    
    if (availableCategory.length < 1) {
        availableCategory = @"0";
    }else{            
        availableCategory = [availableCategory substringFromIndex: [availableCategory length] - 1]; 
    }
     
    _viewLockPerformance.hidden = YES;   
    
    NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];    
    if ([customerFolderName isEqualToString:@"noAccount"] ) {             
        if ([priceCategoryOfSelectedAircraft floatValue] > [availableCategory floatValue]) {
            
            //NSLog(@"you do not have this! ");
            _viewLockManifest.hidden = NO;   
            _labelLockTextOnManifest.text = @"Please purchase the category for the desired aircraft. (>Setup page > Manage Aircraft)";
            _viewLockPerformance.hidden = NO;
            [viewEnvironment bringSubviewToFront: _viewLockPerformance];
        }else{
            //NSLog(@"yes you have this! ");                 
            _viewLockManifest.hidden = YES;                
        }            
    }else{
        //NSLog(@"do not lock");
        _viewLockManifest.hidden = YES; 
      
    }        
    if ([customerFolderName isEqualToString:@"Test User"]  || [customerFolderName isEqualToString:@"Tester"]) {
        _viewLockManifest.hidden = NO;   
        _labelLockTextOnManifest.text = @"To purchase a custom version, please contact us via email: info@gyronimo.com"; 
       
    }
    
    
   if ([trialCheck isEqualToString:@"isATrial"] ) {           
       _viewLockManifest.hidden = NO;  
       _labelLockTextOnManifest.text = @"Please purchase the category for the desired aircraft. (>Setup page > Manage Aircraft)";
       _viewLockPerformance.hidden = NO;
       [viewEnvironment bringSubviewToFront: _viewLockPerformance];
      
   }
    
}

- (void)buttSelHeli :(UIButton*)sender {    
    
    //NSLog(@"buttSelHeli");
    
    NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"];
    if (dedicatedCustomerData.length < 2) {
          dedicatedCustomerData = @"";
     }    
    [arrayCustomFlightDataElements removeAllObjects];    
    
    if ([dedicatedCustomerData rangeOfString:@"enableBEWoverride"].location != NSNotFound  ) {   
        
        UIImage *greenButton = [UIImage imageNamed:@"button strong green.png"];
         [_buttonUseDataForAircraft setBackgroundImage:greenButton forState:UIControlStateNormal];
        
        buttonIDbuttSel =sender.tag;
        
        //NSLog(@"buttonIDbuttSel %ld", (long)sender.tag);
        
        bew =  [[[arrayDictAllAircraft objectAtIndex:buttonIDbuttSel] objectForKey:@"BEW"] doubleValue];
        momlong =  [[[arrayDictAllAircraft objectAtIndex:buttonIDbuttSel] objectForKey:@"MomLong"] doubleValue];
        momlat =  [[[arrayDictAllAircraft objectAtIndex:buttonIDbuttSel] objectForKey:@"MomLat"] doubleValue];
        armlong = momlong / bew;
        armlat = momlat   / bew; 
        
        _inputOverrideBEW.text = [NSString stringWithFormat:@"%.1f",bew];
        _inputOverrideMoment.text = [NSString stringWithFormat:@"%.1f",momlong];
        _inputOverrideMomentLat.text = [NSString stringWithFormat:@"%.1f",momlat];  
        vFlightRegistration.text = [[arrayDictAllAircraft objectAtIndex:buttonIDbuttSel] objectForKey:@"Callsign"]; 
        _inputOverrideRegistration.text = vFlightRegistration.text;
        
         specialdata2 =  [[arrayDictAllAircraft objectAtIndex:buttonIDbuttSel] objectForKey:@"specialdata2"];
        
        if (flagSpecialPHIFlightSettingPage == 1) { 
                     
            _inputPHIOverrideBEW.text = [NSString stringWithFormat:@"%.1f",bew];
            _inputPHIOverrideMoment.text = [NSString stringWithFormat:@"%.1f",momlong];
            _inputPHIOverrideMomentLat.text = [NSString stringWithFormat:@"%.1f",momlat];  
            vFlightRegistration.text = [[arrayDictAllAircraft objectAtIndex:buttonIDbuttSel] objectForKey:@"Callsign"]; 
            _inputPHIOverrideRegistration.text = vFlightRegistration.text; 
            _viewSelectACWindow.hidden = YES;
         
                    
            _inputPHIOverrideFuelFlow.text = @"";
            _phiFuelFlowUnit.text = @"";
            if ([specialdata2 rangeOfString:@"fuelFlow"].location != NSNotFound ) {
                NSRange range = [specialdata2 rangeOfString:@"fuelFlow"];        
                NSString *codeItem =  [specialdata2 substringWithRange:NSMakeRange(range.location+11, 5)]; 
                _inputPHIOverrideFuelFlow.text = [ [NSString alloc] initWithFormat:@"%.1f", [codeItem floatValue] ];
                if ([specialdata2 rangeOfString:@"fuelFlowLB"].location != NSNotFound ) {
                _phiFuelFlowUnit.text = @"lbs/h";
                }
                if ([specialdata2 rangeOfString:@"fuelFlowGA"].location != NSNotFound ) {
                    _phiFuelFlowUnit.text = @"gal/h";
                }
            }
            
            if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"sledWeight"].location != NSNotFound ) {  
                
                [self overrideSledWeightFromSpecialData];
            }
            
            
            
            [self checkOverrideInputs];
        }
       
        
        
        loadedBEWUnits =  [[arrayDictAllAircraft objectAtIndex:buttonIDbuttSel] objectForKey:@"Units"];   
        
        if ( [loadedBEWUnits isEqualToString:@"lbs"]) {
            _labelHeliDataMass.text = @"Mass [lbs]";
            _labelHeliDataMomentLong.text = @"Moment [lbs.In]";
            _labelHeliDataMomentLat.text = @"Moment [lbs.In]";
        }else{
            _labelHeliDataMass.text = @"Mass [kg]";
            _labelHeliDataMomentLong.text = @"Moment [kg.mm]";
            _labelHeliDataMomentLat.text = @"Moment [kg.mm]";
        }
           
       }else{
           
           [self stuffToDoInButtSelHeli: sender.tag];  
       }
}

- (IBAction)actionOverrideBEWData:(id)sender { 
    
    if (_inputOverrideRegistration.text.length < 1|| _inputOverrideBEW.text.length < 1 || _inputOverrideMoment.text.length < 1 || _inputOverrideMomentLat.text.length < 1  ) {
        return;
    }
   [self.view endEditing:TRUE];
   [self stuffToDoInButtSelHeli: buttonIDbuttSel]; 
        
}



- (void) stuffToDoInButtSelHeli: (float)buttonID {
    
    //NSLog (@"stuffToDoInButtSelHeli");
       //NSLog (@"allFlightsMasterArray.count %lu", allFlightsMasterArray.count);
       
       MBpagevisit = 100;
       [[NSUserDefaults standardUserDefaults]  setFloat:  100   forKey:@"MBpagevisit"]; 
       
       _buttonCreateNewPHIFlight.hidden = YES;
    
       if (allFlightsMasterArray.count > 1 ) {
           
           if (flagChangeCallsign == 1) {
               flagMakeNewFlgtNow = 0;
           }else{            
               //NSLog (@"flagDoNotCreateFlightNow %d", flagDoNotCreateFlightNow );
               if (flagDoNotCreateFlightNow == 1) {
                   flagDoNotCreateFlightNow = 0;
               }else{
                    if (flagSpecialPHIFlightSettingPage == 1 ) {
                    }else{
                        flagMakeNewFlgtNow = 1;
                        [self SaveValues];
                        [self LoadValues];
                        [self createNewFlight];
                        flagMakeNewFlgtNow = 0;
                    }
                  
               }
           }     
       }
       
    
       previousACType = AC_Type;     
       arrayDictAllAircraft = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"] mutableCopy];
       vFlightRegistration.text = [[arrayDictAllAircraft objectAtIndex:buttonID] objectForKey:@"Callsign"];     
       loadedBEWUnits =  [[arrayDictAllAircraft objectAtIndex:buttonID] objectForKey:@"Units"];   
       specialdata2 =  [[arrayDictAllAircraft objectAtIndex:buttonID] objectForKey:@"specialdata2"];   
     
       
    
    NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"];
       if (dedicatedCustomerData.length < 2) {
             dedicatedCustomerData = @"";
        }   
    if ([dedicatedCustomerData rangeOfString:@"enableBEWoverride"].location != NSNotFound  ) {
        
        if (flagSpecialPHIFlightSettingPage == 1 ) {
            bew = [_inputPHIOverrideBEW.text floatValue];
            momlong = [_inputPHIOverrideMoment.text floatValue];
            momlat = [_inputPHIOverrideMomentLat.text floatValue];
            vFlightRegistration.text = _inputPHIOverrideRegistration.text;
        }else{
            bew = [_inputOverrideBEW.text floatValue];
            momlong = [_inputOverrideMoment.text floatValue];
            momlat = [_inputOverrideMomentLat.text floatValue];
            vFlightRegistration.text = _inputOverrideRegistration.text;
        }
        
    
    }else{
        bew =  [[[arrayDictAllAircraft objectAtIndex:buttonID] objectForKey:@"BEW"] doubleValue];
        momlong =  [[[arrayDictAllAircraft objectAtIndex:buttonID] objectForKey:@"MomLong"] doubleValue];
        momlat =  [[[arrayDictAllAircraft objectAtIndex:buttonID] objectForKey:@"MomLat"] doubleValue];        
    }
    
    //NSLog (@"1 bew    %f", bew);
    
    
       armlong = momlong / bew;
       armlat = momlat   / bew; 
       
       specialdata1 = [[arrayDictAllAircraft objectAtIndex:buttonID] objectForKey:@"specialdata1"];
       
       // get ac data
       NSString *specialdata3 = [[arrayDictAllAircraft objectAtIndex:buttonID] objectForKey:@"specialdata3"];
       specialdata3 = [specialdata3 stringByReplacingOccurrencesOfString:@" " withString:@""];
       specialdata3 = [specialdata3 stringByReplacingOccurrencesOfString:@"_" withString:@","];
       NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@","];
       NSArray *arrayComponents = [specialdata3 componentsSeparatedByCharactersInSet:charSet1];
        
    
    if (flagSpecialPHIFlightSettingPage == 1) {
        //do not override 
        
    }else{  
        
        
        if (arrayComponents.count == 3) {
            ACCategory = [arrayComponents objectAtIndex:0];
            ACmanufacturer = [arrayComponents objectAtIndex:1];
            AC_Type = [arrayComponents objectAtIndex:2];
            ACVariant = @"NONE";
        }
        if (arrayComponents.count > 3) {
            ACCategory = [arrayComponents objectAtIndex:0];
            ACmanufacturer = [arrayComponents objectAtIndex:1];
            AC_Type = [arrayComponents objectAtIndex:2];
            ACVariant = [arrayComponents objectAtIndex:3];
        }
    }
       
    
       dateOfWeighing = [[arrayDictAllAircraft objectAtIndex:buttonID] objectForKey:@"dateOfWeighing"];
       weighingRemarks = [[arrayDictAllAircraft objectAtIndex:buttonID] objectForKey:@"weighingRemarks"];
       
       
       [[NSUserDefaults standardUserDefaults]  setObject:ACCategory        forKey:@"ACCategory"];
       [[NSUserDefaults standardUserDefaults]  setObject:ACmanufacturer    forKey:@"ACmanufacturer"];
       [[NSUserDefaults standardUserDefaults]  setObject:AC_Type           forKey:@"AC_Type"];
       [[NSUserDefaults standardUserDefaults]  setObject:ACVariant         forKey:@"ACVariant"];
    
    //NSLog (@"1 stuffToDoInButtSelHeli inputFuelFlowOverride %@", inputFuelFlowOverride.text);
    // hier kommt searchbut...
       
       if (flagChangeCallsign == 1) {          
       }else{
           [self setConfiguration];
          
       }
    
       
       vBEW.text = [NSString stringWithFormat:@"%.2f",bew  ];
       vBEWMom.text = [NSString stringWithFormat:@"%.2f",momlong ];
       vBEWMomLat.text = [NSString stringWithFormat:@"%.2f",momlat ];
       lBEWArm.text = [NSString stringWithFormat:@"%.4f",armlong ];
       lBEWArmLat.text = [NSString stringWithFormat:@"%.4f",armlat];
                   
       // replace BEW
       //NSLog (@"3 replacing");
       [_arrayName2 replaceObjectAtIndex:3 withObject:vBEW.text];
       [_arrayName3 replaceObjectAtIndex:3 withObject:lBEWArm.text];
       [_arrayName4 replaceObjectAtIndex:3 withObject:vBEWMom.text];
       [_arrayName5 replaceObjectAtIndex:3 withObject:lBEWArmLat.text];
       [_arrayName6 replaceObjectAtIndex:3 withObject:vBEWMomLat.text];
                   
      
    
                   if (flagChangeCallsign == 1) {
                       //NSLog (@"changing callsign   %@", vBEW.text);
                       flagChangeCallsign = 0;
                       _viewSelectHelicopter.hidden = YES;
                       displayWindow = 0;
                        [self displayWindows];
                   }else{
                       //NSLog (@"NOT changing callsign   %@", vBEW.text);
                       [self addPerformanceButtons];
                       [self makeConfigButtons];
                       
                       triggerSetDefaultsForPerformanceCharts = 0;
                       _viewSelectHelicopter.hidden = YES;
                       //NSLog(@"butSelHeli AC_Type %@ ", AC_Type);
                       //NSLog(@"butSelHeli vBEW.text %@ ", vBEW.text);
                       
                       
                       //NSLog(@"butSelHeli flagMakeNewFlgtNow %d ", flagMakeNewFlgtNow);
                       
                       if (flagMakeNewFlgtNow == 1) {                           
                           [self createNewFlight];
                           displayWindow = 0;
                           [self displayWindows];
                           [self MainRoutine];
                           
                       }else{
                           displayWindow = 0;
                           [self displayWindows];
                          
                       }
                       
                    
                       
                       [self loadDefaultEquipmentArrays];
                       //[[EquipPackagesManager sharedInstance] addNewPackageWithKey: vFlightRegistration.text andDefaultConfig:0];
                       [self resetFlightSettings];  // set configuration and load array listo        
                       // do we need to retain crew?
                       //NSLog(@"allFlightsMasterArray %d ", allFlightsMasterArray.count);
                       if ([previousACType isEqualToString:AC_Type]) {
                           if (allFlightsMasterArray.count > 2) {
                               //[self retainCrewNames];
                           }
                       }
                       
                       if ([ACCategory isEqualToString:@"FixedWing"]) {
                           //NSLog(@"butseliheli triggerPresetSliders %@", ACCategory);
                           [[NSUserDefaults standardUserDefaults]  setObject:AC_Type        forKey:@"tempACtype"];
                           [calculatePerformanceClass_ triggerPresetSliders];
                       }
                   }
                   
 
                   [self SaveValues];    
                   [self MainRoutine];
                   [self MainRoutine];
                   _buttonCancelSelectAC.hidden = NO;
                   
                   if (flagShowOnlySameACType == 1) {
                       flagShowOnlySameACType = 0;
                       _viewLegData.hidden = YES;
                       [self addHelicopterButtons];
                   }
       
       
    
}







- (void) resetFlightSettings {
    
      //NSLog(@"resetFlightSettings");
    
    for (int i = 0; i < arrayCustomFlightDataElements.count; i++) {           
        [arrayCustomFlightDataElements replaceObjectAtIndex:i withObject:@""];         
    }
    
    _inputTimer1.text = @"";
    _inputTimer2.text = @"";
    _inputTimer3.text = @"";
    _inputTimer4.text = @"";
    _inputTimer5.text = @"";
    _inputTimer6.text = @"";
    _inputPaxOnBoard.text = @"";
    _vFlightIDName.text = @"";
    _labelDepartureTimeLocal.text = @"";
    _labelDepartureTimeGMT.text = @"";
    _labellandingtimeLocal.text = @"";
    _labelFlightTimeMinutes.text = @"60";
    vFlightDeparture.text = @"";
    vFlightDestination.text = @"";
    _vFlightTimeHours.text = @"";
    _vFlightTimeMinutes.text = @"";
    _vEngineStarts1.text = @"";
    _vEngineStarts2.text = @"";
    _vRIN.text = @"";
    _vFlightRemarks.text = @"";  
    _vFlightTimeMinInput.text = @"0";
    //_vFlightTypeField.text = @"";
    previousConfiguration = 999;
    [self makeConfigButtons];
    
    _dropDownAvailableACTypes.text = @"select";
    _dropDownAvailableCallsigns.text = @"-";
   
    
    NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"];    
    if (dedicatedCustomerData.length < 2) {
        dedicatedCustomerData = @"";
    }         
    if ([dedicatedCustomerData rangeOfString:@"guidanceSystemOn"].location != NSNotFound  ) {        
         _switchGuidance.on = YES;           
    }else{
        _switchGuidance.on = NO;        
    }    
    if ([dedicatedCustomerData rangeOfString:@"openCrewListOnSeatTap"].location != NSNotFound  ) {        
        _segmentSeatLoadOptions.selectedSegmentIndex = 1;           
    }

    flagJustResettedFlightSettings = 1;
    [self setItemsFlightLegData];
    
}





- (IBAction)buttonActionNextFlight:(id)sender {
    
    //NSLog(@"buttonActionNextFlight" );
    
    int flagFlightSettingsOpen =0;
    if (_viewLegData.hidden == NO) {
        flagFlightSettingsOpen =1;
    }
    
    if ( [vFlightID intValue] >= (allFlightsMasterArray.count-1)  ) {
        return;
    }else{
        [self SaveValues];
        
        triggerOpenChart = 1;
        //triggerSetDefaultsForPerformanceCharts = 1;
        [calculatePerformanceClass_ triggerLoadSliderData];
        vFlightID =  [ [NSString alloc] initWithFormat:@"%u", [vFlightID intValue] +1];
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        //NSLog(@"loading flight  %d ", btn.tag-300);
        [defaults  setObject: vFlightID  forKey:@"vFlightID"];
        vLegID = @"1";
        [self LoadValues];
        [self createFlightButtons];
        [self MainRoutine];
        
        if (viewLoadManifest.hidden == NO) {
            [self copyLabelsManifest];           
        }
        
        if (_viewPowerCheck.hidden == NO) {
            calculatePerformanceClassView_.hidden = YES;
            displayWindow = 0;
        }
        //NSLog(@"displayWindow  %.0f ", displayWindow);
        UIButton *prevButt = (UIButton *)[self.viewTopDisplayButtons viewWithTag:previousdButton];
        UIView *signalStripe = (UIView *)[_viewUniversalButtons viewWithTag:999];
        signalStripe.frame = CGRectMake(prevButt.frame.origin.x, signalStripe.frame.origin.y, signalStripe.frame.size.width, signalStripe.frame.size.height);
        if (displayWindow > 100) {
            prevButt.selected = YES;
            signalStripe.hidden = NO;
        }else{
            prevButt.selected = NO;
            signalStripe.hidden = YES;
        }
        
        
        if (configMode == 1) {
            configMode = 0;
            [self setConfigWindow];
            [self setCGenvelope];
        }
        
    }
    
 
    if (amountofButtonsNeeded == 0 & viewLoadManifest.hidden == YES) {
        displayWindow = 0;
        [self displayWindows];
    }
    
    if (viewLoadManifest.hidden == NO) {
        displayWindow = 11;
        [self displayWindows];
    }
   
    if (displayWindow > 100) {
        
        if (displayWindow - 100 > amountofButtonsNeeded) {
            displayWindow = 0;
            UIView *signalStripe = (UIView *)[_viewUniversalButtons viewWithTag:999];
            signalStripe.hidden = YES;
             [self displayWindows];
        }
    }
    
    if (flagFlightSettingsOpen == 1) {
        _viewLegData.hidden = NO;
    }
    
    if (_viewAddStation.hidden == NO) {
        [self createCustomStationList];
    }
    
    [self MainRoutine];
    
}

- (IBAction)buttonActionPreviousFlight:(id)sender {
    
     //NSLog(@"buttonActionPreviousFlight" );
    
    int flagFlightSettingsOpen =0;
     if (_viewLegData.hidden == NO) {
         flagFlightSettingsOpen =1;
     }
    
    if ( [vFlightID intValue] <= 1  ) {
        return;
    }else{
       
        [self SaveValues];
        triggerOpenChart = 1;
        [calculatePerformanceClass_ triggerLoadSliderData];
        vFlightID =  [ [NSString alloc] initWithFormat:@"%u", [vFlightID integerValue] -1];
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        //NSLog(@"loading flight  %d ", btn.tag-300);
       
        [defaults  setObject: vFlightID  forKey:@"vFlightID"];
        vLegID = @"1";
        [self LoadValues];      
        [self createFlightButtons]; 
        [self MainRoutine];
    
       ;
        if (_viewPowerCheck.hidden == NO) {
            calculatePerformanceClassView_.hidden = YES;
            displayWindow = 0;
        }
        
        if (viewLoadManifest.hidden == NO) {
             [self copyLabelsManifest];
        }
      
        [self addPerformanceButtons];
    
        //NSLog(@"displayWindow  %.0f ", displayWindow);
        UIButton *prevButt = (UIButton *)[self.viewTopDisplayButtons viewWithTag:previousdButton];
        UIView *signalStripe = (UIView *)[_viewUniversalButtons viewWithTag:999];
        signalStripe.frame = CGRectMake(prevButt.frame.origin.x, signalStripe.frame.origin.y, signalStripe.frame.size.width, signalStripe.frame.size.height);
        if (displayWindow > 100) {
            prevButt.selected = YES;
            signalStripe.hidden = NO;
        }else{
            prevButt.selected = NO;
            signalStripe.hidden = YES;
        }
        
        if (configMode == 1) {
            configMode = 0;
            [self setConfigWindow];
            [self setCGenvelope];
        }
      
    
    }
    
    if (amountofButtonsNeeded == 0 & viewLoadManifest.hidden == YES) {
        displayWindow = 0;
        [self displayWindows];
    }    

    if (viewLoadManifest.hidden == NO) {        
        displayWindow = 11;
        [self displayWindows];       
    }
    
    if (displayWindow > 100) {        
        if (displayWindow - 100 > amountofButtonsNeeded) {
            displayWindow = 0;
             [self displayWindows];
            UIView *signalStripe = (UIView *)[_viewUniversalButtons viewWithTag:999];
            signalStripe.hidden = YES;
        }
    }    
    
    if (flagFlightSettingsOpen == 1) {
        _viewLegData.hidden = NO;
    }    
    
    if (_viewAddStation.hidden == NO) {
        [self createCustomStationList];
    }
    
    [self MainRoutine];
    
}


- (IBAction)buttonActionNextLeg:(id)sender {
    
    if ([vLegID intValue] >= allLegsPerFlightArray.count -1) {
        return;
    }
    
    int flagFlightSettingsOpen =0;
    if (_viewLegData.hidden == NO) {
        flagFlightSettingsOpen =1;
    }
    
    [self SaveValues];
    vLegID = [NSString stringWithFormat:@"%d",  [vLegID intValue] + 1  ];
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    [defaults  setObject:vLegID                     forKey:@"vLegID"];
    
    [self LoadValues];
    [self MainRoutine];
    if (viewLoadManifest.hidden == NO) {
        [self copyLabelsManifest];
    }
    
    if (configMode == 1) {
        configMode = 0;
        [self setConfigWindow];
        [self setCGenvelope];
    }
    
   
    
    if (flagFlightSettingsOpen == 1) {
        _viewLegData.hidden = NO;
    } 
    
    [self MainRoutine];
    
}

- (IBAction)buttonActionPreviousLeg:(id)sender {
    
    if ([vLegID intValue] <= 1) {
        return;
    }
    
    int flagFlightSettingsOpen =0;
    if (_viewLegData.hidden == NO) {
        flagFlightSettingsOpen =1;
    }
    
    [self SaveValues];
    
    vLegID = [NSString stringWithFormat:@"%d",  [vLegID intValue] - 1  ];
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    [defaults  setObject:vLegID                     forKey:@"vLegID"];
    
    [self LoadValues];
    [self MainRoutine];
    
    if (viewLoadManifest.hidden == NO) {
        [self copyLabelsManifest];
    }
    
    if (configMode == 1) {
        configMode = 0;
        [self setConfigWindow];
        [self setCGenvelope];
    }
    
    if (flagFlightSettingsOpen == 1) {
        _viewLegData.hidden = NO;
    } 
    
    [self MainRoutine];
    
   
}




// ALERT VIEW

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    // 0 ist der LINKE button   1 ist der RECHTE BUTTON (KG)
    // alert DELETE FLIGHT
    
    if (alertFlag == 1) {
        if (buttonIndex == 0) {
            [self MainRoutine];
        }
        if (buttonIndex == 1) {
        }
    }
    if (alertFlag == 1001) {
        
        if (buttonIndex == 0) {
        }
        if (buttonIndex == 1) {
            [self deleteActiveLeg];
        }
    }
    
    if (alertFlag == 1002) {
        
        if (buttonIndex == 0) {            
        }
        if (buttonIndex == 1) {            
            [self addLegToActiveFlight];
        }        
    }
    
    if (alertFlag == 1003) {        
        if (buttonIndex == 0) {            
        }
        if (buttonIndex == 1) {            
            [self deleteFlightFromManager];
        }        
    }

    
    if (alertFlag == 1004) {        
        if (buttonIndex == 0) {
            
        }
        if (buttonIndex == 1) {            
            [self deleteActiveFlightFromManager];
        }        
    }
    
    if (alertFlag == 1005) {
        
        if (buttonIndex == 0) {
            
        }        
        
        if (buttonIndex == 1) {            
            [self resetAllFlightsFromManager];
        }        
    }
    // alert DELETE first FLIGHT    
    if (alertFlag == 2) { 
        if (buttonIndex == 0) {
            [self MainRoutine]; 
        }
        
        if (buttonIndex == 1) {
            [self MainRoutine];        
     } 
    }
    // alert CREATE new FLIGHT    
    
    if (alertFlag == 3) { 
        if (buttonIndex == 0) { 
            [self MainRoutine]; 
        }
        if (buttonIndex == 1) {
        }
    }
    if (alertFlag == 5) { // SAVE SETTINGS        
        if (buttonIndex == 0) {            
            [self SaveValues];
        }
        
        if (buttonIndex == 1) {
            [self SaveValues];
        }
    }
    
    if (alertFlag == 6) { // SAVE SETTINGS
        if (buttonIndex == 0) {
            [self MainRoutine];            
        }
        if (buttonIndex == 1) {
            [self sendManifestViaEmail];            
        }
    }
    
    if (alertFlag == 8) { // helicopter updates        
        if (buttonIndex == 0) {            
            //NSLog(@"button 0 "); 
        }        
        if (buttonIndex == 1) { 
            flagUpdateFleetControlDataOnly = 1;
            [self updateAircraftData];
        }
    }
    
    if (alertFlag == 81) { // FORCE helicopter updates         
        if (buttonIndex == 0) {            
            //NSLog(@"button 0 "); 
        }        
        if (buttonIndex == 1) { 
            [self updateAircraftData];
        }
    }
    
    
    if (alertFlag == 31) {
        if (buttonIndex == 0) { 
            [self MainRoutine];            
        }
        if (buttonIndex == 1) {
        }
    }

    
    if (alertFlag == 210) { // nvg filter        
        if (buttonIndex == 0) {
            nvgMode = 0;
            [self SaveValues];            
            [self MainRoutine];            
        } 
        if (buttonIndex == 1) {            
            nvgMode = 1;            
            [self SaveValues];            
            [self MainRoutine];
        }
        
        
    }
    
    
    if (alertFlag == 444) {        
        if (buttonIndex == 0) {            
            [self MainRoutine];            
        } 
        if (buttonIndex == 1) {
            displayWindow = 0;            
            [self displayWindows];
        }
    }
    
    
    if (alertFlag == 666) {        
        if (buttonIndex == 0) {
        }
        
        if (buttonIndex == 1) {            
            [self SaveValues];            
            // total recall            
             [[NSUserDefaults standardUserDefaults]  setObject:@"yes" forKey:@"totalRecall"];
            //[self dismissModalViewControllerAnimated:YES];            
            StartPage *second = [[StartPage alloc] initWithNibName:nil bundle:nil];
           second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
             second.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:second animated:YES completion:nil];
            
        }
        
    }
    
    
    if (alertFlag == 1000) {        
        if (buttonIndex == 0) {
        }
        
        if (buttonIndex == 1) {            
           //resload aircraft data
            importPerformanceData *_importPerformanceData = [[importPerformanceData alloc]init];
            [_importPerformanceData loadAvailableACTypesArrayFromFleetControl];
            
            triggerSetDefaultsForPerformanceCharts = 0;
            _viewLoadingData.hidden = NO;
            [viewOne bringSubviewToFront: _viewLoadingData];
            [_loadDatapinner startAnimating];
            [self performSelector: @selector (loadACData) withObject:nil afterDelay: 0.1f];  
            
        }
        
    }
    
    if (alertFlag == 1020) {        
        if (buttonIndex == 0) {
        }
        
        if (buttonIndex == 1) {            
            //resload aircraft data
            [self startImportConfigsFromFleetControl];

            
        }
        
    }
    
    if (alertFlag == 1010) {        
        if (buttonIndex == 0) {
        }
        
        if (buttonIndex == 1) {            
            //change callsign
             flagMakeNewFlgtNow = 0;    
            flagDoNotCreateFlightNow = 1;
                          _viewSelectHelicopter.hidden = NO; [viewOne bringSubviewToFront:_viewSelectHelicopter];
                          //flagShowOnlySameACType = 1; 
                          [self addHelicopterButtons];  

            
        }
        
    }
    
    if (alertFlag == 2000) {        
        if (buttonIndex == 0) {
        }
        
        if (buttonIndex == 1) {
            flagUsingAlternateEquipment = 0;    
            flagLoadConfigDataForButton= 1;    
            //NSLog(@"old configuration  %d" , configuration);                 
            configuration = activeConfigButton;    
            [self setConfiguration];
            [self retainCrewNames];    
            [self searchbutSelHeli];   
            [self loadDefaultEquipmentArrays]; 
            [self createSpecialEquipListItems];
            [self makeConfigButtons];
            [self MainRoutine]; 
        }
    }
    
    if (alertFlag == 2010) {        
        if (buttonIndex == 0) {
        }        
        if (buttonIndex == 1) { 
            [self uploadSummaryAfterCheck];
        }
    }
    [self MainRoutine];
     
        
        
 }
    
   



// setup
- (IBAction)actionWebsiteGyroinimo:(UIButton *)sender {
    
    
    [[UIApplication sharedApplication]
     
     openURL:[NSURL URLWithString:@"http://www.gyronimo.com"]];
    
}

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

- (IBAction)actionSendEmailAuthor:(id)sender {
    
    
    MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
    
    [composer setMailComposeDelegate: self];
    
    if ([MFMailComposeViewController canSendMail]) {
        
        [composer setToRecipients:[NSArray arrayWithObjects:@"info@gyronimo.com", nil]];
        
        [composer setSubject:@"Flight Pad"];
        
        [composer setMessageBody: @"" isHTML:NO];
        
        [composer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
        
        [self presentModalViewController:composer animated:YES];
        
        
    }
    
}

- (IBAction)switchActionWarnings:(id)sender {
    
    if (switchWarnings.on) {
    
        warningsOnOff = 1; [self MainRoutine];
        
            
    }  else {
        
        warningsOnOff = 0;
        
        
        [self MainRoutine];
    
    }

    

    
    
    
}


- (IBAction)switchActionAutoLandingFuel:(id)sender {
    
    if (_switchAutoLandingFuel.on == YES) {
       
    }else{
        
        _sliderFuelLanding.enabled = YES;
    }
    
    [self MainRoutine];
    [self MainRoutine];
    
    
    
}


- (IBAction)switchActionNVG:(id)sender {
    
    if (_switchNVG.on) {
        
        
        
        alertFlag = 210;
        
        
        UIAlertView *alert = [[UIAlertView alloc]
                              
                              initWithTitle:@"NVG Filter"
                              
                              message:@"Before using the NVG filter make sure to dim your iPad backlight all the way down. Then, switch NVG filter ON and use the slider at the bottom to darken the screen even further. To switch off the filter, tapo on the swich again. \n\nNote: Other apps will still be bright! Test function before night flight."
                              
                              delegate:self
                              
                              cancelButtonTitle:@"CANCEL"
                              
                              otherButtonTitles:@"NVG FILTER ON", nil];
        
        [alert show];
        
        
        
        
    }  else {
        
        nvgMode = 0;
        
        [self prefersStatusBarHidden];
        
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
        
        [self SaveValues];
        
        [self MainRoutine];
        
    }
    
    
}






// signature stuff ***************


- (IBAction)buttonActionSignatureWindow:(UIButton *)sender {
    
    signatureForDocumentType = sender.tag;
    [ signatureController clearSignature];
    _viewSignature.hidden = NO; [viewOne bringSubviewToFront:_viewSignature];
}


// delete the signature from the manifest
- (IBAction)buttonActionSignatureDelete:(id)sender {
    [ signatureController clearSignature];
}


//  put signature in manifest

- (IBAction)buttonActionSignatureSign:(id)sender {
    
    _viewSignature.hidden = YES;
    
     //NSLog(@"buttonActionSignatureSign signatureForDocumentType %d", signatureForDocumentType);
    
    if (signatureForDocumentType == 1) {
        loadedSignatureImage = [ signatureController getSignature];
       [self mountSignatureImageToLoadManifest];
    }
    
    if (signatureForDocumentType == 2) {
        loadedSignature2Image = [ signatureController getSignature];
        [self mountSignatureImageToPowerCheck];
    }
    
    [signatureController clearSignature];
    
}



- (void) mountSignatureImageToLoadManifest {
    
    //NSLog(@"mountSignatureImageToLoadManifest");
    
    [scrollSig removeFromSuperview];
    
    scrollSig = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, loadedSignatureImage.size.width, loadedSignatureImage.size.height)];
    [scrollSig setImage:loadedSignatureImage];
    
    float scaleFactor = MIN(110/loadedSignatureImage.size.height, 1.0);  // was 120
    
    scrollSig.transform = CGAffineTransformScale(scrollSig.transform, scaleFactor, scaleFactor);
    
    scrollSig.frame = CGRectMake(70, 1200, scrollSig.frame.size.width, scrollSig.frame.size.height);
    [ ScrollViewManifest addSubview:scrollSig ];
    
    signatureImageData = [NSData dataWithData:UIImagePNGRepresentation(loadedSignatureImage)];

}

- (void) mountSignatureImageToPowerCheck {
    
    //NSLog(@"mountSignatureImageToPowerCheck");
    
    [scroll2Sig removeFromSuperview];
    
    scroll2Sig = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, loadedSignature2Image.size.width, loadedSignature2Image.size.height)];
    [scroll2Sig setImage:loadedSignature2Image];
    
    float scaleFactor = MIN(110/loadedSignature2Image.size.height, 1.0);  // was 120
    
    scroll2Sig.transform = CGAffineTransformScale(scroll2Sig.transform, scaleFactor, scaleFactor);
    
    scroll2Sig.frame = CGRectMake(100, 500, scroll2Sig.frame.size.width, scroll2Sig.frame.size.height);
    [ _ScrollViewPowerCheck addSubview:scroll2Sig ];
    
    signature2ImageData = [NSData dataWithData:UIImagePNGRepresentation(loadedSignature2Image)];
    
}





- (IBAction)actionSaveSummaryAsImage:(id)sender {
    
    [self saveImageSummary];
    
    
}

- (void)saveImageSummary {
    
    
    int pixelWidth = _scrollViewSummaryManifest.contentSize.width;
    int pixelHeight = summaryBoxHeight +290;  // set hight of pdf page here (cut off the bottom)
    
    CGSize frame=CGSizeMake(pixelWidth, pixelHeight);
    UIGraphicsBeginImageContext(frame);
    
    
    CGPoint savedContentOffset = _scrollViewSummaryManifest.contentOffset;
    CGRect savedFrame = _scrollViewSummaryManifest.frame;
    
    
    _scrollViewSummaryManifest.contentOffset = CGPointZero;
    _scrollViewSummaryManifest.frame = CGRectMake(0, 0, pixelWidth, pixelHeight);
    
    
    [_scrollViewSummaryManifest.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(image, self,@selector(image:didFinishSavingWithError:contextInfo:), nil);
    
    
    _scrollViewSummaryManifest.contentOffset = savedContentOffset;
    _scrollViewSummaryManifest.frame = savedFrame;
    
    
}




- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    // Was there an error?
    if (error != NULL)
    {
        // Show error message...
        //NSLog(@"Failed to save image!");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed to Save."
                                                        message:[error localizedDescription]
                                                       delegate:self cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil];
        [alert show];
    }
    else  // No errors
    {
        // Show message image successfully saved
        //NSLog(@"Saved image!");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Done! \nTheManifest was saved to your Photos/Camera folder. You can view and print it from there."
                                                        message:[error localizedDescription]
                                                       delegate:self cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil];
        [alert show];
        
        
        
        
    }
}




//  close signature view

- (IBAction)buttonActionSignatureCancel:(id)sender {
    
    [ signatureController clearSignature];
    _viewSignature.hidden = YES;
    
    
    
}

//  clear signature





- (IBAction)buttonActionSwapDepartDestination:(id)sender {
    
    NSString *depart = vFlightDeparture.text;
    
    NSString *Destin = vFlightDestination.text;
    
    vFlightDeparture.text = Destin;
    
    vFlightDestination.text =depart;
    
    
    
}






// el listo// el listo// el listo// el listo// el listo// el listo// el listo// el listo// el listo// el listo// el listo// el listo// el listo// el listo// el listo


- (void) addListoItemsByMoment {
    
    //NSLog(@"addListoItemsByMoment packageStart %.0f", packageStart);
    
    // add fields in for next
    
    for (int i = packageStart; i < packageEND+1  ; i++) {
        
        // find item i.e. weight
        
        //check if maxCombined
        if ([[_arrayName18 objectAtIndex: i ] rangeOfString:@"maxCombined"].location != NSNotFound ) {            
            //check total weight for this and the next station
            float totalWeight = [[_arrayName2 objectAtIndex: i ] floatValue] + [[_arrayName2 objectAtIndex: i + 1 ] floatValue];            
            if (totalWeight > [[_arrayName9 objectAtIndex: i ] floatValue]) {
                //NSLog (@"yes we have it and it is over!!! %d", i);
                NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"^"];
                NSArray *components = [[_arrayName18 objectAtIndex: i ]  componentsSeparatedByCharactersInSet:charSet1];
                NSString *messageText = [components objectAtIndex:1];
                
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:messageText
                                                                                         message:nil
                                                                                  preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
                [alertController addAction:actionOk];
                [self presentViewController:alertController animated:YES completion:nil];  
            }
        }
       
        
        float weightListo = [[_arrayName2 objectAtIndex:i] floatValue];
        
        float longMomentListo = [[_arrayName4 objectAtIndex:i] floatValue];
        
        float LatMomentListo = [[_arrayName6 objectAtIndex:i] floatValue];
        
        float multiplicator = [[_arrayName8 objectAtIndex:i] floatValue];
        
        //NSLog (@"i %d weightListo is %.0f ", i, weightListo);
        
        //NSLog (@"%@ %f  %f %f", [_arrayName1 objectAtIndex:i],  weightListo,  longMomentListo, LatMomentListo);
  
        
        
        totalWeightListo = totalWeightListo + ( weightListo * multiplicator);
        
        totallongMomentListo = totallongMomentListo + ( longMomentListo * multiplicator);
        
        totalLatMomentListo = totalLatMomentListo + ( LatMomentListo * multiplicator);
        
        totalArmListo = totallongMomentListo / totalWeightListo;
        
        totalArmLatListo = totalLatMomentListo / totalWeightListo;
    
        
        
    }
    
    
    
    return;
    
    
    
}


- (void) addFuelTanksByMoment {
    
    
    
    // add fields in for nexts
    
    
    tankNumber = 0;
    
    
    for (int i = packageStart; i < packageEND+1  ; i++) {
        
        // find item i.e. weight
        
        tankNumber = tankNumber + 1;
        
        //NSLog(@"addFuelTanksByMoment tankNumber %d", tankNumber);
      
        
        float weightListo = [[_arrayName2 objectAtIndex:i] floatValue];
        
        fuelVolume = weightListo / [_inputSpecificFuelMassPerVolume.text floatValue];
        // make gallons from lbs
        
        //NSLog(@"semding from 3 addFuelTanksByMoment");
        [self interpolateFuelMomentsLongitudinal];
        //NSLog (@"fuelMoment LONG %.4f ", fuelMoment);
        
        
        float longMomentListo = fuelMoment;
        
        
        [self interpolateFuelMomentsLateral];
        //NSLog (@"fuelMoment LAT %.0f ", fuelMoment);
        
        
        float LatMomentListo = fuelMoment;
        
        if ([[_arrayName17 objectAtIndex: i  ] rangeOfString:@"subtract"].location != NSNotFound) {
            weightListo = weightListo * -1;
            longMomentListo = longMomentListo * -1;
            LatMomentListo = LatMomentListo * -1;
        }
        
        
        float multiplicator = [[_arrayName8 objectAtIndex:i] floatValue];
        //NSLog (@"multiplicator is %@ ", multiplicator);
        totalWeightListo = totalWeightListo + ( weightListo * multiplicator);
        totallongMomentListo = totallongMomentListo + ( longMomentListo * multiplicator);
        totalLatMomentListo = totalLatMomentListo + ( LatMomentListo * multiplicator);
        
        totalArmListo = totallongMomentListo / totalWeightListo;
        
        totalArmLatListo = totalLatMomentListo / totalWeightListo;
        
        
        //NSLog (@"totalWeightListo LONG %.0f ", totalWeightListo);
        
        //NSLog (@"totallongMomentListo LONG %.0f ", totallongMomentListo);
        
        //NSLog (@"totalArmListo LONG %.0f ", totalArmListo);
        
        
        //[_arrayName2 replaceObjectAtIndex:listoItemNr withObject: [ [NSString alloc] initWithFormat:@"%.1f", totalWeightListo]];
        
        //NSLog (@"longMomentListo %.4f ", longMomentListo);
        
        
        [_arrayName4 replaceObjectAtIndex:i withObject: [ [NSString alloc] initWithFormat:@"%.1f", longMomentListo]];
        [_arrayName6 replaceObjectAtIndex:i withObject: [ [NSString alloc] initWithFormat:@"%.1f", LatMomentListo]];
        
        if ([[_arrayName18 objectAtIndex:lineZFW + tankNumber] rangeOfString:@"fix"].location == NSNotFound  ) {
            [_arrayName3 replaceObjectAtIndex:i withObject: [ [NSString alloc] initWithFormat:@"%.1f", longMomentListo / weightListo ]];
            [_arrayName5 replaceObjectAtIndex:i withObject: [ [NSString alloc] initWithFormat:@"%.1f", LatMomentListo / weightListo]];
            
           if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {        
           [_arrayName3 replaceObjectAtIndex:i withObject: [ [NSString alloc] initWithFormat:@"%.3f", longMomentListo / weightListo ]];
           [_arrayName5 replaceObjectAtIndex:i withObject: [ [NSString alloc] initWithFormat:@"%.3f", LatMomentListo / weightListo]];
           
               
           }
            
            
        }
        
        //NSLog (@"_arrayName3 %@ ", [_arrayName3 objectAtIndex:i]);
        
    }
    
    
    
    return;
    
    
    
}



- (void) getFuelListoMain {
    
   
    
    flagDoNotDrawCG = 0;

    if ([AC_Type rangeOfString:@"R44Raven"].location != NSNotFound   || [AC_Type rangeOfString:@"R44Cadet"].location != NSNotFound  || [AC_Type rangeOfString:@"R22Beta"].location != NSNotFound  ) {
        

        
        if (listoItemNr == lineZFW+1) {
            flagDoNotDrawCG = 1;
            ///NSLog(@"1 getFuelListoMain");
            fuelVolume = mainshare;
            fuelWeight = mainshare * [_inputSpecificFuelMassPerVolume.text floatValue];  
            
            mainWeight = fuelWeight;
            
            [self interpolateFuelMomentsLongitudinal];
            float fuelMomentLong = fuelMoment; 
            mainMom = fuelMomentLong;
            float longArmListo = fuelMomentLong / fuelWeight;    
            if (fuelWeight <= 1) {longArmListo = 0; fuelMomentLong = 0; }
            
            [self interpolateFuelMomentsLateral];    
            float fuelMomentLateral = fuelMoment;
            mainMomLat = fuelMomentLateral;
            float longArmListoLat = fuelMomentLateral / fuelWeight;    
            if (fuelWeight <= 1) {longArmListoLat = 0; fuelMomentLateral = 0; }  
            
            totalWeightListo        = fuelWeight ;    
            totalArmListo           =  longArmListo ;    
            totallongMomentListo    = totallongMomentListo + fuelMomentLong;    
            totalArmLatListo = longArmListoLat;    
            totalLatMomentListo  = totalLatMomentListo + fuelMomentLateral;
            [self overwriteArrays];
            return;
            
        }
        
        if (listoItemNr == lineZFW+2) {
             flagDoNotDrawCG = 1;
            //NSLog(@"2 getFuelListoMain");
            fuelVolume = auxshare;
            fuelWeight = auxshare * [_inputSpecificFuelMassPerVolume.text floatValue];  
            
            auxWeight = fuelWeight;
             
            [self interpolateFuelMomentsLongitudinal];
            float fuelMomentLong = fuelMoment; 
            auxMom =  fuelMomentLong;
            float longArmListo = fuelMomentLong / fuelWeight;    
            if (fuelWeight <= 1) {longArmListo = 0; fuelMomentLong = 0; }
            
            [self interpolateFuelMomentsLateral];    
            float fuelMomentLateral = fuelMoment;
            auxMomLat =  fuelMomentLateral;
            float longArmListoLat = fuelMomentLateral / fuelWeight;    
            if (fuelWeight <= 1) {longArmListoLat = 0; fuelMomentLateral = 0; }  
            
            totalWeightListo        = fuelWeight ;    
            totalArmListo           =  longArmListo ;    
            totallongMomentListo    = totallongMomentListo + fuelMomentLong;    
            totalArmLatListo = longArmListoLat;    
            totalLatMomentListo  = totalLatMomentListo + fuelMomentLateral;
            [self overwriteArrays];
            return;
        }
        
        if (listoItemNr == lineZFW+3) {
            flagDoNotDrawCG = 2;
            
            
            fuelVolume = _sliderFuelMain1.value;
            fuelWeight = _sliderFuelMain1.value * [_inputSpecificFuelMassPerVolume.text floatValue];
            
            
            totalWeightListo        = fuelWeight ;    
            totalArmListo           =  (mainMom + auxMom) /  (mainWeight + auxWeight);    
            totallongMomentListo    = mainMom + auxMom;    
            totalArmLatListo = (mainMomLat + auxMomLat) /  (mainWeight + auxWeight);;    
            totalLatMomentListo  = mainMomLat + auxMomLat; 
            //NSLog(@"totalArmListo %.1f", totalArmListo);
            
            robinsonTotalFuelForCG =  fuelVolume;            
            //NSLog(@"3 getFuelListoMain robinsonTotalFuelForCG %.1f", robinsonTotalFuelForCG);            
            robinsonArmForCG = totalArmListo;
            //NSLog(@"3 getFuelListoMain robinsonArmForCG %.1f", robinsonArmForCG);
            
            [self overwriteArrays];
            
            
            
        }
        
        
    }else{
        fuelVolume = _sliderFuelMain1.value;
        fuelWeight = _sliderFuelMain1.value * [_inputSpecificFuelMassPerVolume.text floatValue];  
        
        [self interpolateFuelMomentsLongitudinal];
        float fuelMomentLong = fuelMoment;    
        float longArmListo = fuelMomentLong / fuelWeight;    
        if (fuelWeight <= 1) {longArmListo = 0; fuelMomentLong = 0; }
        
        [self interpolateFuelMomentsLateral];    
        float fuelMomentLateral = fuelMoment;
        float longArmListoLat = fuelMomentLateral / fuelWeight;    
        if (fuelWeight <= 1) {longArmListoLat = 0; fuelMomentLateral = 0; }  
        
        totalWeightListo        = fuelWeight ;    
        totalArmListo           =  longArmListo ;    
        totallongMomentListo    = totallongMomentListo + fuelMomentLong;    
        totalArmLatListo = longArmListoLat;    
        totalLatMomentListo  = totalLatMomentListo + fuelMomentLateral;
        [self overwriteArrays];
        return;
        
    }
   
   
    
    //NSLog(@"mainshare + mainshare %.1f", mainshare + auxshare);
    //NSLog(@"_sliderFuelMain1.value%.1f", _sliderFuelMain1.value);
    
    
    
   
}

- (void) getFuelListoLanding {
    
    //NSLog(@"getFuelListoLanding");
    
    if ([AC_Type rangeOfString:@"R44Raven"].location != NSNotFound   || [AC_Type rangeOfString:@"R44Cadet"].location != NSNotFound  || [AC_Type rangeOfString:@"R22Beta"].location != NSNotFound  ) {
        
        if (listoItemNr == lineTOW+1) {
            fuelVolume = mainshareLND;
            fuelWeight = mainshareLND * [_inputSpecificFuelMassPerVolume.text floatValue]; 
            mainWeightLND = fuelWeight;            
            [self interpolateFuelMomentsLongitudinal];    
            float fuelMomentLong = fuelMoment; 
            mainMomLND = fuelMomentLong;
            float longArmListo = fuelMomentLong / fuelWeight;    
            if (fuelWeight <= 1) {longArmListo = 0; fuelMomentLong = 0; }
            
            [self interpolateFuelMomentsLateral];    
            float fuelMomentLateral = fuelMoment;  
            mainMomLatLND = fuelMomentLateral;
            //NSLog(@"fuelMomentLateral %.0f", fuelMomentLateral);
            float longArmListoLat = fuelMomentLateral / fuelWeight;    
            if (fuelWeight <= 1) {longArmListoLat = 0; fuelMomentLateral = 0; }
            totalWeightListo        = fuelWeight ;    
            totalArmListo           =  longArmListo ;    
            totallongMomentListo    = totallongMomentListo + fuelMomentLong;    
            totalArmLatListo = longArmListoLat;    
            totalLatMomentListo  = totalLatMomentListo + fuelMomentLateral; 
            [self overwriteArrays];
            
            
        }
        
        if (listoItemNr == lineTOW+2) {
            fuelVolume = auxshareLND;
            fuelWeight = auxshareLND * [_inputSpecificFuelMassPerVolume.text floatValue]; 
            
            auxWeightLND = fuelWeight;            
            [self interpolateFuelMomentsLongitudinal];    
            float fuelMomentLong = fuelMoment; 
            auxMomLND = fuelMomentLong;
            float longArmListo = fuelMomentLong / fuelWeight;    
            if (fuelWeight <= 1) {longArmListo = 0; fuelMomentLong = 0; }
            
            [self interpolateFuelMomentsLateral];    
            float fuelMomentLateral = fuelMoment;  
            auxMomLatLND = fuelMomentLateral;
            //NSLog(@"fuelMomentLateral %.0f", fuelMomentLateral);
            float longArmListoLat = fuelMomentLateral / fuelWeight;    
            if (fuelWeight <= 1) {longArmListoLat = 0; fuelMomentLateral = 0; }
            totalWeightListo        = fuelWeight ;    
            totalArmListo           =  longArmListo ;    
            totallongMomentListo    = totallongMomentListo + fuelMomentLong;    
            totalArmLatListo = longArmListoLat;    
            totalLatMomentListo  = totalLatMomentListo + fuelMomentLateral; 
            [self overwriteArrays];
            
            
        }
        
        if (listoItemNr == lineTOW+3) {
            fuelVolume = _sliderFuelLanding.value;
            fuelWeight = _sliderFuelLanding.value * [_inputSpecificFuelMassPerVolume.text floatValue];  
            
            totalWeightListo        = fuelWeight ;    
            totalArmListo           =  (mainMomLND + auxMomLND) /  (mainWeightLND + auxWeightLND);    
            totallongMomentListo    = mainMomLND + auxMomLND;    
            totalArmLatListo = (mainMomLatLND + auxMomLatLND) /  (mainWeightLND + auxWeightLND);;    
            totalLatMomentListo  = mainMomLatLND + auxMomLatLND; 
            //NSLog(@"totalArmListo %.1f", totalArmListo);
            
            [self overwriteArrays];
            
            
        }
        
    }else{
        
        fuelVolume = _sliderFuelLanding.value;
        fuelWeight = _sliderFuelLanding.value * [_inputSpecificFuelMassPerVolume.text floatValue];
        
        [self interpolateFuelMomentsLongitudinal];    
        float fuelMomentLong = fuelMoment;    
        float longArmListo = fuelMomentLong / fuelWeight;    
        if (fuelWeight <= 1) {longArmListo = 0; fuelMomentLong = 0; }
        
        [self interpolateFuelMomentsLateral];    
        float fuelMomentLateral = fuelMoment;    
        //NSLog(@"fuelMomentLateral %.0f", fuelMomentLateral);
        float longArmListoLat = fuelMomentLateral / fuelWeight;    
        if (fuelWeight <= 1) {longArmListoLat = 0; fuelMomentLateral = 0; }
        totalWeightListo        = fuelWeight ;    
        totalArmListo           =  longArmListo ;    
        totallongMomentListo    = totallongMomentListo + fuelMomentLong;    
        totalArmLatListo = longArmListoLat;    
        totalLatMomentListo  = totalLatMomentListo + fuelMomentLateral; 
        [self overwriteArrays];
        
    }
    
    
   
    
    
    
    return;
    
    
    
}


- (void) overwriteArrays {
    
    //NSLog(@"overwriteArrays listoItemNr %.0f", listoItemNr); 
     //NSLog (@"%@ %f  %f", [_arrayName1 objectAtIndex:listoItemNr],  totallongMomentListo,  totalLatMomentListo);
    
    /*
    if (isnan(totalWeightListo)) {
        totalWeightListo = 0;
    }    
    if (isnan(totalArmListo)) {
        totalArmListo = 0;
    }    
    if (isnan(totallongMomentListo)) {
        totallongMomentListo = 0;
    }    
    if (isnan(totalArmLatListo)) {
        totalArmLatListo = 0;
    }
    if (isnan(totalLatMomentListo)) {
        totalLatMomentListo = 0;
    }
     */
    
    
    if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {        
        //if meter
        [_arrayName2 replaceObjectAtIndex:listoItemNr withObject: [ [NSString alloc] initWithFormat:@"%.4f", totalWeightListo]];        
        [_arrayName3 replaceObjectAtIndex:listoItemNr withObject: [ [NSString alloc] initWithFormat:@"%.4f", totalArmListo]];        
        [_arrayName4 replaceObjectAtIndex:listoItemNr withObject: [ [NSString alloc] initWithFormat:@"%.4f", totallongMomentListo]];        
        [_arrayName5 replaceObjectAtIndex:listoItemNr withObject: [ [NSString alloc] initWithFormat:@"%.4f", totalArmLatListo]];        
        [_arrayName6 replaceObjectAtIndex:listoItemNr withObject: [ [NSString alloc] initWithFormat:@"%.4f", totalLatMomentListo]];        
    }else{
        [_arrayName2 replaceObjectAtIndex:listoItemNr withObject: [ [NSString alloc] initWithFormat:@"%.5f", totalWeightListo]];        
        [_arrayName3 replaceObjectAtIndex:listoItemNr withObject: [ [NSString alloc] initWithFormat:@"%.4f", totalArmListo]];        
        [_arrayName4 replaceObjectAtIndex:listoItemNr withObject: [ [NSString alloc] initWithFormat:@"%.4f", totallongMomentListo]];        
        [_arrayName5 replaceObjectAtIndex:listoItemNr withObject: [ [NSString alloc] initWithFormat:@"%.4f", totalArmLatListo]];        
        [_arrayName6 replaceObjectAtIndex:listoItemNr withObject: [ [NSString alloc] initWithFormat:@"%.4f", totalLatMomentListo]];
    }
    
   
       return;
    
}

- (void) updateSeatButtonLabels {
    
    
    
   //NSLog(@"updateSeatButtonLabels listStart %.0f", listStart);
    
   for (int i = listStart; i < listEnd+1 ; i++) {
       
       valueField = (UITextField*)[_viewInterior viewWithTag: 200 + i];
       
       [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [[_arrayName2 objectAtIndex:i ] floatValue]  ]  ];
       
       if (_segmentNamesOnSeats.selectedSegmentIndex == 1 ) {
           
           
           valueField = (UITextField*)[_viewInterior viewWithTag: 700 + i];
           
           [valueField  setText: [_arrayName12 objectAtIndex:i ]   ];
           
           
           // exception pilot/copilot
           
           if (i == linePilot || i == linePilot +1) {
                [valueField  setText: [_arrayName7 objectAtIndex:i ]   ];
           }
          
           
       }
       
       if (_segmentNamesOnSeats.selectedSegmentIndex == 2 ) {
           
           
           valueField = (UITextField*)[_viewInterior viewWithTag: 700 + i];
           
           //[valueField  setText: [_arrayName7 objectAtIndex:i ]   ];
           
           //only surname
           //NSLog(@"[_arrayName7 objectAtIndex:i ]  %@", [_arrayName7 objectAtIndex:i ] );
           NSArray* componentItems  = [[_arrayName7 objectAtIndex:i ]  componentsSeparatedByString:@","];  
           [valueField  setText: [componentItems objectAtIndex:0 ]   ];
           
           if ([[_arrayName14 objectAtIndex:i  ] rangeOfString:@"single"].location != NSNotFound) {
               [valueField  setText: [_arrayName1 objectAtIndex:i ]   ];               
           }
           
       }
       
     
       
     

       
   }
   
    
    
    
    
}


- (void) getPenaltiesH145 {
    
    //NSLog (@"getPenaltiesH145");
    
    penaltyWeight = 0;
    penaltyFtMin = 0;
    
    for (int i = listStart; i < listEnd+1 ; i++) {
        
        if ([[_arrayName24 objectAtIndex:i]length] > 1  ) {
            
            // read penalty
            
            NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"_"];
            NSArray *items = [[_arrayName24 objectAtIndex:i] componentsSeparatedByCharactersInSet:charSet1];
            
            //NSLog (@"check %d %@  %@", i, [_arrayName1 objectAtIndex:i], [_arrayName8 objectAtIndex:i]);
            
            penaltyWeight = penaltyWeight +  ( [[items objectAtIndex:0] floatValue] * [[_arrayName8 objectAtIndex:i] floatValue] );
            
            
            if (weightTOW >= 3200) {
                penaltyFtMin = penaltyFtMin +  ( [[items objectAtIndex:2] floatValue] * [[_arrayName8 objectAtIndex:i] floatValue] );
            }else{
                penaltyFtMin = penaltyFtMin +  ( [[items objectAtIndex:1] floatValue] * [[_arrayName8 objectAtIndex:i] floatValue] );
            }
            
        }
    }    
    
    UILabel *label =(UILabel*)[_viewOptions viewWithTag: 1000] ;
    [label  setText: [ [NSString alloc] initWithFormat:@"Weight Penalty = %.0f kg", penaltyWeight ] ];
    
    label =(UILabel*)[_viewOptions viewWithTag: 1001] ;
    [label  setText: [ [NSString alloc] initWithFormat:@"Height Gain Penalty = %.0f ft/100ft", penaltyFtMin ] ];
    
    
    label =(UILabel*)[_viewOptions viewWithTag: 1002] ;
    [label  setText: [ [NSString alloc] initWithFormat:@"TOM = %.0fkg / Corrected = %.0fkg", weightTOW,  weightTOW - penaltyWeight ] ];

    
    
   //NSLog (@"penaltyWeight %.1f  ", penaltyWeight);
    //NSLog (@"penaltyFtMin %.1f  ", penaltyFtMin);
    
    
}

-(void) calculateListo {
         
    
    //NSLog (@"calculateListo  [_arrayName2 objectAtIndex:3] %@", [_arrayName2 objectAtIndex:3]);    
    //NSLog (@"_arrayName2  %@", _arrayName2);    
    
    [self computeSpecialEquipmentTotals];
    
    float totalEquipmentWeight     =  totalSpecialEquipWeight;
    float totalEquipmentMoment     =  totalSpecialEquipMoment;
    float totalEquipmentMomentLat  =  totalSpecialEquipMomentLat;
    
    float totalEquipmentArm        =  totalSpecialEquipMoment/totalSpecialEquipWeight;
    float totalEquipmentArmLat     =  totalEquipmentMomentLat/totalSpecialEquipWeight;
    
    
    totalWeightListo = totalEquipmentWeight;
    totalArmListo = totalEquipmentArm ;
    
    if (totalEquipmentArm < 1) {
        totalArmListo = 0;
    }    
    totallongMomentListo = totalEquipmentMoment ;
    totalLatMomentListo = totalEquipmentMomentLat;
    totalArmLatListo = totalEquipmentArmLat;
    if (totalEquipmentMomentLat < 1) {
        totalArmLatListo = 0;
    }    
    //NSLog(@"lineEquipment %f", lineEquipment); 
    if (lineEquipment > 0) {
        listoItemNr = lineEquipment;    
        [self overwriteArrays];
    }
        
   
    
    // special Richard   
    // get Zero Fuel    
    packageStart    = 1;
    packageEND      = lineZFW-1;     
    totalWeightListo = 0; totallongMomentListo =0; totalLatMomentListo = 0; totalArmListo = 0 ; totalLatMomentListo = 0;    
    [self addListoItemsByMoment];
    
    listoItemNr = lineZFW;    
    [self overwriteArrays];
    
    lZFW = totalWeightListo;    
    lZFWArm = totalArmListo;    
    lZFWMom = totallongMomentListo;    
    lZFWArmLat = totalArmLatListo;    
    lZFWMomLAt = totalLatMomentListo;    
    
    float lZFM = totalWeightListo,  lZFMmoment = totallongMomentListo,  lZFMmomlat = totalLatMomentListo; // this is ZFM
    
    
    //  ***************************************************************************************************************
       
    // check if we have the new fuel system    
    fuelOnBoardKg = 0;
    flagMultipleFuelTanks = 0;
    tankNumber = 1;
    firstLineFuelTank = lineFirstFuelTankTO;    
    
    
    //NSLog(@"******");
         
    //NSLog(@"Fuel Arie fuelUnits = %@", fuelUnits);
    
    //NSLog(@"Fuel Arie selectedUnitForFuel = %@", selectedUnitForFuel);
          
    //NSLog (@"flagCreateFuelPage %d", flagCreateFuelPage);   
   
    float internalSpecificFuelMassPerVolume = 0;
    
    if ([fuelUnits isEqualToString:selectedUnitForFuel] ) { 
        //convert lbs/Gal to kg/liter            
        internalSpecificFuelMassPerVolume = [_inputSpecificFuelMassPerVolume.text floatValue] ;          
    }
    
    if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
        //convert lbs/Gal to kg/liter            
        internalSpecificFuelMassPerVolume =  ([_inputSpecificFuelMassPerVolume.text floatValue] / 2.2046 ) / 3.78541;            
    }
    
    if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
        
        //convert lbs/Gal to kg/liter            
        internalSpecificFuelMassPerVolume =  ([_inputSpecificFuelMassPerVolume.text floatValue] * 2.2046 ) * 3.78541;            
    }
    
    
    
    
    
  
    //NSLog(@"internalSpecificFuelMassPerVolume %.3f ", internalSpecificFuelMassPerVolume);
   
    if (![fuelUnits isEqualToString:selectedUnitForFuel]) {      
        
        _viewFuelDensityConversion.hidden = NO;        
        if ([selectedUnitForFuel isEqualToString:@"lbs"]) {            
            _unitLabelFuelDenistyConversion.text = @"lbs/gal";
            _inputFuelDensityConverted.text = [[NSString alloc] initWithFormat:@"%.3f", internalSpecificFuelMassPerVolume ];           
            
        }else{
           
            _unitLabelFuelDenistyConversion.text = @"kg/ltr";
            _inputFuelDensityConverted.text = [[NSString alloc] initWithFormat:@"%.3f", internalSpecificFuelMassPerVolume ];
        }        
        
        
    }else{
         _viewFuelDensityConversion.hidden = YES;
    }
    
    //set new flight time field if leg time is > 0
    if (legFlightTimeMinutes > 0) {
        _vFlightTimeMinInput.text = [[NSString alloc] initWithFormat:@"%d", legFlightTimeMinutes ];
        _vFlightTimeMinInput.enabled = NO;
        _vFlightTimeMinInput.backgroundColor = [UIColor grayColor];
        //NSLog(@"setting flight time");
    }else{
        _vFlightTimeMinInput.enabled = YES;
        _vFlightTimeMinInput.backgroundColor = [UIColor whiteColor];   
        
    }
    
    if (flagCreateFuelPage == 1) {      
        
        // new fuel system
        _viewFuelSliders.hidden = NO;        
        packageStart    = lineFirstFuelTankTO;
        packageEND      = (lineFirstFuelTankTO-1) + amountOfFuelTanksTO;
        
        if (amountOfFuelTanksTO > 1) {
            flagMultipleFuelTanks = 1;
        }else{
            flagMultipleFuelTanks = 0;
        }        
        //NSLog (@"flagMultipleFuelTanks %d ", flagMultipleFuelTanks);
        totalWeightListo = 0; totallongMomentListo =0; totalLatMomentListo = 0; totalArmListo = 0 ; totalLatMomentListo = 0;
        
        //NSLog(@"go addFuelTanksByMoment ");
        [self addFuelTanksByMoment];
        listoItemNr = lineTOW - 1; // total fuel
        [self overwriteArrays];
        fuelOnBoardKg = totalWeightListo;   
        
        
        //*******************************************************
        //NSLog (@"fuelOnBoardKg %.0f", fuelOnBoardKg);        
        // write total fuel TO
        valueField = (UITextField*)[_viewFuelSliders viewWithTag: 2000 ];
        
        
        //NSLog(@"fuelEnterMode %@", fuelEnterMode);
        
        //NSLog(@"fuelUnits %@", fuelUnits);
        
        //NSLog(@"selectedUnitForFuel %@", selectedUnitForFuel);
        
        //NSLog(@"1 fuelOnBoardKg %.0f", fuelOnBoardKg);
        
        if (valueField) {            
            //NSLog(@"1fuelarie");
            //fuelarie
            
            if ([fuelEnterMode isEqualToString:@"mass"]) {
                //NSLog(@"1");
                if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f lbs / %.0f gal", fuelOnBoardKg, fuelOnBoardKg / [_inputSpecificFuelMassPerVolume.text floatValue]]  ];  
                    _inputFuelOnBoard.text = [ [NSString alloc] initWithFormat:@"%.1f",  fuelOnBoardKg * factorApplyToNativeFuelWeight];
                    _labelRequiredReserveWeight.text = [ [NSString alloc] initWithFormat:@"%.1f",  [inputFuelFlowOverride.text floatValue] * ([_vReserveTimeField.text floatValue]/60)   ];
                    _labelFuelForFlight.text = [ [NSString alloc] initWithFormat:@"%.1f",   [inputFuelFlowOverride.text floatValue] * ([_vFlightTimeMinInput.text floatValue]/60) ];

                }                
                
                if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
                    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f kg / %.0f ltr", (fuelOnBoardKg / 2.2046), (fuelOnBoardKg/ 2.2046) / internalSpecificFuelMassPerVolume  ]  ];  
                    _inputFuelOnBoard.text = [ [NSString alloc] initWithFormat:@"%.0f", (fuelOnBoardKg/ 2.2046)];
                    _labelRequiredReserveWeight.text = [ [NSString alloc] initWithFormat:@"%.1f",  [inputFuelFlowOverride.text floatValue] * ([_vReserveTimeField.text floatValue]/60)   ];
                    _labelFuelForFlight.text = [ [NSString alloc] initWithFormat:@"%.1f",   [inputFuelFlowOverride.text floatValue] * ([_vFlightTimeMinInput.text floatValue]/60) ];
                    
                    
                }
                
                if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
                    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f kg / %.0f ltr", fuelOnBoardKg, fuelOnBoardKg / internalSpecificFuelMassPerVolume  ]  ];  
                    _inputFuelOnBoard.text = [ [NSString alloc] initWithFormat:@"%.0f", fuelOnBoardKg];
                    _labelRequiredReserveWeight.text = [ [NSString alloc] initWithFormat:@"%.1f",  [inputFuelFlowOverride.text floatValue] * ([_vReserveTimeField.text floatValue]/60)   ];
                    _labelFuelForFlight.text = [ [NSString alloc] initWithFormat:@"%.1f",   [inputFuelFlowOverride.text floatValue] * ([_vFlightTimeMinInput.text floatValue]/60) ];
                }
                
                if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f lbs / %.0f gal", (fuelOnBoardKg * 2.2046), (fuelOnBoardKg* 2.2046) / internalSpecificFuelMassPerVolume  ]  ];  
                    _inputFuelOnBoard.text = [ [NSString alloc] initWithFormat:@"%.0f", (fuelOnBoardKg * 2.2046)];
                    _labelRequiredReserveWeight.text = [ [NSString alloc] initWithFormat:@"%.1f",  [inputFuelFlowOverride.text floatValue] * ([_vReserveTimeField.text floatValue]/60)   ];
                    _labelFuelForFlight.text = [ [NSString alloc] initWithFormat:@"%.1f",   [inputFuelFlowOverride.text floatValue] * ([_vFlightTimeMinInput.text floatValue]/60) ];
                }
                
                
            }else{
                 //NSLog(@"2");
                if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f gal / %.0f lbs", fuelOnBoardKg / [_inputSpecificFuelMassPerVolume.text floatValue], fuelOnBoardKg  ]  ];   
                    _inputFuelOnBoard.text = [ [NSString alloc] initWithFormat:@"%.1f",  (fuelOnBoardKg / [_inputSpecificFuelMassPerVolume.text floatValue]) * factorApplyToNativeFuelVolumeGalLiter ];
                    _labelRequiredReserveWeight.text = [ [NSString alloc] initWithFormat:@"%.1f",   [inputFuelFlowOverride.text floatValue] * ([_vReserveTimeField.text floatValue]/60)   ];
                    _labelFuelForFlight.text = [ [NSString alloc] initWithFormat:@"%.1f",   [inputFuelFlowOverride.text floatValue] * ([_vFlightTimeMinInput.text floatValue]/60) ];
                } 
                
                
                if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
                    //slider in lbs and we need liter
                    // convert lbs to specific gallons  = lbs / specific                
                    // convert gallons to ltr                        
                    //NSLog (@"(fuelOnBoardKg %.0f", fuelOnBoardKg);                    
                    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f ltr / %.0f kg", (fuelOnBoardKg /  [_inputSpecificFuelMassPerVolume.text floatValue]) * 3.78541 , (fuelOnBoardKg / 2.2046)   ]  ];
                    _inputFuelOnBoard.text = [ [NSString alloc] initWithFormat:@"%.1f", (fuelOnBoardKg /  [_inputSpecificFuelMassPerVolume.text floatValue]) * 3.78541   ];
                    _labelRequiredReserveWeight.text = [ [NSString alloc] initWithFormat:@"%.1f",   [inputFuelFlowOverride.text floatValue] * ([_vReserveTimeField.text floatValue]/60)   ];
                    _labelFuelForFlight.text = [ [NSString alloc] initWithFormat:@"%.1f",   [inputFuelFlowOverride.text floatValue] * ([_vFlightTimeMinInput.text floatValue]/60) ];
                } 
                
                
                if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
                    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f ltr / %.0f kg", fuelOnBoardKg / [_inputSpecificFuelMassPerVolume.text floatValue], fuelOnBoardKg  ]  ];   
                    _inputFuelOnBoard.text = [ [NSString alloc] initWithFormat:@"%.1f",  (fuelOnBoardKg / [_inputSpecificFuelMassPerVolume.text floatValue]) * factorApplyToNativeFuelVolumeGalLiter ];
                    _labelRequiredReserveWeight.text = [ [NSString alloc] initWithFormat:@"%.1f",   [inputFuelFlowOverride.text floatValue] * ([_vReserveTimeField.text floatValue]/60)   ];
                    _labelFuelForFlight.text = [ [NSString alloc] initWithFormat:@"%.1f",   [inputFuelFlowOverride.text floatValue] * ([_vFlightTimeMinInput.text floatValue]/60) ];
                } 
                
                
                if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                    //slider in kg and we need gallons
                    // convert kg to liter / specific 0.79             
                    // convert liter to gallons   / 3.78541                        
                    //NSLog (@"(fuelOnBoardKg %.0f", fuelOnBoardKg);                    
                    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f gal / %.0f lbs", ((fuelOnBoardKg / [_inputSpecificFuelMassPerVolume.text floatValue]) / 3.78541 ) , (fuelOnBoardKg * 2.2046)   ]  ];
                    _inputFuelOnBoard.text = [ [NSString alloc] initWithFormat:@"%.1f", ((fuelOnBoardKg / [_inputSpecificFuelMassPerVolume.text floatValue]) / 3.78541 )   ];
                    _labelRequiredReserveWeight.text = [ [NSString alloc] initWithFormat:@"%.1f",   [inputFuelFlowOverride.text floatValue] * ([_vReserveTimeField.text floatValue]/60)   ];
                    _labelFuelForFlight.text = [ [NSString alloc] initWithFormat:@"%.1f",   [inputFuelFlowOverride.text floatValue] * ([_vFlightTimeMinInput.text floatValue]/60) ];
                } 
                
                
            }
            
        }  
        
        
        //NSLog(@"fuelOnBoardKg %.0f", fuelOnBoardKg);
        //NSLog(@"_inputFuelOnBoard.text %@", _inputFuelOnBoard.text);
        
      //_inputFuelOnBoard
        
     //************************************************************************************************* 
        //************************************************************************************************* 
        //************************************************************************************************* 
        //************************************************************************************************* 
        //************************************************************************************************* 
        
        
    }else{
        
        
        _viewFuelSliders.hidden = YES;
        // get Fuel
        
        
      
        if ([AC_Type rangeOfString:@"R44Raven"].location != NSNotFound   || [AC_Type rangeOfString:@"R44Cadet"].location != NSNotFound  || [AC_Type rangeOfString:@"R22Beta"].location != NSNotFound  ) {
            
           
            packageStart    = lineZFW+1;
            packageEND      = lineZFW+2; // get Fuel
            totalWeightListo = 0; totallongMomentListo =0; totalLatMomentListo = 0;
            listoItemNr = lineZFW+1;          
            [self getFuelListoMain];
            
       
            packageStart    = lineZFW+1;
            packageEND      = lineZFW+2; // get Fuel
            totalWeightListo = 0; totallongMomentListo =0; totalLatMomentListo = 0;
            listoItemNr = lineZFW+2;         
            [self getFuelListoMain];
         
           
            packageStart    = lineZFW+1;
            packageEND      = lineZFW+2; // get Fuel
            totalWeightListo = 0; totallongMomentListo =0; totalLatMomentListo = 0;
            listoItemNr = lineZFW+3;         
            [self getFuelListoMain];
        
        
            
            
        }else{
            
            packageStart    = lineZFW+1;
            packageEND      = lineTOW-1; // get Fuel
            totalWeightListo = 0; totallongMomentListo =0; totalLatMomentListo = 0;
            listoItemNr = lineZFW+1;
            [self getFuelListoMain];
            
            
        }
       
        
        
        
       
        if ([_vFlightTimeMinutes.text floatValue] > 59 || [_vFlightTimeMinutes.text floatValue] <= 0 ) {
            _vFlightTimeMinutes.text = @"00";
        }
        if ([_vFlightTimeHours.text floatValue] > 59 || [_vFlightTimeHours.text floatValue] <= 0 ) {
            _vFlightTimeHours.text = @"0";
        }
        flightTimeMinutesALL = ( [_vFlightTimeHours.text floatValue] * 60.0 )    +  [_vFlightTimeMinutes.text floatValue];
        fuelOnBoardKg = _sliderFuelMain1.value  * [_inputSpecificFuelMassPerVolume.text floatValue];
        
        //sfuel
        
        //NSLog(@"fuelOnBoardKg %.0f", fuelOnBoardKg);        
        //NSLog(@"factorApplyToNativeFuelWeight %.0f", factorApplyToNativeFuelWeight);
        
         if ([fuelEnterMode isEqualToString:@"mass"] ) {
            _inputFuelOnBoard.text = [ [NSString alloc] initWithFormat:@"%.1f",  fuelOnBoardKg * factorApplyToNativeFuelWeight];
            
         }else{
             _inputFuelOnBoard.text = [ [NSString alloc] initWithFormat:@"%.1f",  (fuelOnBoardKg / [_inputSpecificFuelMassPerVolume.text floatValue]) * factorApplyToNativeFuelVolumeGalLiter ];
              
         }
        
        _labelRequiredReserveWeight.text = [ [NSString alloc] initWithFormat:@"%.1f",  [inputFuelFlowOverride.text floatValue] * ([_vReserveTimeField.text floatValue]/60) ];
        
        _labelFuelForFlight.text = [ [NSString alloc] initWithFormat:@"%.1f",  [inputFuelFlowOverride.text floatValue] * ([_vFlightTimeMinInput.text floatValue]/60) ];
        
        //NSLog(@"[inputFuelFlowOverride.text floatValue] %.2f", [inputFuelFlowOverride.text floatValue]);        
        //NSLog(@"([_vReserveTimeField.text floatValue]/60) %.2f", ([_vReserveTimeField.text floatValue]/60)  );        
        //NSLog(@"factorApplyToNativeFuelWeight %.2f", factorApplyToNativeFuelWeight);        
        //NSLog(@"_labelRequiredReserveWeight.textt %@", _labelRequiredReserveWeight.text);
        
        
    }
    
    //NSLog(@"fuelOnBoardKg %.2f", fuelOnBoardKg);  
    
     double lFuel = totalWeightListo,  lFuelMom = totallongMomentListo,  lFuelMomLat = totalLatMomentListo; // this is Fuel
    
     double lFuelLanding = 0,  lFuelMomLanding = 0,  lFuelMomLatLanding = 0; // this is landing Fuel
    

   
    
    if (_vReserveTimeField.text.length < 1) {
        _vReserveTimeField.items   =  @[ @"20", @"30", @"45"];
        _vReserveTimeField.text = @"20";
    }
 
   
    float landingFuelMinutes = [_vReserveTimeField.text integerValue];
    
    float totalPossibleFlightTimeMinutes = ([_inputFuelOnBoard.text floatValue] / [inputFuelFlowOverride.text floatValue]) * 60 ;
    
    if ([_vFlightTimeMinInput.text floatValue] > 0) {
        landingFuelMinutes =  totalPossibleFlightTimeMinutes - [_vFlightTimeMinInput.text integerValue] - [_vReserveTimeField.text floatValue]; 
        //NSLog(@"landingFuelMinutes %.0f", landingFuelMinutes);
    }
    
  
    
     ;
    
    
    
    float landingFuelKg = 0;
    
    float landingFuelKgMinForReserve = 0;
    
    
    tankNumber = 1;
    firstLineFuelTank = lineFirstFuelTankLD;
    
    _warningIncreaseLandingFuel.hidden = YES;
    
    UIButton* btn = (UIButton*)[buttonView viewWithTag: 111 ];
    UIImage *btnImage = [UIImage imageNamed:@"button blue top184x52"];
    [btn  setBackgroundImage:btnImage forState:UIControlStateNormal];
    
    
    if (flagCreateFuelPage == 1) {
        
        _viewAutoLandingFuel.hidden = YES;
        // new fuel system for landing fuel
        packageStart    = lineFirstFuelTankLD;
        packageEND      = (lineFirstFuelTankLD-1) + amountOfFuelTanksLD;
        
        //NSLog(@"packageStart %.1f", packageStart );
        //NSLog(@"packageEND %.1f", packageEND );
        
        totalWeightListo = 0; totallongMomentListo =0; totalLatMomentListo = 0; totalArmListo = 0 ; totalLatMomentListo = 0;        
        //NSLog(@"calculateListo Landing ");
        [self addFuelTanksByMoment];        
        listoItemNr = lineLDW - 1; // total fuel        
        [self overwriteArrays];        
        landingFuelKg = totalWeightListo;        
        lFuelLanding = totalWeightListo,  lFuelMomLanding = totallongMomentListo,  lFuelMomLatLanding = totalLatMomentListo; // this is landing Fuel
        
        
        // write total fuel LD
        valueField = (UITextField*)[_viewFuelSliders viewWithTag: 2010 ]; 
       
        //NSLog(@"landingFuelKg %.0f", landingFuelKg);
      
         if ([fuelEnterMode isEqualToString:@"mass"]) {
             
             if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                 [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f lbs / %.0f gal", landingFuelKg, landingFuelKg / [_inputSpecificFuelMassPerVolume.text floatValue]]  ]; 
                  _labelFuelEstimatedLanding.text = [ [NSString alloc] initWithFormat:@"%.0f",  landingFuelKg   ];                 
                 _labelTotalReserveTime.text = [ [NSString alloc] initWithFormat:@"%.0f", (landingFuelKg /  [inputFuelFlowOverride.text floatValue]) * 60    ];
             }                
             
             if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
                 [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f kg / %.0f ltr", (landingFuelKg/ 2.2046), (landingFuelKg/ 2.2046) / internalSpecificFuelMassPerVolume  ]  ]; 
                  _labelFuelEstimatedLanding.text = [ [NSString alloc] initWithFormat:@"%.0f",  landingFuelKg/2.2046   ];
                 
                 _labelTotalReserveTime.text = [ [NSString alloc] initWithFormat:@"%.0f", ((landingFuelKg/ 2.2046) /  [inputFuelFlowOverride.text floatValue]) * 60    ];
             }
             
             if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
                 [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f kg / %.0f ltr", landingFuelKg, landingFuelKg / internalSpecificFuelMassPerVolume  ]  ]; 
                 _labelFuelEstimatedLanding.text = [ [NSString alloc] initWithFormat:@"%.0f",  landingFuelKg   ];                 
                 _labelTotalReserveTime.text = [ [NSString alloc] initWithFormat:@"%.0f", (landingFuelKg /  [inputFuelFlowOverride.text floatValue]) * 60    ];
             }
             
             
             if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                 [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f kg / %.0f ltr", (landingFuelKg * 2.2046), (landingFuelKg * 2.2046) / internalSpecificFuelMassPerVolume  ]  ]; 
                 _labelFuelEstimatedLanding.text = [ [NSString alloc] initWithFormat:@"%.0f",  landingFuelKg * 2.2046   ];
                 
                 _labelTotalReserveTime.text = [ [NSString alloc] initWithFormat:@"%.0f", ((landingFuelKg * 2.2046) /  [inputFuelFlowOverride.text floatValue]) * 60    ];
             }
             
             
             
             
         }else{
             
             if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                 [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f gal / %.0f lbs", landingFuelKg / [_inputSpecificFuelMassPerVolume.text floatValue], landingFuelKg  ]  ];  
                  _labelFuelEstimatedLanding.text = [ [NSString alloc] initWithFormat:@"%.0f",  landingFuelKg  / [_inputSpecificFuelMassPerVolume.text floatValue]  ];                                  
                 _labelTotalReserveTime.text = [ [NSString alloc] initWithFormat:@"%.0f",  landingFuelKg /  ([inputFuelFlowOverride.text floatValue] * [_inputSpecificFuelMassPerVolume.text floatValue]) *60   ];
             } 
             
             if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
                 //slider in lbs and we need liter
                 // convert lbs to specific gallons  = lbs / specific                
                 // convert gallons to ltr                        
                 //NSLog (@"(fuelOnBoardKg %.0f", fuelOnBoardKg);                    
                 [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f ltr / %.0f kg", (landingFuelKg /  [_inputSpecificFuelMassPerVolume.text floatValue]) * 3.78541 , (landingFuelKg / 2.2046)   ]  ];
                 _labelFuelEstimatedLanding.text = [ [NSString alloc] initWithFormat:@"%.0f",  (landingFuelKg /  [_inputSpecificFuelMassPerVolume.text floatValue]) * 3.78541   ];                                  
                 _labelTotalReserveTime.text = [ [NSString alloc] initWithFormat:@"%.0f",  (( (landingFuelKg /  [_inputSpecificFuelMassPerVolume.text floatValue]) * 3.78541) /  [inputFuelFlowOverride.text floatValue]) *60   ];
             } 
             
             
             if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
                 [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f ltr / %.0f kg", landingFuelKg / [_inputSpecificFuelMassPerVolume.text floatValue], landingFuelKg  ]  ];  
                 _labelFuelEstimatedLanding.text = [ [NSString alloc] initWithFormat:@"%.0f",  landingFuelKg  / [_inputSpecificFuelMassPerVolume.text floatValue]  ];                                  
                 _labelTotalReserveTime.text = [ [NSString alloc] initWithFormat:@"%.0f",  landingFuelKg /  ([inputFuelFlowOverride.text floatValue] * [_inputSpecificFuelMassPerVolume.text floatValue]) *60   ];
             } 
            
             
             
             if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) {                                   
                 //slider in kg and we need gallons
                 // convert kg to liter / specific 0.79             
                 // convert liter to gallons   / 3.78541
                 //NSLog (@"(fuelOnBoardKg %.0f", fuelOnBoardKg);                    
                 [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f gal / %.0f lbs", ((landingFuelKg / [_inputSpecificFuelMassPerVolume.text floatValue]) / 3.78541 ) , (landingFuelKg * 2.2046)   ]  ];                 
                 _labelFuelEstimatedLanding.text = [ [NSString alloc] initWithFormat:@"%.0f",  ((landingFuelKg / [_inputSpecificFuelMassPerVolume.text floatValue]) / 3.78541 )  ];                                  
                 _labelTotalReserveTime.text = [ [NSString alloc] initWithFormat:@"%.0f",  (( (landingFuelKg /  [_inputSpecificFuelMassPerVolume.text floatValue]) / 3.78541) /  [inputFuelFlowOverride.text floatValue]) *60   ];
                 
                 
             } 
             
             
             
         }
        
      
        //NSLog(@"[_vReserveTimeField.text floatValue] %.2f", [_vReserveTimeField.text floatValue]);
        
        //NSLog(@"[_labelTotalReserveTime.text floatValue] %.2f", [_labelTotalReserveTime.text floatValue] );
        
        if ([_vReserveTimeField.text floatValue] > [_labelTotalReserveTime.text floatValue] ) {
            _warningIncreaseLandingFuel.hidden = NO;                      
            UIButton* btn = (UIButton*)[buttonView viewWithTag: 111 ];
            UIImage *btnImage = [UIImage imageNamed:@"button_red.png"];
            [btn  setBackgroundImage:btnImage forState:UIControlStateNormal];
        }  
      
        
       
            
         
        
        
    }else{
        _viewAutoLandingFuel.hidden = NO;
        landingFuelKg = ( landingFuelMinutes / 60) * [inputFuelFlowOverride.text floatValue];        
        landingFuelKgMinForReserve = landingFuelKg;        
        //NSLog(@"landingFuelKg %.0f ", landingFuelKg);
        //NSLog(@"_inputSpecificFuelMassPerVolume.text %@ ", _inputSpecificFuelMassPerVolume.text);
        
        if (_switchAutoLandingFuel.on == YES) {
                      
            if ([fuelEnterMode isEqualToString:@"mass"]) {
                _labelFuelEstimatedLanding.text = [ [NSString alloc] initWithFormat:@"%.0f",  landingFuelKg   ];
                _sliderFuelLanding.value = ((landingFuelKg / factorApplyToNativeFuelWeight) / [_inputSpecificFuelMassPerVolume.text floatValue]) ;                
            }else{
                _labelFuelEstimatedLanding.text = [ [NSString alloc] initWithFormat:@"%.0f",  landingFuelKg     ];
                 _sliderFuelLanding.value = landingFuelKg / factorApplyToNativeFuelVolumeGalLiter ;                
            }           
            _sliderFuelLanding.enabled = NO;  
            
        }else{            
           
            if ([fuelEnterMode isEqualToString:@"mass"]) {
                _labelFuelEstimatedLanding.text = [ [NSString alloc] initWithFormat:@"%.0f",  (_sliderFuelLanding.value *  [_inputSpecificFuelMassPerVolume.text floatValue] ) * factorApplyToNativeFuelWeight   ];
            }else{
                _labelFuelEstimatedLanding.text = [ [NSString alloc] initWithFormat:@"%.0f",  _sliderFuelLanding.value   * factorApplyToNativeFuelVolumeGalLiter   ];                
            }           
            
            landingFuelKg = [_labelFuelEstimatedLanding.text floatValue];
            _sliderFuelLanding.enabled = YES;
        }
        
          
        float reserveMinutes = (landingFuelKg /  [inputFuelFlowOverride.text floatValue]) * 60 ;
        
        //NSLog(@"landingFuelKg %.0f ", landingFuelKg);        
        //NSLog(@"reserveMinutes %.0f ", reserveMinutes);
        _labelAdditionalFuelInfoReserveTime.backgroundColor = [UIColor clearColor];
        if (reserveMinutes < [_vReserveTimeField.text floatValue]) {
            _warningIncreaseLandingFuel.hidden = NO;                 
            UIButton* btn = (UIButton*)[buttonView viewWithTag: 111 ];
            UIImage *btnImage = [UIImage imageNamed:@"button_red.png"];
            [btn  setBackgroundImage:btnImage forState:UIControlStateNormal];
            _labelAdditionalFuelInfoReserveTime.backgroundColor = [UIColor redColor];
        }   
        
        
        _labelTotalReserveTime.text = [ [NSString alloc] initWithFormat:@"%.0f", (landingFuelKg /  [inputFuelFlowOverride.text floatValue]) * 60    ];    
        _lReserveTime.text = [ [NSString alloc] initWithFormat:@"%.0f min", (landingFuelKg /  [inputFuelFlowOverride.text floatValue]) * 60    ];
    }
    
    
   
       
    float enduranceKg = [_inputFuelOnBoard.text floatValue];
    
    
   
    if ([fuelEnterMode isEqualToString:@"mass"]) {
        
       
        [_segmentUnitsForFuel setTitle:@"kg" forSegmentAtIndex:0];
        [_segmentUnitsForFuel setTitle:@"lbs" forSegmentAtIndex:1];
        
        
        if ([selectedUnitForFuel isEqualToString:@"kg"]) {
            _labelFuelCompUnitFuelOnBoard.text = @"kg";            
            _labelFuelCompUnitFuelFlow.text = @"kg/h";
            _labelFuelCompUnitLandingFuel.text = @"kg";
            _labelFuelCompUnitRequiredReserve.text = @"kg";            
        }else{
            _labelFuelCompUnitFuelOnBoard.text = @"lbs";
            _labelFuelCompUnitFuelFlow.text = @"lbs/h";
            _labelFuelCompUnitLandingFuel.text = @"lbs";
            _labelFuelCompUnitRequiredReserve.text = @"lbs";
        }
        
    }else{
        
        [_segmentUnitsForFuel setTitle:@"ltr" forSegmentAtIndex:0];
        [_segmentUnitsForFuel setTitle:@"gal" forSegmentAtIndex:1];
        
        if ([selectedUnitForFuel isEqualToString:@"kg"]) {
            _labelFuelCompUnitFuelOnBoard.text = @"ltr";
            _labelFuelCompUnitFuelFlow.text = @"ltr/h";
            _labelFuelCompUnitLandingFuel.text = @"ltr";
            _labelFuelCompUnitRequiredReserve.text = @"ltr";
        }else{
            _labelFuelCompUnitFuelOnBoard.text = @"Gal";
            _labelFuelCompUnitFuelFlow.text = @"Gal/h";
            _labelFuelCompUnitLandingFuel.text = @"Gal";
            _labelFuelCompUnitRequiredReserve.text = @"Gal";
        }
        
        
    }
    
    _labelFuelCompUnitRFuelForFlight.text = _labelFuelCompUnitFuelOnBoard.text;
    
    
    //NSLog(@"selectedUnitForFuel %@ ", selectedUnitForFuel);
    
    //NSLog(@"inputFuelFlowOverride.text %@ ", inputFuelFlowOverride.text);
    
    
    
    enduranceHours = enduranceKg / [inputFuelFlowOverride.text floatValue];
    float enduranceMinutes = (enduranceKg / [inputFuelFlowOverride.text floatValue]) * 60;
    enduranceMinutesOnly = roundf( enduranceMinutes - (enduranceHours * 60));

    if (enduranceMinutesOnly < 10) {
        _labelEnduranceHoursMinutes.text  = [ [NSString alloc] initWithFormat:@"%d:0%d", enduranceHours, enduranceMinutesOnly ];
    }else{
        _labelEnduranceHoursMinutes.text  = [ [NSString alloc] initWithFormat:@"%d:%d", enduranceHours, enduranceMinutesOnly ];               
    }
    
    float enduranceToReserveMinutes =  enduranceMinutes - [_labelTotalReserveTime.text floatValue];
    
    int minuteDifference = enduranceMinutes - [_labelTotalReserveTime.text floatValue];    
    int hours = minuteDifference / 60;
    int minutes = minuteDifference - (hours * 60);
    NSString *flightTime=  [ [NSString alloc] initWithFormat:@"%.d", minuteDifference ];
    if (minutes >= 10)                  { flightTime =  [ [NSString alloc] initWithFormat:@"%d:%.d", hours, minutes ];}
    if (minutes <= 9  & minutes > 0)    { flightTime =  [ [NSString alloc] initWithFormat:@"%d:0%.d", hours, minutes ];}
    if (minutes <= 0)                   { flightTime =  [ [NSString alloc] initWithFormat:@"%d:00", hours ];}
    
    _labelEnduranceToReserve.text  = flightTime;
    
 
    
   _labelFuelSettingsWarning.text = @"(check reserve time and/or landing fuel)";
    _labelEnduranceToReserve.backgroundColor = [UIColor clearColor];
    
     if (enduranceToReserveMinutes < [_vFlightTimeMinInput.text floatValue]) {
        _warningIncreaseLandingFuel.hidden = NO;                 
        UIButton* btn = (UIButton*)[buttonView viewWithTag: 111 ];
        UIImage *btnImage = [UIImage imageNamed:@"button_red.png"];
        [btn  setBackgroundImage:btnImage forState:UIControlStateNormal];
        _labelEnduranceToReserve.backgroundColor = [UIColor redColor];
        _labelFuelSettingsWarning.text = @"(not sufficient fuel for flight time)"; 
    }
    
    
    
    _labelAdditionalFuelInfoTotalEndurance.text = [ [NSString alloc] initWithFormat:@"%@ h", _labelEnduranceHoursMinutes.text    ]; 
    _labelAdditionalFuelInfoReserveTime.text = [ [NSString alloc] initWithFormat:@"%@ min", _labelTotalReserveTime.text  ];       
    _labelAdditionalFuelInfoAvailFlightTime.text = [ [NSString alloc] initWithFormat:@"%@ h", _labelEnduranceToReserve.text  ]; 
    
    _labelSupplyFuel.hidden = YES;
    _viewFuelPercentage.hidden = NO;
    
    if (![[_arrayName25 objectAtIndex:19] isEqualToString:@""]) {
        //need to show supply fuel label
        _labelSupplyFuel.hidden = NO;
        _viewFuelPercentage.hidden = YES;
        
        float supplyFuelVolume = [[_arrayName25 objectAtIndex:19] floatValue] * factorApplyToNativeFuelVolumeGalLiter;
        
        //NSLog(@"_sliderFuelLanding %.0f", _sliderFuelLanding.value);
        
            
        if ([selectedUnitForFuel isEqualToString:@"kg"]) {          
            if ([fuelEnterMode isEqualToString:@"mass"]) {
                _labelSupplyFuel.text = [ [NSString alloc] initWithFormat:@"Supply Fuel = %.0f kg",  (supplyFuelVolume *  [_inputSpecificFuelMassPerVolume.text floatValue] ) * factorApplyToNativeFuelWeight   ];
            }else{
                _labelSupplyFuel.text = [ [NSString alloc] initWithFormat:@"Supply Fuel = %.0f ltr",  supplyFuelVolume     ];                
            } 
            
        }else{         
            if ([fuelEnterMode isEqualToString:@"mass"]) {
                _labelSupplyFuel.text = [ [NSString alloc] initWithFormat:@"Supply Fuel = %.0f lbs",  (supplyFuelVolume /  [_inputSpecificFuelMassPerVolume.text floatValue] ) * factorApplyToNativeFuelWeight   ];
                
            }else{
                _labelSupplyFuel.text = [ [NSString alloc] initWithFormat:@"Supply Fuel = %.0f Gal",  supplyFuelVolume     ];                
            }  
            
            
        }
        
        
        
        
    }
    
    
    
    
    // warning
    if ([inputFuelFlowOverride.text floatValue] < 1) {        
        _labelEnduranceToReserve.text = @"-";
        _labelEnduranceHoursMinutes.text = @"-";
        _labelTotalReserveTime.text = @"-";
    }
    
     
    
    // end fuel computation ***************************************************************************************************************
    
     
    
    fuelTO = lFuel;
    // calc TOW
    totalWeightListo = lZFM +  lFuel ;
    totallongMomentListo = lZFMmoment +  lFuelMom;
    totalLatMomentListo = lZFMmomlat +  lFuelMomLat;
    totalArmListo = totallongMomentListo / totalWeightListo;
    totalArmLatListo = totalLatMomentListo / totalWeightListo;
    
    if (isnan(totalArmLatListo)) {
        totalArmLatListo = 0;
    }
    
    listoItemNr = lineTOW;
    [self overwriteArrays]; // TOW line
    
    
    vTOW = totalWeightListo;
    vTOWArm = totalArmListo;
    vTOWMom = totallongMomentListo;
    vTOWArmLat = totalArmLatListo;
    vTOWMomLAt = totalLatMomentListo;
    
    
    
    if (flagCreateFuelPage == 0) {
        
        // to get LDW, first get Landing Fuel
        
        
        if ([AC_Type rangeOfString:@"R44Raven"].location != NSNotFound   || [AC_Type rangeOfString:@"R44Cadet"].location != NSNotFound  || [AC_Type rangeOfString:@"R22Beta"].location != NSNotFound  ) {
       
            packageStart    = lineTOW +1;
            packageEND      = lineTOW +2; // Landing Fuel
            totalWeightListo = 0; totallongMomentListo =0; totalLatMomentListo = 0;        
            listoItemNr = lineTOW +1;        
            [self getFuelListoLanding];
            
            packageStart    = lineTOW +1;
            packageEND      = lineTOW +2; // Landing Fuel
            totalWeightListo = 0; totallongMomentListo =0; totalLatMomentListo = 0;        
            listoItemNr = lineTOW +2;        
            [self getFuelListoLanding];
            
            packageStart    = lineTOW +1;
            packageEND      = lineTOW +2; // Landing Fuel
            totalWeightListo = 0; totallongMomentListo =0; totalLatMomentListo = 0;        
            listoItemNr = lineTOW +3;        
            [self getFuelListoLanding];
        
            
            
            
        }else{
            
            // get LDW
            packageStart    = lineTOW +1;
            packageEND      = lineLDW -1; // Landing Fuel
            totalWeightListo = 0; totallongMomentListo =0; totalLatMomentListo = 0;        
            listoItemNr = lineTOW +1;        
            [self getFuelListoLanding];
            
            
        }
        
        
        
        
       
        
        
        
        
        
        
        
        
        
        
        
        lFuelLanding = totalWeightListo,  lFuelMomLanding = totallongMomentListo,  lFuelMomLatLanding = totalLatMomentListo; // this is landing Fuel
        
        fuelLD = lFuelLanding;
        
        
    }
   
    
    
    totalWeightListo = lZFM +  lFuelLanding ;
    
    totallongMomentListo = lZFMmoment +  lFuelMomLanding;
    
    totalLatMomentListo = lZFMmomlat +  lFuelMomLatLanding;
    
    totalArmListo = totallongMomentListo / totalWeightListo;
    
    totalArmLatListo = totalLatMomentListo / totalWeightListo;
    
    
    listoItemNr = lineLDW;
    
    [self overwriteArrays]; // LDW line
    
    
    
    
    vLDW = totalWeightListo;
    
    vLDWArm = totalArmListo;
    
    vLDWMom = totallongMomentListo;
    
    vLDWArmLat = totalArmLatListo;
    
    vLDWMomLAt = totalLatMomentListo;
    
    
    
    // color labels   colorlabels new color
    NSString *colorCode = @"";
     colorCode = [_arrayName21 objectAtIndex:47];
    // set seat marks
    
    flagOneDoorOff = 0;
    

    
    for (int i = 4; i < lineLDW ; i++) {
        
       //NSLog(@"item  %d %@  wgt %@  8 %@ 10 %@ 14 %@", i, [_arrayName1 objectAtIndex: i]  , [_arrayName2 objectAtIndex: i] , [_arrayName8 objectAtIndex: i]  , [_arrayName8 objectAtIndex: i]  , [_arrayName14 objectAtIndex: i]   );
        
        if ([[_arrayName10 objectAtIndex: i] isEqualToString:@"0"] || [[_arrayName10 objectAtIndex: i] isEqualToString:@""] || [[_arrayName10 objectAtIndex: i] isEqualToString:@"fuelTank"] || [[_arrayName10 objectAtIndex: i] isEqualToString:@"fuelTankTotal"]  ) {
            continue;
        }
        
        // get weight for stations
        float wgt = [[_arrayName2 objectAtIndex:i] floatValue];
        
        // check if item is a show only - not yellow green or dark
        // this is when there is an ! in arrayName10
        
        
        
         if  ( [[_arrayName14 objectAtIndex: i  ]  isEqualToString:@"door"]  ) { 
        
             if ([[_arrayName8 objectAtIndex: i  ] floatValue] > 0) { 
             
                 if ([[_arrayName2 objectAtIndex: i  ] floatValue] >= 0) {
                
                     // ON                  
                     NSString *itemName =  [ [NSString alloc] initWithFormat:@"%@%@.png", [_arrayName10 objectAtIndex: i], colorCode ];
                     UIImageView *stationImage = (UIImageView*)[_viewInterior viewWithTag: 1500 + i];
                     if ([[_arrayName10 objectAtIndex: i] length] > 1) {
                         UIImage *newImage = [UIImage imageNamed: itemName ];
                         [stationImage setImage:newImage ];
                     }  
                 }else{
               
                     NSString *itemName =  [ [NSString alloc] initWithFormat:@"%@%@.png", [_arrayName10 objectAtIndex: i], @"Dark" ];
                     UIImageView *stationImage = (UIImageView*)[_viewInterior viewWithTag: 1500 + i];
                     if ([[_arrayName10 objectAtIndex: i] length] > 1) {
                         UIImage *newImage = [UIImage imageNamed: itemName ];
                         [stationImage setImage:newImage ];                         
                     }
                     if ([[_arrayName10 objectAtIndex: i  ] rangeOfString:@"door"].location != NSNotFound   || [[_arrayName10 objectAtIndex: i  ] rangeOfString:@"Door"].location != NSNotFound  ) { 
                        
                         flagOneDoorOff = 1;
                     }
                     
                 }
                
             }else{
            
                 if ([[_arrayName2 objectAtIndex: i  ] floatValue] >= 0) {
                
                     NSString *itemName =  [ [NSString alloc] initWithFormat:@"%@%@.png", [_arrayName10 objectAtIndex: i], @"Dark" ];
                     UIImageView *stationImage = (UIImageView*)[_viewInterior viewWithTag: 1500 + i];
                     if ([[_arrayName10 objectAtIndex: i] length] > 1) {
                
                         UIImage *newImage = [UIImage imageNamed: itemName ];
                         [stationImage setImage:newImage ];
                     }
                     if ([[_arrayName10 objectAtIndex: i  ] rangeOfString:@"door"].location != NSNotFound   || [[_arrayName10 objectAtIndex: i  ] rangeOfString:@"Door"].location != NSNotFound  ) { 
                     
                         flagOneDoorOff = 1;
                     }
                     
                 }else{   
                  
                     NSString *itemName =  [ [NSString alloc] initWithFormat:@"%@%@.png", [_arrayName10 objectAtIndex: i], colorCode ];
                     UIImageView *stationImage = (UIImageView*)[_viewInterior viewWithTag: 1500 + i];
                     if ([[_arrayName10 objectAtIndex: i] length] > 1) {
                        
                         UIImage *newImage = [UIImage imageNamed: itemName ];
                         [stationImage setImage:newImage ];
                     }
                 }
             }
             
             
         }else{
             
             if ([[_arrayName10 objectAtIndex: i  ] rangeOfString:@"!"].location != NSNotFound    ) {
                 
                 int imageInOut = 0;
                 
                 if ([[_arrayName8 objectAtIndex: i  ] floatValue] > 0) {
                     imageInOut = 1; 
                 }                 
                 if ([[_arrayName8 objectAtIndex: i  ] floatValue] < 1 && [[_arrayName14 objectAtIndex: i  ]isEqualToString:@"showWhenOff"]) {
                     imageInOut = 1;                     
                 }
                 if ([[_arrayName8 objectAtIndex: i  ] floatValue] > 0 && [[_arrayName14 objectAtIndex: i  ]isEqualToString:@"showWhenOff"]) {
                     imageInOut = 0;
                 }
                 
                 //NSLog(@" %@ imageInOut  %d", [_arrayName8 objectAtIndex: i], imageInOut);                 
                 
                 
                 
                 
                
                 
               
                 
                 if (imageInOut == 1) {
                     
                     NSString *imageName =  [ [_arrayName10 objectAtIndex: i  ] stringByReplacingOccurrencesOfString:@"!" withString:@""];
                     if ([imageName rangeOfString:@"exi_"].location != NSNotFound    ) {
                         //NSLog(@"we need to load this image:  %@",  imageName);  
                         NSString *imageToLoad = [NSString stringWithFormat:@"%@", imageName ];
                         NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
                         NSString *documentsDirectory = [paths objectAtIndex:0];

                         NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:imageToLoad];
                         UIImage *imageLoaded = [UIImage imageWithContentsOfFile:getImagePath];  
                         UIImageView *stationImage = (UIImageView*)[_viewInterior viewWithTag: 1500 + i];
                         [stationImage setImage: imageLoaded  ];
                         
                     }else{
                      //we have this image on file  
                         NSString *itemName =  [ [NSString alloc] initWithFormat:@"%@.png", imageName  ];
                         UIImageView *stationImage = (UIImageView*)[_viewInterior viewWithTag: 1500 + i];
                         UIImage *newImage = [UIImage imageNamed: itemName ];
                         [stationImage setImage:newImage ];                         
                     }
                   
                     
                 }else{
                     
                     UIImageView *stationImage = (UIImageView*)[_viewInterior viewWithTag: 1500 + i];
                     if ([[_arrayName10 objectAtIndex: i] length] > 1) {
                         UIImage *newImage = [UIImage imageNamed: @"empty.png" ];
                         [stationImage setImage:newImage ];
                         //NSLog(@"set empty i %d", i );
                     }
                 }
                 
             }else{
                 
                 //select item name plus color dark, green, yelllow
                 if (wgt > 0) {
                     NSString *itemName =  [ [NSString alloc] initWithFormat:@"%@%@.png", [_arrayName10 objectAtIndex: i], colorCode ];
                     UIImageView *stationImage = (UIImageView*)[_viewInterior viewWithTag: 1500 + i];
                     
                     if ([[_arrayName10 objectAtIndex: i] length] > 1) {
                         UIImage *newImage = [UIImage imageNamed: itemName ];
                         
                         [stationImage setImage:newImage ];
                     }
                 }else{
                     NSString *itemName ;
                     if ([[_arrayName16 objectAtIndex: i  ]isEqualToString:@"standby"] & [[_arrayName8 objectAtIndex: i  ]isEqualToString:@"0"]) {
                         itemName =  [ [NSString alloc] initWithFormat:@"%@.png", [_arrayName16 objectAtIndex: i] ];
                     }else{
                         itemName =  [ [NSString alloc] initWithFormat:@"%@%@.png", [_arrayName10 objectAtIndex: i], @"Dark" ];
                     }
                     
                     UIImageView *stationImage = (UIImageView*)[_viewInterior viewWithTag: 1500 + i];
                     if ([[_arrayName10 objectAtIndex: i] length] > 1) {
                         UIImage *newImage = [UIImage imageNamed: itemName ];
                         [stationImage setImage:newImage ];
                     }
                 }
                 
                 
             }
             
         }
        
       
    }// end for next
    
    
    
    //NSLog(@"flagOneDoorOff %d", flagOneDoorOff);
    
    [self checkGuidance];
    /*
     if (_segmentFlightLegMode.selectedSegmentIndex == 0) {
     _labelFlightLegID.text =  [ [NSString alloc] initWithFormat:@"Flight: %@ / %u", vFlightID, allFlightsMasterArray.count -1 ];
     _labelFlightLegID2.text = [ [NSString alloc] initWithFormat:@"%@/%u", vFlightID, allFlightsMasterArray.count -1 ];
     
     }else{
     _labelFlightLegID.text =  [ [NSString alloc] initWithFormat:@"Flight: %@ / Leg: %@ of %u", vFlightID, vLegID,  allLegsPerFlightArray.count-1 ];
     _labelFlightLegID2.text =  [ [NSString alloc] initWithFormat:@"Flight: %@ / Leg: %@ of %u", vFlightID, vLegID,  allLegsPerFlightArray.count-1 ];
     
     }
     */
    
    _labelFlightLegID.text =  [ [NSString alloc] initWithFormat:@"Flight: %@ / %lu", vFlightID, allFlightsMasterArray.count -1 ];
    _labelFlightLegID2.text = [ [NSString alloc] initWithFormat:@"%@/%lu - %@", vFlightID, allFlightsMasterArray.count -1, vFlightRegistration.text ];    
    _labelFlightID.text = [ [NSString alloc] initWithFormat:@"%@", vFlightID ];
    
    
    // crosses *************************************
    
    CGLongTOW = vTOWArm ;    
    CGLongZFW =  lZFWArm ;    
    CGLongLDW =  vLDWMom / vLDW  ;
    weightTOW = vTOW ;    
    weightZFW = lZFW ;    
    weightLDW = vLDW  ;
    CGLATTOW = vTOWArmLat ;
    CGLATZFW = lZFWArmLat  ;
    CGLATLDW =  vLDWMomLAt / vLDW ;
    
    // animate crosses   and CG ball    
    [self setACImage: 0];
    
    
    [self animateFuelPathAndCheckCG];
    
    if (flagLATinputH130 ==1) {        
        [self animateFuelPathLateralAndCheckCGH130];        
    }else{        
        [self animateFuelPathLateralAndCheckCG];
    }
    
    
    [self animateCrossTOW]; [self animateCrossTOWforMail];    
    [self animateCrossZFW]; [self animateCrossZFWforMail];    
    [self animateCrossLDW]; [self animateCrossLDWforMail];
    [self animateCrossLAT]; [self animateCrossLATforMail];
    [self animateCrossLATLDW]; [self animateCrossLATforMail_LDW];
    [self animateCrossLATZFW]; [self animateCrossLATforMail_ZFW];
    
    if (flagLATinputH130 == 1) {        
        _crossLatZFW.hidden = YES; _crossMailLATZFW.hidden = YES;        
        //_crossLatLDW.hidden = YES; _crossMailLATLDW.hidden = YES;
    }else{
        _crossLatZFW.hidden = NO; _crossMailLATZFW.hidden = NO;
        _crossLatLDW.hidden = NO; _crossMailLATLDW.hidden = NO;
    }
    
    
    lineRelevantForExternalLoad = 0;
    _labelAvailableExternalLoad.hidden = YES;
    _label2AvailableExternalLoad.hidden = YES;
    
    
    //[_arrayName23 objectAtIndex:29] = Calc max External/Hoist
    
   
    if ([[_arrayName23 objectAtIndex:29] isEqualToString:@"yes"] ) {   
        //NSLog(@"1 _arrayName23 %@", [_arrayName23 objectAtIndex:29]);
        //NSLog(@"1 [_arrayName25 objectAtIndex:27] %@", [_arrayName25 objectAtIndex:27]);
       
        // search for item name 
        for (int i = 3; i < _arrayName1.count-3 ; i++) { 
            //NSLog(@"[_arrayName25 objectAtIndex:27] %@", [_arrayName25 objectAtIndex:27]);
             //NSLog(@"[_arrayName1 objectAtIndex:i] %@", [_arrayName1 objectAtIndex:i]);            
            // check "Depends on Display Button"            
            //NSLog(@"[_arrayName25 objectAtIndex:27] %@", [_arrayName25 objectAtIndex:27]);
            //depends on display button
            if ([[_arrayName25 objectAtIndex:27] isEqualToString:[_arrayName1 objectAtIndex:i]]) { 
                lineRelevantForExternalLoad = i;                
                 //NSLog(@"found lineRelevantForExternalLoad %d", lineRelevantForExternalLoad);
                break;
            }
        }
        
        //NSLog(@"lineRelevantForExternalLoad %d", lineRelevantForExternalLoad);
        if ([[_arrayName8 objectAtIndex:lineRelevantForExternalLoad] floatValue] > 0) {
            //NSLog(@"lineRelevantForExternalLoad %d", lineRelevantForExternalLoad);  
            _labelAvailableExternalLoad.hidden = NO;
            maxExternalLoadString = [_arrayName25 objectAtIndex:27];
            //NSLog(@"maxExternalLoadString %@", maxExternalLoadString);  
            maxHoistLoad = [[_arrayName9 objectAtIndex:lineRelevantForExternalLoad] floatValue];
            //NSLog(@"maxHoistLoad %.0f", maxHoistLoad); 
            [self findMaxEnternalLoad];
        } 
    }
    
   
    
    
  
    // hungarian air ambulance (via excel only)    
    if (![[_arrayName23 objectAtIndex:29] isEqualToString:@""] & ![[_arrayName23 objectAtIndex:29] isEqualToString:@"yes"] ) { 
        lineRelevantForExternalLoad = [[_arrayName23 objectAtIndex:29] intValue];             
        if ([[_arrayName8 objectAtIndex:lineRelevantForExternalLoad] floatValue] > 0) { 
            _labelAvailableExternalLoad.hidden = NO;
            maxExternalLoadString = [_arrayName23 objectAtIndex:30];
            maxHoistLoad = [[_arrayName9 objectAtIndex:lineRelevantForExternalLoad] floatValue];
            [self calcMaxEnternalLoad];
        }
    }
    
   
    
   
    
    
    
    // do a pax count
    int paxCount = 0;
    int lineToStart = 0;
     lineToStart = [[_arrayName23 objectAtIndex:11] floatValue];
    
    
    for (int i = lineToStart; i < _arrayName10.count ; i++) {
        if ( [[_arrayName10 objectAtIndex:i] isEqualToString:@"seat"] ) {
            if ( [[_arrayName2 objectAtIndex:i]floatValue] > 0  ) { // if it has weight
                if ( [[_arrayName8 objectAtIndex:i]floatValue] > 0  ) { // it is is in
                    paxCount = paxCount + 1;
                }
            }
        }
    }
    
    _inputPaxOnBoard.text = [ [NSString alloc] initWithFormat:@"%d", paxCount];
    //NSLog(@"paxCount %d", paxCount);
    
    
    
    
    
    
    return;
    
    
    
}


















-(void)WeightSliderAction:(id)sender{
    
    UISlider *slider = (UISlider*)sender;  
    float dummyFactor = [_inputSliderIncrement.text doubleValue] /factorApplyToNativeWeightforItems; 
    
    if ((slider.maximumValue - dummyFactor) < slider.value  ) {
        dummyFactor = 1;
    }
    
    int dummy = slider.value/dummyFactor ;    
    slider.value = dummy * dummyFactor;
    
    //NSLog (@"_inputSliderIncrement.text %@ ", _inputSliderIncrement.text);
    weightValue = slider.value;    
    
    //NSLog (@"slider.tag %@ ", [ [NSString alloc] initWithFormat:@"%ld ", (long)slider.tag]);
    //NSLog (@"weightValue %f ", weightValue);    
    [self setSliderValues:weightValue tagValue:slider.tag];    
    if (slider.value < 1) {
        
        // check if this is a fuel slider
        if ([[_arrayName10 objectAtIndex: slider.tag  ] rangeOfString:@"fuelTank"].location != NSNotFound  ) {
            valueField = (UITextField*)[_viewFuelSliders viewWithTag: 1200+ slider.tag];
            //NSLog (@"weightValue %f ", weightValue); 
            
        }else{
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200+ slider.tag];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200 + slider.tag];
            }
            [valueField  setText: @"-"  ];
            [_arrayName7 replaceObjectAtIndex:slider.tag withObject:@"-"];  
        }        
             
    }    
    [self MainRoutine];
    
}

- (void) setSliderValues:  (float)sliderWeightValue  tagValue:(float)sliderTag {
    
    //NSLog(@"setSliderValues");
    
    // update weight label 1000
    
    // check if this is a fuel slider
    if ([[_arrayName10 objectAtIndex: sliderTag  ] rangeOfString:@"fuelTank"].location != NSNotFound  ) {
        valueField = (UITextField*)[_viewFuelSliders viewWithTag: 1000 + sliderTag];
        
        // if mass, then convert the label from volume to mass
        if ([fuelEnterMode isEqualToString:@"mass"]) {
             [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", sliderWeightValue * factorApplyToNativeFuelWeight  ]];            
        }else{
            [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", sliderWeightValue / [_inputSpecificFuelMassPerVolume.text floatValue] * factorApplyToNativeFuelVolumeGalLiter  ]];
        }
        
    }else{
        valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1000 + sliderTag];
        if (valueField == nil) {
            valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1000 + sliderTag];
        }
        
        [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", sliderWeightValue * factorApplyToNativeWeightforItems]  ];
    }
    
    
   
    
    
    
    
    if (sliderWeightValue >= 1000) {
        valueField.font = [UIFont boldSystemFontOfSize:13.0];
    }else{
        valueField.font = [UIFont boldSystemFontOfSize:15.0];
    }
    
    
    //label.font = [UIFont boldSystemFontOfSize:17.0];
    
    totalWeightListo = sliderWeightValue;
    
    totalArmListo = [[_arrayName3 objectAtIndex:sliderTag] floatValue];
    
    totallongMomentListo = totalWeightListo * totalArmListo;
    
    totalArmLatListo = [[_arrayName5 objectAtIndex:sliderTag] floatValue];
    
    totalLatMomentListo  = totalWeightListo * totalArmLatListo;
    
    listoItemNr = sliderTag;
    
    [self overwriteArrays];
    
    
    return;
    
    
    
    
}





// enter weights ************************************************************************************************


-(void)actionTapOnStation :(id)sender{
    
    
    
    guidanceDictionary[@"guidanceBtnCrew"] =  @"ok";
    guidanceDictionary[@"guidanceBtnDispatch"] =  @"ok";
    
    UIButton *btn = (UIButton*)sender;
    buttonIDtransfer = btn.tag;
    
    //NSLog(@"buttonIDtransfer %d", buttonIDtransfer);
    //NSLog(@"actionTapOnStation buttonIDtransfer %d", buttonIDtransfer);
    //NSLog(@"_arrayName10 %@", [_arrayName10 objectAtIndex:buttonIDtransfer - 1600]);
    
    if (_viewPilotList.hidden == NO) {
        [self actionEnterViaCrewListWhileOpen: btn.tag];
        
    }else{ 
       
        if (_segmentSeatLoadOptions.selectedSegmentIndex == 0) { 
          
            // quick load
            if ([[_arrayName14 objectAtIndex: btn.tag -1600 ] rangeOfString:@"picAndLabelLocked"].location != NSNotFound) {                
                //do not do quickload  
                 
                return;
            }else{    
               
                [self actionEnterViaQuickLoad: btn.tag];
            }
        }
        
        if (_segmentSeatLoadOptions.selectedSegmentIndex == 1) {   
         
            // crew list           
                if ([[_arrayName10 objectAtIndex:buttonIDtransfer - 1600] rangeOfString:@"seat"].location != NSNotFound  ) {
              
                [self actionEnterViaCrewList];
            }else{   
                
                //[self actionEnterViaCrewListDirectStationInput];
                selectedItem = 40;
                calculatorscreen.text = @"" ; EnterPadString = @"";
                enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;
               
            }
        }
    }
    
     [self MainRoutine];
    
}

-(void)actionEnterViaCrewListWhileOpen: (float)buttonTag {
    
    //NSLog(@"actionEnterViaCrewListWhileOpen");  
    
    flagEnterCrewListMode = 0; // tap a station to open crew list and select just one item
    
    weightValue = 0;
    
    if (_viewPilotList.hidden == NO & CrewDataLoaded == 1) {
        //NSLog(@"1 actionEnterViaCrewListWhileOpen");
        NSIndexPath *selectedPath = [self.tableView indexPathForSelectedRow];
        _labelPilotCheck.text = [self nameForRow:selectedPath.row AndSection:selectedPath.section];        
        selectedPathTransfer = selectedPath;        
        if ( selectedPath != nil){            
            //NSLog(@"2 actionEnterViaCrewListWhileOpen");
            NSString *nameOnly = [self nameForRow:selectedPath.row AndSection:selectedPath.section];
            //NSLog(@"name from crew list %@", nameOnly);            
            float s1 = [[self weightForRow:selectedPath.row AndSection:selectedPath.section] doubleValue];            
            //NSLog(@"unitsWeight.tex %@", unitsWeight.text);
         
            if ([unitsWeight.text isEqualToString:@"kg"] & [loadedBEWUnits isEqualToString:@"kg"] ) {
                weightValue = s1;               
            }            
            if ([unitsWeight.text isEqualToString:@"lbs"] & [loadedBEWUnits isEqualToString:@"lbs"] ) {
                weightValue = s1;               
            }            
            if ([unitsWeight.text isEqualToString:@"kg"] & [loadedBEWUnits isEqualToString:@"lbs"] ) {
                weightValue = s1/ 2.20462 ;               
            }            
            if ([unitsWeight.text isEqualToString:@"lbs"] & [loadedBEWUnits isEqualToString:@"kg"] ) {
                weightValue = s1 * 2.20462 ;               
            }   
            if ( [[_arrayName25 objectAtIndex:15] floatValue] !=0 ) {
                weightValue = s1 * [[_arrayName25 objectAtIndex:15] floatValue];
                // swift crew weight trick               
            }  
            // set name in list and on slider            
            [_arrayName7 replaceObjectAtIndex:buttonTag- 1600 withObject:nameOnly];            
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200+ buttonTag- 1600];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200+ buttonTag- 1600];
            }            
            [valueField  setText: nameOnly ];            
            //NSLog(@"name from crew list %d", btn.tag);
            
        }else{
            
            weightValue = 0;            
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200+ buttonTag- 1600];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200+ buttonTag- 1600];
            }            
            [valueField  setText: @"-"  ];            
            [_arrayName7 replaceObjectAtIndex:buttonTag- 1600 withObject:@"-"];            
            _viewPilotList.hidden = YES;            
        }
        [self updateSlider: buttonTag];
        
    }
    
    
    
    
}

- (IBAction)actionClearSeat:(id)sender {
    
    if (flagEnterCrewListMode == 2) {
        
        flagEnterCrewListMode = 0;
        
        weightValue = 0;
        
        valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200+ buttonIDtransfer- 1600];
        if (valueField == nil) {
            valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200+ buttonIDtransfer- 1600];
        }
        
        [valueField  setText: @"-"  ];
        
        [_arrayName7 replaceObjectAtIndex:buttonIDtransfer- 1600 withObject:@"-"];
        
        
        [self updateSlider: buttonIDtransfer];
        
        _viewPilotList.hidden = YES;

        
    }
    
    
    
}

- (IBAction)actionEnterRideAlong:(id)sender {
    
    
    _inputSeatWeight.keyboardType = UIKeyboardTypeNumberPad;
    _inputSeatMaxWeight.keyboardType = UIKeyboardTypeNumberPad;   
    _inputInstalledWeight.keyboardType = UIKeyboardTypeNumberPad; 
    _inputSeatName.keyboardType = UIKeyboardTypeDefault;    
    _inputSeatName.autocorrectionType = UITextAutocorrectionTypeNo;    
    _inputSeatName.autocapitalizationType = UITextAutocapitalizationTypeWords;
    
    
    
    
    rideAlongSeat = buttonIDtransfer -300;
    
    
    //NSLog (@"buttonIDtransfer %@ ", [ [NSString alloc] initWithFormat:@"%d ", buttonIDtransfer]);
    
    
    _inputSeatName.text =@""; _inputSeatWeight.text =@""; _inputSeatMaxWeight.text =@""; _inputInstalledWeight.text =@"";
    
    _viewSeatOptions.hidden = NO;
    
    [_viewPilotList bringSubviewToFront:_viewSeatOptions];
    
    
}





-(void)actionEnterViaQuickLoad:(float)buttonTag{    
   //NSLog(@"use quick load ");    
    // use Quick Load:
    
    float fieldWeight = [[_arrayName2 objectAtIndex:buttonTag - 1600] floatValue];
    
    if (fieldWeight >0) {
        
        weightValue = 0;
        
        valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200+ buttonTag- 1600];
        if (valueField == nil) {
            valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200+ buttonTag- 1600];
        }
        
        [valueField  setText: @"-"  ];
        
        [_arrayName7 replaceObjectAtIndex:buttonTag- 1600 withObject:@"-"];
        
        
    }else{
        weightValue = [_inputQuickLoadPreset.text  doubleValue] / factorApplyToNativeWeightforItems;
        
         //individual quick load
        
            if ([[_arrayName18 objectAtIndex: buttonTag-1600 ] rangeOfString:@"quick"].location != NSNotFound  ) {
                
                weightValue = [[_arrayName18 objectAtIndex: buttonTag -1600 ]  doubleValue] ;
                
                //NSLog(@"weight value %.0f", weightValue);
        }
        
        
        
        //NSLog(@"weight value %.0f", [_inputQuickLoadPreset.text  doubleValue]);
        
         //NSLog(@"[_arrayName9 objectAtIndex:buttonTag - 1600] floatValue]%.0f", [[_arrayName9 objectAtIndex:buttonTag - 1600] floatValue]);
        
        if (weightValue > [[_arrayName9 objectAtIndex:buttonTag - 1600] floatValue] ) {
            weightValue = [[_arrayName9 objectAtIndex:buttonTag - 1600] floatValue];
        }
        
    }
    
    
    [self updateSlider: buttonTag];
    
    
    
    
}


- (void) updateSlider: (int)buttonTag {
    
    //NSLog(@"updateSlider");
    
    buttonTag = buttonTag- 1600;
    
    totalWeightListo = weightValue;
    
    totalArmListo = [[_arrayName3 objectAtIndex:buttonTag] floatValue];
    
    totallongMomentListo = totalWeightListo * totalArmListo;
    
    totalArmLatListo = [[_arrayName5 objectAtIndex:buttonTag] floatValue];
    
    totalLatMomentListo  = totalWeightListo * totalArmLatListo;
    
    listoItemNr = buttonTag;
    
    [self overwriteArrays];
    
    
    // update weight label 1000
    
    valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1000 + buttonTag];
    if (valueField == nil) {
        valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1000 + buttonTag];
    }
    
    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", weightValue * factorApplyToNativeWeightforItems]  ];
    
    
    
    // update slider
    
    UISlider *slider = (UISlider*)[_viewStationsSlider viewWithTag:  buttonTag];
    if (!slider) {
        slider = (UISlider*)[_viewStationsSliderRight viewWithTag:  buttonTag];
    }
    
    slider.value = weightValue;
    
    [self MainRoutine];
    
    
    
    
    
}


-(void)actionEnterViaCrewListDirectStationInput {
    
    
    flagEnterCrewListMode = 2; // tap a station to open crew list and select just one item
    
    _inputSeatWeight.keyboardType = UIKeyboardTypeNumberPad;
    
    _inputSeatName.keyboardType = UIKeyboardTypeDefault;
    
    _inputSeatName.autocorrectionType = UITextAutocorrectionTypeNo;
    
    _inputSeatName.autocapitalizationType = UITextAutocapitalizationTypeWords;
    
    rideAlongSeat = buttonIDtransfer -300;
    
    //NSLog (@"btn.tag %.0f ", buttonIDtransfer);
    
    _inputSeatName.text =@""; _inputSeatWeight.text =@"";
    
    _viewPilotList.hidden = NO;
    [viewOne bringSubviewToFront:_viewPilotList];   [viewOne bringSubviewToFront:viewTopTop];
    
    _viewSeatOptions.hidden = NO;
    
    [_viewPilotList bringSubviewToFront:_viewSeatOptions];
    
    [_inputSeatWeight becomeFirstResponder];

    
}

-(void)actionEnterViaCrewList {
    
     //NSLog(@"actionEnterViaCrewList");    
    flagEnterCrewListMode = 2; // tap a station to open crew list and select just one item    
     _viewPilotList.hidden = NO;
    [viewOne bringSubviewToFront:_viewPilotList];   [viewOne bringSubviewToFront:viewTopTop];
    _viewSeatOptions.hidden = YES;
    
    
}





- (void) loadSeatFromCrewList {
    
    flagEnterCrewListMode = 0;
    
  
    
    NSIndexPath *selectedPath = [self.tableView indexPathForSelectedRow];
    _labelPilotCheck.text = [self nameForRow:selectedPath.row AndSection:selectedPath.section];

    
    //EMPnumber
    
    if ( selectedPath != nil){
        
        NSString *nameOnly = [self nameForRow:selectedPath.row AndSection:selectedPath.section];
        
        if (flagSpecialPHIFlightSettingPage == 1) {
            nameOnly = [ [NSString alloc] initWithFormat:@"%@ #%@", [self nameForRow:selectedPath.row AndSection:selectedPath.section], [self EMPnumber:selectedPath.row AndSection:selectedPath.section]  ];
        }
        
       
        
        float s1 = [[self weightForRow:selectedPath.row AndSection:selectedPath.section] doubleValue];       
       
        
        if ([unitsWeight.text isEqualToString:@"kg"] & [loadedBEWUnits isEqualToString:@"kg"] ) {
            weightValue = s1;
        }
        
        if ([unitsWeight.text isEqualToString:@"lbs"] & [loadedBEWUnits isEqualToString:@"lbs"] ) {
            weightValue = s1;
        }
        
        if ([unitsWeight.text isEqualToString:@"kg"] & [loadedBEWUnits isEqualToString:@"lbs"] ) {
            weightValue = s1/ 2.20462 ;
        }
        
        if ([unitsWeight.text isEqualToString:@"lbs"] & [loadedBEWUnits isEqualToString:@"kg"] ) {
            weightValue = s1 * 2.20462 ;
        }
        
        
        // set name in list and on slider
        
        [_arrayName7 replaceObjectAtIndex:buttonIDtransfer- 1600 withObject:nameOnly];
        
        
        valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200+ buttonIDtransfer- 1600];
        if (valueField == nil) {
            valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200+ buttonIDtransfer- 1600];
        }

        
        [valueField  setText: nameOnly ];
        
        //NSLog(@"name from crew list %d", btn.tag);
        
        
        
     }
    
    _viewPilotList.hidden = YES;
    
    [self updateSlider: buttonIDtransfer];
  

}







-(void)buttonActionEnterRideAlong:(id)sender{
    
    //NSLog (@"buttonActionEnterRideAlong ");    
    UIButton *btn = (UIButton*)sender;    
    rideAlongSeat = [btn tag];    
    if (_viewPilotList.hidden == NO & CrewDataLoaded == 1) {
        //NSLog (@"1 ");        
        NSIndexPath *selectedPath = [self.tableView indexPathForSelectedRow];
        _labelPilotCheck.text = [self nameForRow:selectedPath.row AndSection:selectedPath.section];
        selectedPathTransfer = selectedPath;        
        if ( selectedPath != nil){
            NSString *nameOnly = [self nameForRow:selectedPath.row AndSection:selectedPath.section];
            //NSLog(@"name from crew list %@", nameOnly);
            float s1 = [[self weightForRow:selectedPath.row AndSection:selectedPath.section] doubleValue];
            weightValue = s1;
            if ([unitsWeight.text isEqualToString:@"kg"] & [loadedBEWUnits isEqualToString:@"kg"] ) {
                weightValue = s1;
            }            
            if ([unitsWeight.text isEqualToString:@"lbs"] & [loadedBEWUnits isEqualToString:@"lbs"] ) {
                weightValue = s1;
            }            
            if ([unitsWeight.text isEqualToString:@"kg"] & [loadedBEWUnits isEqualToString:@"lbs"] ) {
                weightValue = s1/ 2.20462 ;
            }            
            if ([unitsWeight.text isEqualToString:@"lbs"] & [loadedBEWUnits isEqualToString:@"kg"] ) {
                weightValue = s1 * 2.20462 ;
            } 
            
            
            //NSLog(@"[_arrayName25 objectAtIndex:15] %@", [_arrayName25 objectAtIndex:15] );            
            if ( [[_arrayName25 objectAtIndex:15] floatValue] !=0 ) {
                weightValue = s1 * [[_arrayName25 objectAtIndex:15] floatValue];
                // swift crew weight trick               
            }
            
            
            // set name in list and on slider
            [_arrayName7 replaceObjectAtIndex:rideAlongSeat- 1300 withObject:nameOnly];
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200+ rideAlongSeat- 1300];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200+ rideAlongSeat- 1300];
            }
            [valueField  setText: nameOnly ];
            //NSLog(@"btn.tagt %d", btn.tag);
        }else{
            //NSLog(@"nil actionEnterViaCrewListWhileOpen");
            weightValue = 0;
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200+ rideAlongSeat- 1300];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200+ rideAlongSeat- 1300];
            }
            [valueField  setText: @"-"  ];
            [_arrayName7 replaceObjectAtIndex:rideAlongSeat- 1300 withObject:@"-"];
            _viewPilotList.hidden = YES;
        }
        [self updateSlider: rideAlongSeat-1300 + 1600];
        
    }else{
              
        _inputSeatWeight.keyboardType = UIKeyboardTypeNumberPad;
        _inputSeatMaxWeight.keyboardType = UIKeyboardTypeNumberPad;
        _inputInstalledWeight.keyboardType = UIKeyboardTypeNumberPad;
        _inputSeatName.keyboardType = UIKeyboardTypeDefault;
        _inputSeatName.autocorrectionType = UITextAutocorrectionTypeNo;
        _inputSeatName.autocapitalizationType = UITextAutocapitalizationTypeWords; 
        
        
        if (rideAlongSeat - 1300 == lineFreeLoad) {        
            
        }else{
           
        }        
        
        [self setRideAlongValues];
    }
    
}

- (IBAction)closeKeyboardSaveSeatOptions:(id)sender {

     [self saveSeatOptions];
}

- (IBAction)buttonActionSaveSeatOptions:(id)sender {
    
    [self saveSeatOptions];
    
}

- (void) saveSeatOptions {
    

      [self.view endEditing:TRUE];
     
      
      //NSLog(@"rideAlongSeatt %.0f", rideAlongSeat );
      
      
      
      if (rideAlongSeat - 1300 == lineFreeLoad) {
          [_arrayName3 replaceObjectAtIndex:lineFreeLoad withObject:_inputSeatArmLong.text];
          [_arrayName5 replaceObjectAtIndex:lineFreeLoad withObject:_inputSeatArmLat.text];
          //_inputSeatName.text = [ [NSString alloc] initWithFormat:@"@ %@", _inputSeatArmLong.text  ];
          [self createListoItemsSlidersAndInterior];
      }
      

      //NSLog(@"rideAlongSeat %.0f ", rideAlongSeat);
      
      float previousLongArm = [[_arrayName3 objectAtIndex:rideAlongSeat - 1300]floatValue]  +  [[_arrayName5 objectAtIndex:rideAlongSeat - 1300] floatValue]   +  [[_arrayName9 objectAtIndex:rideAlongSeat - 1300] floatValue];
      
      if (![previousSeatName isEqualToString:_inputSeatName.text]) {
          //NSLog(@"changing seat name ");
          previousLongArm = previousLongArm + 1;
          if ([[_arrayName14 objectAtIndex:rideAlongSeat - 1300]isEqualToString:@"-"] ) {
              [_arrayName7 replaceObjectAtIndex:rideAlongSeat - 1300 withObject:_inputSeatName.text];
              valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200+ rideAlongSeat - 1300];
              if (valueField == nil) {
                  valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200+ rideAlongSeat - 1300];
              }
              [valueField  setText: _inputSeatName.text ]; 
          }else{
              [_arrayName12 replaceObjectAtIndex:rideAlongSeat - 1300 withObject:_inputSeatName.text];
              [_arrayName1 replaceObjectAtIndex:rideAlongSeat - 1300 withObject:_inputSeatName.text];
                    
          }
      }
      
      
      _viewPilotList.hidden = YES;
      
      NSString *correctedSeatWeight;
      NSString *correctedSeatMaxWeight;
      NSString *correctedLongArm;
      NSString *correctedLatArm;
      NSString *correctedInstallationWeight;
      //this is the weight for the array, the actual unit
      
    
      if ([selectedUnitForItems isEqualToString: unitsWeight.text]  ) {
          correctedSeatWeight =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputSeatWeight.text floatValue]];
          correctedSeatMaxWeight =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputSeatMaxWeight.text floatValue]];
          correctedLongArm =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputSeatArmLong.text floatValue]];
          correctedLatArm =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputSeatArmLat.text floatValue]];
          correctedInstallationWeight =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputInstalledWeight.text floatValue]];
      }
      
      if ([selectedUnitForItems isEqualToString:@"kg"] && [unitsWeight.text isEqualToString:@"lbs"] ) {
          correctedSeatWeight =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputSeatWeight.text floatValue] * 2.2046];
          correctedSeatMaxWeight =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputSeatMaxWeight.text floatValue]  * 2.2046 ];
          correctedLongArm =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputSeatArmLong.text floatValue] / factorApplyToNativeDistanceInchMM ];
          correctedLatArm=  [ [NSString alloc] initWithFormat:@"%.1f", [_inputSeatArmLat.text floatValue] / factorApplyToNativeDistanceInchMM ];
          correctedInstallationWeight =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputInstalledWeight.text floatValue]  * 2.2046];
           
      }
      
      if ([selectedUnitForItems isEqualToString:@"lbs"] && [unitsWeight.text isEqualToString:@"kg"] ) {
          correctedSeatWeight =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputSeatWeight.text floatValue] / 2.2046];
          correctedSeatMaxWeight =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputSeatMaxWeight.text floatValue]  / 2.2046 ];
          correctedLongArm =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputSeatArmLong.text floatValue] / factorApplyToNativeDistanceInchMM ];
          correctedLatArm =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputSeatArmLat.text floatValue] / factorApplyToNativeDistanceInchMM ];
          correctedInstallationWeight =  [ [NSString alloc] initWithFormat:@"%.1f", [_inputInstalledWeight.text floatValue] / 2.2046];
      }
      
      //NSLog(@"[_arrayName3 objectAtIndex: rideAlongSeat - 1300] %@", [_arrayName3 objectAtIndex: rideAlongSeat - 1300]);    
      //NSLog(@"correctedLongArm %@", correctedLongArm);
      
      [_arrayName9 replaceObjectAtIndex:rideAlongSeat - 1300 withObject: correctedSeatMaxWeight];
      [_arrayName17 replaceObjectAtIndex:rideAlongSeat - 1300 withObject: correctedInstallationWeight];
      [_arrayName3 replaceObjectAtIndex:rideAlongSeat - 1300 withObject: correctedLongArm];
      [_arrayName5 replaceObjectAtIndex:rideAlongSeat - 1300 withObject: correctedLatArm];
      
      
      //NSLog(@"2 [[_arrayName9 objectAtIndex:rideAlongSeat - 1300] floatValue] %.0f",  [[_arrayName9 objectAtIndex:rideAlongSeat - 1300] floatValue]);
      
       float newLongArm = [[_arrayName3 objectAtIndex:rideAlongSeat - 1300]floatValue]  +  [[_arrayName5 objectAtIndex:rideAlongSeat - 1300] floatValue]   +  [[_arrayName9 objectAtIndex:rideAlongSeat - 1300] floatValue];
      
       //NSLog(@"1 previousLongArm %.0f",previousLongArm);
       //NSLog(@"2 newLongArm %.0f",newLongArm);
      
          
      //NSLog(@"correctedSeatWeight %@", correctedSeatWeight);
      
      [_arrayName2 replaceObjectAtIndex:rideAlongSeat - 1300 withObject: correctedSeatWeight]; // weight
       //NSLog(@"_inputSeatWeight.text %@", _inputSeatWeight.text );
      
      // update weight label 1000
      valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1000 + rideAlongSeat - 1300];
      if (valueField == nil) {
          valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1000 + rideAlongSeat - 1300];
      }
      [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [_inputSeatWeight.text floatValue]]  ];
      
      // update slider
      UISlider *slider = (UISlider*)[_viewStationsSlider viewWithTag:  rideAlongSeat - 1300];
      if (!slider) {
          slider = (UISlider*)[_viewStationsSliderRight viewWithTag:  rideAlongSeat - 1300];
      }
      slider.value = [correctedSeatWeight floatValue];
      totalWeightListo = [correctedSeatWeight floatValue];
      totalArmListo = [[_arrayName3 objectAtIndex:rideAlongSeat - 1300] floatValue];
      totallongMomentListo = totalWeightListo * totalArmListo;
      totalArmLatListo = [[_arrayName5 objectAtIndex:rideAlongSeat - 1300] floatValue];
      totalLatMomentListo  = totalWeightListo * totalArmLatListo;
      listoItemNr = rideAlongSeat - 1300;
      [self overwriteArrays]; 
      
      if (newLongArm != previousLongArm) {
          //NSLog(@"createListoItemsSlidersAndInterior");
          [self createListoItemsSlidersAndInterior];
      }
      
      [self MainRoutine];
    
    
}



- (IBAction)buttonActionConfigurations:(id)sender {
    
    //NSLog(@"buttonActionConfigurations");
    
    [self actionConfigurations];
    
}
- (IBAction)buttonActionConfigurationsFromFlightSettings:(id)sender {
    
    //NSLog(@"buttonActionConfigurationsFromFlightSettings");
    
    flagReopenFlightSettings = 1;
    [self actionConfigurations];
    
}

- (void) actionConfigurations {
    guidanceDictionary[@"guidanceBtnSetConfiguration"] =  @"ok";
    //NSLog(@"actionConfigurations");
    
    if (_viewConfigurations.hidden == YES) {        
        _viewConfigurations.hidden = NO;   [viewMain bringSubviewToFront:_viewConfigurations];
        _viewLegData.hidden = YES;
        _viewPilotList.hidden = YES;
        
        [viewOne bringSubviewToFront:_viewConfigurations];
        [viewOne bringSubviewToFront:viewTopTop];
        _viewLowerButtons.hidden  = NO;
        [viewOne bringSubviewToFront:_viewLowerButtons];   
        
        if (flagReopenFlightSettings == 1) {
            _viewLegData.hidden = NO;
        }
        
    }else{        
        _viewConfigurations.hidden = YES;    
        if (flagReopenFlightSettings == 1) {
            flagReopenFlightSettings = 0;
            _viewLegData.hidden = NO;
            _viewConfigurations.hidden = YES;
            _viewPilotList.hidden = YES;
        }
    }
    [self MainRoutine];
    
}


- (void) actionENTERpadListo { // after click on ENTER on enter Pad
    
    
    
    float enterTag = previousButton - 1300;
    
    if (selectedItem == 40) {
        enterTag =  buttonIDtransfer - 1600;
        
    }
    
   //NSLog (@"enterTag %@ ", [ [NSString alloc] initWithFormat:@"%.0f ", enterTag]);
    weightValue =  [EnterPadString doubleValue] / factorApplyToNativeWeightforItems ;
     
    //NSLog (@"weightValue %.0f ", weightValue);    
    //NSLog (@"fuelEnterMode %@ ", fuelEnterMode);
    //NSLog (@"fuelUnits %@ ", fuelUnits);
    //NSLog (@"selectedUnitForFuel %@ ", selectedUnitForFuel);
    
    
    
    float maxWeightForStation = [[_arrayName9 objectAtIndex: enterTag ] doubleValue];
    
    // check if this is a fuel slider    
    if ([[_arrayName10 objectAtIndex: enterTag  ] rangeOfString:@"fuelTank"].location != NSNotFound  ) {
        
        // if vol, then convert the value from volume to mass 
        //fuelarie        
        if ([fuelEnterMode isEqualToString:@"volume"] ) {
            weightValue =  [EnterPadString doubleValue] * [_inputSpecificFuelMassPerVolume.text floatValue] ;
            
            if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
                //slider is in lbs and we enter liter!
                //convert liter to gallons
                //convert gallons to lbs                
                weightValue = ([EnterPadString doubleValue] / 3.78541) * [_inputSpecificFuelMassPerVolume.text floatValue];
                //NSLog (@"22weightValue %.0f", weightValue); 
            } 
            if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                //slider is in kg and we enter gallons!              
                weightValue = ([EnterPadString doubleValue] * 3.78541) * [_inputSpecificFuelMassPerVolume.text floatValue];
                //NSLog (@"22weightValue %.0f", weightValue); 
            }
        }
        
        if ([fuelEnterMode isEqualToString:@"mass"] ) {            
            if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
                //slider is in lbs and we enter kilo!
                weightValue = ([EnterPadString doubleValue] * 2.2046) ;
            } 
            
            if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                //slider is in kg and we enter pounds
                weightValue = ([EnterPadString doubleValue] / 2.2046) ;
            }
        }
    }

    
    //NSLog (@"weightValue %.0f ", weightValue);
    //NSLog (@"maxWeightForStation %.0f ",maxWeightForStation);
    
    
    if (weightValue > maxWeightForStation) {
        weightValue = maxWeightForStation;
        
        NSString *maxWeightText = [[NSString alloc] initWithFormat:@"Max weight of %.0f %@ exceeded./nPlease note weight in station. \n\nNote: To change the max weight for this flight, tap and hold on the station and enter new max weight.", maxWeightForStation, selectedUnitForItems];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:maxWeightText
                                                                                 message:nil
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil]; 
    }
    
    totalWeightListo = weightValue;    
    totalArmListo = [[_arrayName3 objectAtIndex:enterTag] floatValue];    
    totallongMomentListo = totalWeightListo * totalArmListo;    
    totalArmLatListo = [[_arrayName5 objectAtIndex:enterTag] floatValue];    
    totalLatMomentListo  = totalWeightListo * totalArmLatListo;    
    listoItemNr = enterTag;
    
    [self overwriteArrays];    
    
    // check if this is a fuel slider to change the slider label
    
    if ([[_arrayName10 objectAtIndex: enterTag  ] rangeOfString:@"fuelTank"].location != NSNotFound  ) {
        
        //fuelarie
        
        
        if ([fuelEnterMode isEqualToString:@"volume"] ) {
          
            // if vol, then convert the value from volume to mass
            
            // update weight label 1000
            valueField = (UITextField*)[_viewFuelSliders viewWithTag: 1000 + enterTag];
            [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", weightValue / [_inputSpecificFuelMassPerVolume.text floatValue] ]  ];
            
            if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) {  
             
                [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [EnterPadString doubleValue] ]  ];
            }
            
            
            if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) {     
                
                [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [EnterPadString doubleValue] ]  ];
            }
            
            // update slider
            UISlider *slider = (UISlider*)[_viewFuelSliders viewWithTag:  enterTag ];
            slider.value = weightValue ;
            
            
        }else{
            
            // update weight label 1000
            valueField = (UITextField*)[_viewFuelSliders viewWithTag: 1000 + enterTag];
            [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", weightValue]  ];
            
            if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
                //slider is in lbs and we enter kilo!
                 [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", weightValue / 2.2046]  ];
            } 
            
            if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                //slider is in lbs and we enter kilo!
                [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", weightValue * 2.2046]  ];
            }
            
            
            
            // update slider
            UISlider *slider = (UISlider*)[_viewFuelSliders viewWithTag:  enterTag ];
            slider.value = weightValue;
            
            
            
        }
        
        
        
        
       
        
        
        if (weightValue < 1) {
            valueField = (UITextField*)[_viewFuelSliders viewWithTag: 1200+ enterTag];
            [valueField  setText: @"-"  ];
            [_arrayName7 replaceObjectAtIndex:enterTag withObject:@"-"];
            
        }
    }else{
        
        // update weight label 1000
        valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1000 + enterTag];
        if (valueField == nil) {
            valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1000 + enterTag];
        }
        [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", weightValue * factorApplyToNativeWeightforItems]  ];
        
        
        // update slider
        UISlider *slider = (UISlider*)[_viewStationsSlider viewWithTag:  enterTag ];
        if (!slider) {
            slider = (UISlider*)[_viewStationsSliderRight viewWithTag:  enterTag ];
        }
        slider.value = weightValue;
        
        
        if (weightValue < 1) {
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200+ enterTag];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200+ enterTag];
            }
            [valueField  setText: @"-"  ];
            [_arrayName7 replaceObjectAtIndex:enterTag withObject:@"-"];
        }
    }
    
    
    
    
    
    
    
    
    enterPad.hidden = YES;  [self setListoButtonsNeutral];
    
    [self MainRoutine];
    
   
    
}

- (IBAction)buttonActionEnterPadListo:(id)sender{    
    
    UIButton *btn = (UIButton*)sender;    
    //NSLog(@"btn  %d", btn.tag);
    [self setButtonMarksNeutral];
    
    if (flagButtonListoPressed == 0) {        
        // button pressed first time        
        enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonListoPressed = btn.tag ; previousButton = btn.tag;                
        // get current value for enter pad screen        
        valueField = (UITextField*)[_viewStationsSlider viewWithTag: previousButton - 300];
        if (valueField == nil) {
            valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: previousButton - 300];
        }        
        calculatorscreen.text = valueField.text ; EnterPadString = valueField.text; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;                
        UIImage *buttonmark = [UIImage imageNamed:@"Klammern YelGlow.png"];        
        [btn setImage:buttonmark forState:UIControlStateNormal];        
        btn.alpha = 1.0;
        
    }else{
        if (btn.tag == previousButton) {
            // same button pressed            
            enterPad.hidden = YES; flagButtonListoPressed = 0;            
            [self setListoButtonsNeutral];
        }else{
            
            // other button pressed            
            [self setListoButtonsNeutral];
            // get current value for enter pad screen            
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: btn.tag - 300];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: btn.tag - 300];
            }            
            calculatorscreen.text = valueField.text ; EnterPadString = valueField.text; EnterValueTwo = 0; commapressedTwo =0; minuspressedTwo = 0;
            enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonListoPressed = btn.tag ; previousButton = btn.tag;            
            UIImage *buttonmark = [UIImage imageNamed:@"Klammern YelGlow.png"];            
            [btn setImage:buttonmark forState:UIControlStateNormal];            
            btn.alpha = 1.0;
            
        }
    }
    
    [self MainRoutine];
    [self MainRoutine];
    
    

}

- (void) setListoButtonsNeutral {
    
    //[self setButtonMarksNeutral];
    
    
    enterPad.hidden = YES;
    
    for (int i = listStart; i < listEnd+1 ; i++) {
        
        
        
        UIButton *btnClear = (UIButton*)[_viewStationsSlider viewWithTag: 1300 + i];
        
        if (!btnClear) {
            btnClear = (UIButton*)[_viewStationsSliderRight viewWithTag: 1300 + i];
        }
        
        if ([[_arrayName10 objectAtIndex: i  ] rangeOfString:@"fuelTank"].location != NSNotFound   ) {
            btnClear = (UIButton*)[_viewFuelSliders viewWithTag: 1300 + i];
        }
        
        
        UIImage *buttonmark = [UIImage imageNamed:@"Klammern.png"];
        
        [btnClear setImage:buttonmark forState:UIControlStateNormal];
        
        btnClear.alpha = 1.0;
        
        
        
    }
    
    return;
    
}

- (void) createItemListForLoadManifest {
    
    //NSLog(@" createItemListForLoadManifest factorApplyToNativeWeightforItems %.3f", factorApplyToNativeWeightforItems);    
    //NSLog(@"_arrayName1 %@ ", _arrayName1);     
   //NSLog(@"allFlightsMasterArray %@ ", [allFlightsMasterArray objectAtIndex:1]); 
    
    
    
        

    
    for(UIView *subview in [_viewManifestListo subviews]) {
        [subview removeFromSuperview];
    }
    
    float fontSize = 13;
    float yInc = 40;
    float bHeight = 30;
    xPos1 = 74;
    width1 = 130; 
    width2 = 91;
    yPosTable = 0 - yInc;
    float yPix = 0;
    float lineDelta = 0;
    
    float noLatXpush = 0;
    
    if ( [[_arrayName21 objectAtIndex:13] isEqualToString:@"noLat"]) {
        
        noLatXpush = 172;
        
    }

    
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    
    //                                                                 MAKE items Load Manifest
    
    
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    
    //NSLog(@"make items");
    
    
    if ([selectedUnitForItems isEqualToString: @"kg"]  ) {
        [_arrayName2 replaceObjectAtIndex:2 withObject: @"kg"];
        [_arrayName3 replaceObjectAtIndex:2 withObject: @"mm"];
        [_arrayName4 replaceObjectAtIndex:2 withObject: @"kg.mm"];
        [_arrayName5 replaceObjectAtIndex:2 withObject: @"mm"];
        [_arrayName6 replaceObjectAtIndex:2 withObject: @"kg.mm"];
        
        if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
            //if meter
            [_arrayName2 replaceObjectAtIndex:2 withObject: @"kg"];
            [_arrayName3 replaceObjectAtIndex:2 withObject: @"m"];
            [_arrayName4 replaceObjectAtIndex:2 withObject: @"kg.m"];
            [_arrayName5 replaceObjectAtIndex:2 withObject: @"m"];
            [_arrayName6 replaceObjectAtIndex:2 withObject: @"kg.m"];
        }
    }else{
        [_arrayName2 replaceObjectAtIndex:2 withObject: @"lbs"];
        [_arrayName3 replaceObjectAtIndex:2 withObject: @"inches"];
        [_arrayName4 replaceObjectAtIndex:2 withObject: @"lbs.in"];
        [_arrayName5 replaceObjectAtIndex:2 withObject: @"inches"];
        [_arrayName6 replaceObjectAtIndex:2 withObject: @"lbs.in"];        
    }
    
    NSMutableArray *tempArrayInstName = [[NSMutableArray alloc] init];
    NSMutableArray *tempArrayInstWgt = [[NSMutableArray alloc] init];
    NSMutableArray *tempArrayInstArm = [[NSMutableArray alloc] init];
    NSMutableArray *tempArrayInstMom = [[NSMutableArray alloc] init];
    NSMutableArray *tempArrayArmLat = [[NSMutableArray alloc] init];
    NSMutableArray *tempArrayInstMomLat = [[NSMutableArray alloc] init];
    
 
    float addY = 0;
  
   
    
   
    double totalNativeMoment = 0, totalNativeMomentLat = 0;
    double totalNativeFuelMoment = 0, totalNativeFuelMomentLat = 0;
    double totalNativeFuelMomentLanding = 0, totalNativeFuelMomentLatLanding = 0;
    
    double zfwMoment = 0, zfwMomentLat = 0;
    //NSLog(@"----------");
    
    NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"];
    if (dedicatedCustomerData.length < 2) {
        dedicatedCustomerData = @"";
    }
    
    _buttonShowHideEquipmentListPage.hidden = YES;
    if ([dedicatedCustomerData rangeOfString:@"createExtraEquipmentPage"].location != NSNotFound  ) {   
        if (equipmentItemsOnBoard > 0) {            
             _buttonShowHideEquipmentListPage.hidden = NO; [viewLoadManifest bringSubviewToFront:_buttonShowHideEquipmentListPage];
        }
    }
    
    float flagShowSeatsAsInstallationOnManifest = 0;
    if ([dedicatedCustomerData rangeOfString:@"showSeatsAsInstallationOnManifest"].location != NSNotFound  ) {   
        flagShowSeatsAsInstallationOnManifest = 1;
    }
    
 
       
    
    //NSLog(@"listStart %f", listStart);
    
    for (int i = listStart; i < listEnd+1 ; i++) {
        
        float itemNr = i;
        float lineWidth = 1;
        float itemInOut = 1;
        float sliderInOut = 1;
        float isFuelSlider = 0;
        float isSingleLine = 0;
        lineDelta = 0;
        
        //NSLog(@"[_arrayName25 objectAtIndex:45 ] %@", [_arrayName25 objectAtIndex: 45 ]);
        //if item is zero weight, do not show on load manifest
        //sdf
        
        
        if (flagShowSeatsAsInstallationOnManifest == 1) {
            //check if item weight - list seats seppel
            if ([[_arrayName17 objectAtIndex: itemNr ] doubleValue] > 0 & [[_arrayName8 objectAtIndex: itemNr ] floatValue] == 1) { 
                [tempArrayInstName addObject:[_arrayName1 objectAtIndex:itemNr]];
                [tempArrayInstWgt addObject:[_arrayName17 objectAtIndex:itemNr]];
                if ([[_arrayName18 objectAtIndex:itemNr]floatValue] > 0) {                    
                    if ([[_arrayName18 objectAtIndex: itemNr ] rangeOfString:@"quick"].location != NSNotFound || [[_arrayName18 objectAtIndex: itemNr ] rangeOfString:@"max"].location != NSNotFound || [[_arrayName18 objectAtIndex: itemNr ] rangeOfString:@"forceFuelTank"].location != NSNotFound){
                        [tempArrayInstArm addObject:[_arrayName3 objectAtIndex:itemNr]];
                        [tempArrayInstMom addObject:[[NSString alloc] initWithFormat:@"%.0f", [[_arrayName17 objectAtIndex:itemNr]floatValue] * [[_arrayName3 objectAtIndex:itemNr] floatValue]]];           
                    }else{
                        [tempArrayInstArm addObject:[_arrayName18 objectAtIndex:itemNr]];
                        [tempArrayInstMom addObject:[[NSString alloc] initWithFormat:@"%.1f", [[_arrayName17 objectAtIndex:itemNr]floatValue] * [[_arrayName18 objectAtIndex:itemNr] floatValue]]]; 
                        
                        
                    }
                   
                }else{
                    [tempArrayInstArm addObject:[_arrayName3 objectAtIndex:itemNr]];
                    [tempArrayInstMom addObject:[[NSString alloc] initWithFormat:@"%.0f", [[_arrayName17 objectAtIndex:itemNr]floatValue] * [[_arrayName3 objectAtIndex:itemNr] floatValue]]];               
                } 
                [tempArrayArmLat addObject:[[NSString alloc] initWithFormat:@"%.0f", [[_arrayName5 objectAtIndex:itemNr]floatValue]]];            
                [tempArrayInstMomLat addObject:[[NSString alloc] initWithFormat:@"%.0f", [[_arrayName17 objectAtIndex:itemNr]floatValue] * [[_arrayName5 objectAtIndex:itemNr] floatValue]]];
            }
            
             
        }
        
        
        if ([[_arrayName25 objectAtIndex:45 ] isEqualToString:@"no"] && i >2) {            
            if ( ![[_arrayName14 objectAtIndex:45 ] isEqualToString:@"result"] ||  ![[_arrayName14 objectAtIndex:45 ] isEqualToString:@"resultIntermediate"] || ![[_arrayName14 objectAtIndex:45 ] isEqualToString:@"noSlider"]   ) {                
                if ([[_arrayName2 objectAtIndex: itemNr ] doubleValue] == 0) {
                    continue;
                }
            }
        }
        
        
        if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"noSliderNoPicNotOnManifest"].location != NSNotFound) {            
            continue;
        }
        
        
        
        // check multiplicator
        if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] < 1) {
            sliderInOut = 0; itemInOut = 0;
        }
        if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] == 1) {
            sliderInOut = 1;
        }
        
        // check specials and seat names
        if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"single"].location != NSNotFound) {
            
            if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] == 1) {
                //lineDelta = - 12;  itemInOut = 1; sliderInOut = 0; isSingleLine = 1;
                isSingleLine = 1; lineDelta = - 12; 
            }
        }
        
        if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"picAndLabel"].location != NSNotFound) {
            
            if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] == 1) {
                //lineDelta = - 12;  itemInOut = 1; sliderInOut = 0; isSingleLine = 1;
                isSingleLine = 1; lineDelta = - 12; 
            }
        }
        
        
        
        if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"picOnly"].location != NSNotFound) {
            
            if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] == 1) {
                //lineDelta = - 12;  itemInOut = 1; sliderInOut = 0; isSingleLine = 1;
                isSingleLine = 1; lineDelta = - 12; 
            }
        }
        
        
        
        if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"fuel"].location != NSNotFound) {
            isFuelSlider = 1; sliderInOut = 1; itemInOut = 1; lineDelta = - 12;            
           if  ( [[_arrayName8 objectAtIndex: itemNr  ]  floatValue] < 1 ) {
                itemInOut = 0;
           }            
        }
        
       
        if  ( [[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"door"]  ) {
            //NSLog (@"equip %@ ", [ [NSString alloc] initWithFormat:@"%.0f  -  %.0f ", itemNr, [[_arrayName8 objectAtIndex: itemNr ] doubleValue] ]);
            // check multiplicator
            if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] < 1) {
                itemInOut = 0; sliderInOut = 1;
            }
            
            if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] == 1) {
                //lineDelta = - 12;  itemInOut = 1; sliderInOut = 0; isSingleLine = 1;
                lineDelta = -12;   sliderInOut = 0; isSingleLine = 1;
            }
        }
        
        
        
        if  ( [[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"equip"] || [[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"showWhenOff"] ) {
            //NSLog (@"equip %@ ", [ [NSString alloc] initWithFormat:@"%.0f  -  %.0f ", itemNr, [[_arrayName8 objectAtIndex: itemNr ] doubleValue] ]);
            // check multiplicator
            if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] < 1) {
                itemInOut = 0; sliderInOut = 1;
            }
            
            if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] == 1) {
                //lineDelta = - 12;  itemInOut = 1; sliderInOut = 0; isSingleLine = 1;
                lineDelta = -12;   sliderInOut = 0; isSingleLine = 1;
            }
        }
        
        
        
        if  ([[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"noSlider"]) {
            lineDelta = - 12;   sliderInOut = 0; isSingleLine = 1;
                   }
        
        if  ([[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"noSliderNoPicNotOnManifest"]) {
            lineDelta = - 12;   sliderInOut = 0; isSingleLine = 1;
        }
        
        
        // if NEXT item is result, then make thick line
        if  ([[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"result"]) {
            //NSLog(@"this is result %@", [_arrayName1 objectAtIndex: itemNr  ]);
            //NSLog(@"this is a result line ");
            lineDelta = - 12;
            isSingleLine = 1;
            itemInOut = 1; sliderInOut = 0;
            lineWidth = 3;
            if  ( [[_arrayName8 objectAtIndex: itemNr  ]  floatValue] < 1  &&  [[_arrayName10 objectAtIndex: itemNr] isEqualToString:@"fuelTankTotal"]) {
                itemInOut = 0;
            }
        }
        
        if  ([[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"resultIntermediate"]) {
            //NSLog(@"this is resultIntermediate %@", [_arrayName1 objectAtIndex: itemNr  ]);
            lineDelta = - 12;
            isSingleLine = 1;
            itemInOut = 1; sliderInOut = 0;
            lineWidth = 1;
            if  ( [[_arrayName8 objectAtIndex: itemNr  ]  floatValue] < 1  &&  [[_arrayName10 objectAtIndex: itemNr] isEqualToString:@"fuelTankTotal"]) {
                itemInOut = 0;
            }
        }
        
        if ([[self.arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"%MAC"].location != NSNotFound     ) {
            lineDelta = - 12;
            isSingleLine = 1;
            itemInOut = 1; sliderInOut = 0;
            lineWidth = 3;
        }
        
        //hier stand die alte    if (flagShowSeatsAsInstallationOnManifest == 1) {
        
        
        //*************************************************************************************
        
     
        
        int flagAddStations = 0;        
        if (itemInOut == 0) {
            
            if ([[_arrayName12 objectAtIndex:itemNr] isEqualToString:@"addStations"] || [[_arrayName12 objectAtIndex:itemNr] isEqualToString:@"addDOM"]    ) {                
                itemInOut = 1;
                flagAddStations = 1;                
            }else{
                continue;                
            } 
        }        
        float APSweight = 0;
        float APSmom = 0;
        float APSmomLat = 0;  
        
      
        
        if (flagAddStations == 1) {             
            NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"+"];
            NSArray *components;
            
            if ([[_arrayName12 objectAtIndex:itemNr] isEqualToString:@"addDOM"]    ) {
                components = [[_arrayName18 objectAtIndex:itemNr] componentsSeparatedByCharactersInSet:charSet];   
            }else{                
                 components = [[_arrayName11 objectAtIndex:itemNr] componentsSeparatedByCharactersInSet:charSet];   
            }       
            
            for(int addStationItem =0; addStationItem<components.count; addStationItem++) { 
                
                //if object has a minus then subtract!
                 
                int flagSubtract = 0;
                int flagUseValue = 0;
                float stationID = [[components objectAtIndex:addStationItem] intValue];
                if (stationID < 0) {
                    stationID = stationID * -1;
                    flagSubtract = 1;
                }
                
               
                if (stationID > 99 || stationID < -99) {
                    flagUseValue = 1;
                }
                
                //NSLog(@"components %d", stationID);                 
                //NSLog(@"name %@", [_arrayName1 objectAtIndex:stationID]);                
                float APStempWeight = 0;   
                if  (flagUseValue == 1) {
                    APStempWeight = stationID;
                }else{
                    APStempWeight = [[_arrayName2 objectAtIndex:stationID] floatValue] * [[_arrayName8 objectAtIndex:stationID] floatValue]; 
                    if (stationID > lineZFW) {
                        APStempWeight = [[_arrayName2 objectAtIndex:stationID] floatValue];
                    }
                }                
                if (flagSubtract == 0) {
                     APSweight =  APSweight + APStempWeight;   
                }else{
                    APSweight =  APSweight - APStempWeight;  
                }
                           
                if (flagUseValue == 0) {
                    float APStempARM = [[_arrayName3 objectAtIndex: stationID ] doubleValue]  *  factorApplyToNativeDistanceInchMM; 
                    float APStempMOM = ( APStempWeight * APStempARM );
                    if (flagSubtract == 0) {
                             APSmom =  APSmom + APStempMOM;                                    
                             APSmomLat =  APSmomLat + ( APStempWeight * [[_arrayName5 objectAtIndex: stationID ] doubleValue]  *  factorApplyToNativeDistanceInchMM  );   
                      }else{
                            APSmom =  APSmom - APStempMOM;                                    
                            APSmomLat =  APSmomLat - ( APStempWeight * [[_arrayName5 objectAtIndex: stationID ] doubleValue]  *  factorApplyToNativeDistanceInchMM  );  
                      }
                }else{
                    APSmom = 0;
                    APSmomLat = 0;
                    
                }          
                                
            }  
            
            //NSLog(@"result APSweight %.1f", APSweight);
            totalWeightListo =  APSweight;
            totallongMomentListo =  APSmom;
            totalLatMomentListo =  APSmomLat;
            totalArmListo = totallongMomentListo / totalWeightListo;
            totalArmLatListo = totalLatMomentListo / totalWeightListo;                        
            listoItemNr = itemNr;
            [self overwriteArrays];                        
            lineDelta = - 12;
            isSingleLine = 1;
            itemInOut = 1; sliderInOut = 0;
            lineWidth = 3;            
            
        } 
        
         //*************************************************************************************
        
        yPix = yPix + yInc;
        // make lines on load manifest
        // draw from 66 - 672 = 606
        
        if (itemNr == 2 || itemNr == 3 ) {
            lineWidth = 3;
        }
        if (itemNr == 1  ) {
            lineWidth = 0; lineDelta = - 22;
        }
        
        if (itemNr == 2  ) { // line units
            fontSize = 11;
        }
        
        NSLog(@"making it");
        addY = 0;
        if (itemNr == lineSeats & tempArrayInstName.count > 0 & flagShowSeatsAsInstallationOnManifest == 1 ) {
            //NSLog(@"this is line seats and we have entries %f", itemNr );            
            float lineAbstand = 18;
            float lineStart = 0;
            
             
            
            lineDelta = tempArrayInstName.count * lineAbstand -9;
            
            addY =  tempArrayInstName.count * lineAbstand +3;
            
            for (int instNumber = 0; instNumber < tempArrayInstName.count ; instNumber++) {
                
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1, (yPosTable + yPix + lineStart + (instNumber* lineAbstand) ), width1, bHeight)];
                label.font = [UIFont systemFontOfSize:10];
                label.textAlignment = NSTextAlignmentLeft;
                [label  setText: [tempArrayInstName objectAtIndex:instNumber]  ];                                      
                [_viewManifestListo addSubview: label];                
                //weight
                label = [[UILabel alloc] initWithFrame:CGRectMake(noLatXpush + xPos1 + width1, (yPosTable + yPix + lineStart + (instNumber* lineAbstand)), width2, bHeight)];
                label.font = [UIFont systemFontOfSize:10];
                label.textAlignment = NSTextAlignmentRight;              
                [label  setText: [[NSString alloc] initWithFormat:@"%.1f", [[tempArrayInstWgt objectAtIndex:instNumber]floatValue] * factorApplyToNativeWeightforItems]];
                [_viewManifestListo addSubview: label];                
                //arm
                label = [[UILabel alloc] initWithFrame:CGRectMake(noLatXpush + xPos1 + width1 + 1 * width2 - 10, (yPosTable + yPix + lineStart + (instNumber* lineAbstand)), width2, bHeight)];                                                       
                label.font = [UIFont systemFontOfSize:10];
                label.textAlignment = NSTextAlignmentRight;
                [label  setText: [[NSString alloc] initWithFormat:@"%.1f", [[tempArrayInstArm objectAtIndex:instNumber]floatValue]*  factorApplyToNativeDistanceInchMM ]];                               
                [_viewManifestListo addSubview: label];                
                //moment
                label = [[UILabel alloc] initWithFrame:CGRectMake(noLatXpush + xPos1 + width1 + 2 * width2, (yPosTable + yPix + lineStart + (instNumber* lineAbstand)), width2, bHeight)];                                                       
                label.font = [UIFont systemFontOfSize:10];
                label.textAlignment = NSTextAlignmentRight;                  
                [label  setText: [[NSString alloc] initWithFormat:@"%.1f", [[tempArrayInstMom objectAtIndex:instNumber]floatValue] *factorApplyToNativeMoment]];               
                [_viewManifestListo addSubview: label];            
                label = [[UILabel alloc] initWithFrame:CGRectMake(noLatXpush + xPos1 + width1 + 3 * width2, (yPosTable + yPix + lineStart + (instNumber* lineAbstand)), width2, bHeight)];                                                       
                label.font = [UIFont systemFontOfSize:10];
                label.textAlignment = NSTextAlignmentRight;               
                [label  setText: [[NSString alloc] initWithFormat:@"%.1f", [[tempArrayArmLat objectAtIndex:instNumber]floatValue]*  factorApplyToNativeDistanceInchMM ]];   
                [_viewManifestListo addSubview: label];                
                
                label = [[UILabel alloc] initWithFrame:CGRectMake(noLatXpush + xPos1 + width1 + 4 * width2, (yPosTable + yPix + lineStart + (instNumber* lineAbstand)), width2, bHeight)];                                                       
                label.font = [UIFont systemFontOfSize:10];
                label.textAlignment = NSTextAlignmentRight;                
                [label  setText: [[NSString alloc] initWithFormat:@"%.1f", [[tempArrayInstMomLat objectAtIndex:instNumber]floatValue] *factorApplyToNativeMoment]];   
                [_viewManifestListo addSubview: label];
                
                //NSLog(@"[tempArrayInstMom objectAtIndex:instNumber] %@", [tempArrayInstMom objectAtIndex:instNumber] ); 
                
            }
            
            UIImageView *line =[[UIImageView alloc] initWithFrame:CGRectMake(noLatXpush + xPos1 + width1 +30, yPosTable + yPix + lineStart + (tempArrayInstName.count * lineAbstand) + 8, 672 - noLatXpush - xPos1 - width1 - 30, 1) ];
            
            
            line.backgroundColor = [UIColor blackColor];
            line.alpha = 0.6;
            [_viewManifestListo addSubview: line];
            
            
        }
        
        UIImageView *line =[[UIImageView alloc] initWithFrame:CGRectMake(66, (yPosTable + yPix + yInc + lineDelta   ), 606, lineWidth) ];
        line.backgroundColor = [UIColor blackColor];
        line.alpha = 0.6;
        
        if (itemInOut == 1) {
            [_viewManifestListo addSubview: line];
        }
        
        
        if (itemNr == lineZFW) {
            lineWidth = 4;
            UIImageView *line =[[UIImageView alloc] initWithFrame:CGRectMake(66, (yPosTable + yPix + yInc - 42   ), 606, lineWidth) ];
            line.backgroundColor = [UIColor blackColor];
            line.alpha = 0.6;
            [_viewManifestListo addSubview: line];
        }
        
        
        //NSLog(@"lineWidth %.0f", lineWidth);
        // make all buttons on load manifest (and on view OPTIONS)
        
        // station name
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1, (yPosTable + yPix ) + addY, width1 , bHeight)];
        label.font = [UIFont boldSystemFontOfSize:fontSize];
        label.textAlignment = NSTextAlignmentLeft;
        label.adjustsFontSizeToFitWidth = YES;   // trick to shrink fonts            
        label.minimumScaleFactor = 0.3;  
        [label  setText: [_arrayName1 objectAtIndex: itemNr ]  ];
        
        if (itemNr == lineSeats & tempArrayInstName.count > 0) {
            [label  setText: @"Installations Total" ];            
        }
        
        //NSLog(@"_arrayName4 %@", _arrayName4);
              
        
        if (itemNr == 1 || itemNr == 2 ) { [label  setText: [_arrayName1 objectAtIndex: itemNr ]  ];    }
       
        
        // mark TOM line3
        if ([[_arrayName1 objectAtIndex:itemNr] rangeOfString:@"TOM"].location != NSNotFound || [[_arrayName1 objectAtIndex:itemNr] rangeOfString:@"TOW"].location != NSNotFound ) {
            UIImageView *line =[[UIImageView alloc] initWithFrame:CGRectMake(66, (yPosTable + yPix + yInc + lineDelta -25  ), 606, 25) ];
            line.backgroundColor = [UIColor blackColor];
            line.alpha = 0.2;
            [_viewManifestListo addSubview: line];
        }
        
        
        
        //NSLog(@"item %.0f =  %@", itemNr, [_arrayName1 objectAtIndex: itemNr ]);
        
        if ([dedicatedCustomerData rangeOfString:@"weight"].location != NSNotFound & [dedicatedCustomerData rangeOfString:@"spellOut"].location != NSNotFound  ) {
                   
            if ([[_arrayName1 objectAtIndex:itemNr] rangeOfString:@"BEM"].location != NSNotFound  ) {
                       [label  setText: @"Basic Empty Weight" ];
                if (flagSpecialPHIFlightSettingPage == 1) {
                    [label  setText: @"Form C Weight" ];
                }
                   } 
            
            if ([[_arrayName1 objectAtIndex:itemNr] rangeOfString:@"ZFM"].location != NSNotFound  ) {
                [label  setText: @"Zero Fuel Weight" ];
            } 
            if ([[_arrayName1 objectAtIndex:itemNr] rangeOfString:@"TOM"].location != NSNotFound  ) {
                [label  setText: @"Takeoff Weight" ];
            } 
            if ([[_arrayName1 objectAtIndex:itemNr] rangeOfString:@"LDM"].location != NSNotFound  ) {
                [label  setText: @"Landing Weight" ];
            }            
            if ([[_arrayName1 objectAtIndex:itemNr] rangeOfString:@"TO Fuel"].location != NSNotFound  ) {
                [label  setText: @"Takeoff Fuel" ];
            }
            if ([[_arrayName1 objectAtIndex:itemNr] rangeOfString:@"Ldg. Fuel"].location != NSNotFound  ) {
                [label  setText: @"Landing Fuel" ];
            }
        }
        
        if ([dedicatedCustomerData rangeOfString:@"weight"].location != NSNotFound & [dedicatedCustomerData rangeOfString:@"spellOut"].location == NSNotFound  ) {
            if ([[_arrayName1 objectAtIndex:itemNr] rangeOfString:@"BEM"].location != NSNotFound  ) {
                       [label  setText: @"Basic Empty Weight" ];
                   }  
            
            if ([[_arrayName1 objectAtIndex:itemNr] rangeOfString:@"ZFM"].location != NSNotFound  ) {
                [label  setText: @"ZFW" ];
            } 
            if ([[_arrayName1 objectAtIndex:itemNr] rangeOfString:@"TOM"].location != NSNotFound  ) {
                [label  setText: @"TOW" ];
            } 
            if ([[_arrayName1 objectAtIndex:itemNr] rangeOfString:@"LDM"].location != NSNotFound  ) {
                [label  setText: @"LDW" ];
            } 
        }
        
        [_viewManifestListo addSubview: label];
        
       
        
       
        
     
         //*************************************************************************************************
        // weight
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(noLatXpush + xPos1 + width1, (yPosTable + yPix ) + addY, width2, bHeight)];
        label.font = [UIFont systemFontOfSize:fontSize];
        label.textAlignment = NSTextAlignmentRight;
        NSString *valueText =  [ [NSString alloc] initWithFormat:@"%.1f", [[_arrayName2 objectAtIndex: itemNr ] doubleValue] * factorApplyToNativeWeightforItems ];
        
        if (itemNr == 3) {
             //NSLog(@"item %.0f %@  wgt %@ arm %@   mom %@  armLat %@ momLat %@", itemNr, [_arrayName1 objectAtIndex: itemNr ], [_arrayName2 objectAtIndex: itemNr ],  [_arrayName3 objectAtIndex: itemNr ], [_arrayName4 objectAtIndex: itemNr ], [_arrayName6 objectAtIndex: itemNr ], [_arrayName6 objectAtIndex: itemNr ] );
        }
        
        [label  setText: valueText ];          
        
        if ([dedicatedCustomerData rangeOfString:@"weight"].location != NSNotFound  ) {
            //NSLog(@"2 Customer (UHI!) wants weight instead of mass");
            [_arrayName2 replaceObjectAtIndex:1 withObject:@"Weight"];
        }        
        if (itemNr == 1 || itemNr == 2 ) {[label  setText: [_arrayName2 objectAtIndex: itemNr ]  ];     }
        
        
        if ([[_arrayName17 objectAtIndex: i  ] rangeOfString:@"subtract"].location != NSNotFound) {
            valueText =  [ [NSString alloc] initWithFormat:@"%.1f", [[self.arrayName2 objectAtIndex: itemNr ] doubleValue] *-1 ];
            [label  setText: valueText ];
        }

        NSString *percentMac;
        
        if ([[self.arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"%MAC TO"].location != NSNotFound     ) {
            percentMac =  [ [NSString alloc] initWithFormat:@"%.1f %%", (vTOWArm - 188.24) / 0.78 ];
            [label  setText: percentMac ];
        }
        
        if ([[self.arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"%MAC LD"].location != NSNotFound     ) {
            percentMac =  [ [NSString alloc] initWithFormat:@"%.1f %%", (vLDWArm - 188.24) / 0.78 ];
            [label  setText: percentMac ];
        }
        
        
        if (itemNr == 1 || itemNr == 2 ) {             [label  setText: [self.arrayName2 objectAtIndex: itemNr ]  ];     }
        
        [_viewManifestListo addSubview: label];
        
      
        
        
        NSString *numberFormat;
        NSString *numberFormat2;
        
        if ( [[_arrayName21 objectAtIndex:5] isEqualToString:@"kg"]) {
           
            
            if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
               
                numberFormat = @"%.3f"; 
                numberFormat2 = @"%.2f"; 
            }else{
            
                numberFormat = @"%.1f";
                numberFormat2 = @"%.1f";
                [decimalFormatter setFormatWidth:2];
                [decimalFormatter setGroupingSeparator:@","];
                [decimalFormatter setGroupingSize:3];
                [decimalFormatter setUsesGroupingSeparator:YES];
                decimalFormatter.maximumFractionDigits = 0;
                decimalFormatter.minimumFractionDigits = 0;
                                
            }
            
        }else{
            
            numberFormat = @"%.1f";
            numberFormat2 = @"%.1f";
        }
        
        //*************************************************************************************************
        // arm long
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(noLatXpush + xPos1 + width1 + 1 * width2 - 10, (yPosTable + yPix ) + addY, width2, bHeight)];
        
        label.font = [UIFont systemFontOfSize:fontSize];
        label.textAlignment = NSTextAlignmentRight;
        valueText =  [ [NSString alloc] initWithFormat:numberFormat, ([[_arrayName3 objectAtIndex: itemNr ] doubleValue])  *  factorApplyToNativeDistanceInchMM ];
        
       
        //float tempArm = [valueText floatValue];
        NSString *armRounded = [NSString stringWithFormat:numberFormat,  [[_arrayName3 objectAtIndex: itemNr ] doubleValue] * factorApplyToNativeDistanceInchMM ];
        
        NSString *weightRounded =  [ [NSString alloc] initWithFormat:numberFormat2, [[_arrayName2 objectAtIndex: itemNr ] doubleValue] * factorApplyToNativeWeightforItems ];
        
        if (itemNr == lineSeats & tempArrayInstName.count > 0) { 
            //"Installations Total"   
            armRounded = [NSString stringWithFormat:numberFormat2,  ([[_arrayName4 objectAtIndex: itemNr ] doubleValue] * factorApplyToNativeMoment)  / [weightRounded floatValue]] ;
        }
        
        [label  setText: armRounded ];
        
        if (itemNr == 1|| itemNr == 2 ) { [label  setText: [_arrayName3 objectAtIndex: itemNr ]  ];       }
       
        if (flagAddStations == 0) {
             [_viewManifestListo addSubview: label];
        }
        
        if ([[self.arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"%MAC"].location != NSNotFound     ) {
            label.hidden = YES;
        }
        
        
         //*************************************************************************************************
        // moment long
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(noLatXpush + xPos1 + width1 + 2 * width2, (yPosTable + yPix  ) + addY, width2, bHeight)];
        label.font = [UIFont systemFontOfSize:fontSize];
        label.textAlignment = NSTextAlignmentRight;
        //valueText =  [ [NSString alloc] initWithFormat:numberFormat, [[_arrayName4 objectAtIndex: itemNr ] doubleValue]  ];
        
        valueText = [NSString stringWithFormat:numberFormat2, [weightRounded doubleValue] * [armRounded doubleValue] ];
        
        if (itemNr == lineSeats & tempArrayInstName.count > 0) {
            //"Installations Total"   
             valueText = [NSString stringWithFormat:numberFormat2,  [[_arrayName4 objectAtIndex: itemNr ] doubleValue] * factorApplyToNativeMoment];
        }
        
        if (itemNr == 3   ){            
            //NSLog(@" [[_arrayName4 objectAtIndex: itemNr ] doubleValue] %f ",  [[_arrayName4 objectAtIndex: itemNr ] doubleValue]);            
            valueText = [NSString stringWithFormat:@"%.2f",  [[_arrayName4 objectAtIndex: itemNr ] doubleValue] * factorApplyToNativeMoment ];              
            //NSLog(@"BEW valueText %@", valueText);           
        }  
        
        
        if ([[_arrayName1 objectAtIndex: itemNr]isEqualToString:@"Fuel Main TO"]) {
            //NSLog(@"aha  %@ %.2f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText doubleValue]);
        }
        
        if ([AC_Type rangeOfString:@"R44Raven"].location != NSNotFound   || [AC_Type rangeOfString:@"R44Cadet"].location != NSNotFound  || [AC_Type rangeOfString:@"R22Beta"].location != NSNotFound  ) {
            
            // Robinson specials LONG     
            
            if (itemNr != lineZFW & itemNr != lineTOW & itemNr != lineLDW ){                
                if ([[_arrayName1 objectAtIndex: itemNr]isEqualToString:@"Takeoff Fuel TOTAL"] ) {
                    //do not add the fuel tank                     
                }else if ([[_arrayName1 objectAtIndex: itemNr]isEqualToString:@"Landing Fuel TOTAL"] ) {
                    //do not add the fuel tank                      
                }else if ([[_arrayName1 objectAtIndex: itemNr  ] rangeOfString:@"Takeoff Fuel Main"].location != NSNotFound ) {              
                    totalNativeFuelMoment = totalNativeFuelMoment + [valueText doubleValue];
                    //NSLog(@"%@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText floatValue]); 
                    //NSLog(@"totalNativeFuelMoment %f ", totalNativeFuelMoment);  
                }else if ([[_arrayName1 objectAtIndex: itemNr  ] rangeOfString:@"Takeoff Fuel Aux"].location != NSNotFound ) {              
                    totalNativeFuelMoment = totalNativeFuelMoment + [valueText doubleValue];
                    //NSLog(@"%@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText floatValue]); 
                    //NSLog(@"totalNativeFuelMoment %f ", totalNativeFuelMoment);  
                }else if ([[_arrayName1 objectAtIndex: itemNr ] rangeOfString:@"Landing Fuel Main"].location != NSNotFound ) {              
                    totalNativeFuelMomentLanding = totalNativeFuelMomentLanding + [valueText doubleValue];
                    //NSLog(@"%@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText doubleValue]);  
                    //NSLog(@"totalNativeFuelMomentLanding %f ", totalNativeFuelMomentLanding);  
                }else if ([[_arrayName1 objectAtIndex: itemNr ] rangeOfString:@"Landing Fuel Aux"].location != NSNotFound ) {              
                    totalNativeFuelMomentLanding = totalNativeFuelMomentLanding + [valueText doubleValue];
                    //NSLog(@"%@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText doubleValue]);  
                    //NSLog(@"totalNativeFuelMomentLanding %f ", totalNativeFuelMomentLanding);  
                }else{                    
                    //add the normal stuff
                    totalNativeMoment = totalNativeMoment + [valueText doubleValue];
                    //NSLog(@"%@ %.2f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText doubleValue]);  
                    //NSLog(@"totalNativeMoment %.2f ", totalNativeMoment);  
                } 
                
                if (itemNr == lineTOW -1  ){
                    valueText = [NSString stringWithFormat:@"%.1f", totalNativeFuelMoment  ];
                    //NSLog(@"totalNativeFuelMomentLanding %f ", totalNativeFuelMomentLanding); 
                }                
                if (itemNr == lineLDW -1  ){
                    valueText = [NSString stringWithFormat:@"%.1f", totalNativeFuelMomentLanding  ];
                    //NSLog(@"totalNativeFuelMomentLanding %f ", totalNativeFuelMomentLanding); 
                }                
            }
            
            if (itemNr == lineZFW  ){
                valueText = [NSString stringWithFormat:@"%.2f", totalNativeMoment  ];
                //NSLog(@"lineZFW totalNativeMoment %f", totalNativeMoment);
                zfwMoment = totalNativeMoment;
            }
            if (itemNr == lineTOW  ){
                valueText = [NSString stringWithFormat:@"%.2f", totalNativeMoment + totalNativeFuelMoment ];
                //NSLog(@"lineTOW totalNativeMoment %f", totalNativeMoment);
                totalNativeMoment = 0;            
            }        
            if (itemNr == lineLDW  ){
                valueText = [NSString stringWithFormat:@"%.2f", zfwMoment + totalNativeFuelMomentLanding  ];
                //NSLog(@"lineLDW totalNativeMoment %f", zfwMoment + totalNativeFuelMomentLanding );
            }
            
            
            
        }else{
            
            // not Robinson
            if (itemNr != lineZFW & itemNr != lineTOW & itemNr != lineLDW ){
                
                if (flagMultipleFuelTanks == 1) { 
                    
                    if ([[_arrayName10 objectAtIndex: itemNr]isEqualToString:@"fuelTankTotal"] ) {
                        //do not add the fuel tank  
                        //NSLog(@"3 %@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText floatValue]);  
                    }else if ([[_arrayName1 objectAtIndex: itemNr  ] rangeOfString:@"Fuel TO"].location != NSNotFound ) {              
                        totalNativeMoment = totalNativeMoment + [valueText doubleValue];
                        //NSLog(@"%@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText floatValue]); 
                        //NSLog(@"totalNativeMoment %f ", totalNativeMoment);  
                    }else if ([[_arrayName1 objectAtIndex: itemNr ] rangeOfString:@"Fuel LD"].location != NSNotFound ) {              
                        totalNativeFuelMomentLanding = totalNativeFuelMomentLanding + [valueText doubleValue];
                        //NSLog(@"%@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText doubleValue]);  
                        //NSLog(@"totalNativeFuelMomentLanding %f ", totalNativeFuelMomentLanding);  
                    }else{                    
                        //add the normal stuff
                        totalNativeMoment = totalNativeMoment + [valueText doubleValue];
                        //NSLog(@"%@ %.2f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText doubleValue]);  
                        //NSLog(@"totalNativeMoment %.2f ", totalNativeMoment);  
                    }  
                    
                    if (itemNr == lineLDW -1  ){
                        valueText = [NSString stringWithFormat:@"%.1f", totalNativeFuelMomentLanding  ];
                        //NSLog(@"totalNativeFuelMomentLanding %f ", totalNativeFuelMomentLanding); 
                    }
                    
                }else{  
                    
                    //NSLog(@"adding totalNativeMoment to %@  %f ", [_arrayName1 objectAtIndex: itemNr], [valueText floatValue]);                     
                    
                    if ([[_arrayName12 objectAtIndex:itemNr] isEqualToString:@"addDOM"] ) {
                        //do no add this to native
                    }else{
                         totalNativeMoment = totalNativeMoment + [valueText doubleValue];
                        
                    }
                    
                    if (itemNr == lineLDW -1  ){
                        totalNativeFuelMomentLanding = totalNativeFuelMomentLanding + [valueText doubleValue]; 
                        //NSLog(@"totalNativeFuelMomentLanding %f ", [valueText floatValue]); 
                    }
                }
            }
            
            if (itemNr == lineZFW  ){
                valueText = [NSString stringWithFormat:@"%.2f", totalNativeMoment  ];
                //NSLog(@"lineZFW totalNativeMoment %f", totalNativeMoment);
                zfwMoment = totalNativeMoment;
            }
            if (itemNr == lineTOW  ){
                valueText = [NSString stringWithFormat:@"%.2f", totalNativeMoment  ];
                //NSLog(@"lineTOW totalNativeMoment %f", totalNativeMoment);
                totalNativeMoment = 0;            
            }        
            if (itemNr == lineLDW  ){
                valueText = [NSString stringWithFormat:@"%.2f", zfwMoment + totalNativeFuelMomentLanding  ];
                //NSLog(@"lineLDW totalNativeMoment %f", zfwMoment + totalNativeFuelMomentLanding );
            }
            
            
        }
        
      
        
        
        
        if ([[_arrayName4 objectAtIndex: itemNr ] doubleValue] == 0) {
            valueText = @"0";
        }
        [label  setText: valueText ];
         if (itemNr == 1|| itemNr == 2 ) {             [label  setText: [_arrayName4 objectAtIndex: itemNr ]  ];       }       
        
         if (flagAddStations == 0) {
             [_viewManifestListo addSubview: label]; 
         }
        
        if ([[self.arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"%MAC"].location != NSNotFound     ) {
            label.hidden = YES;
        }
        
        
        
        
        if ( ![[_arrayName21 objectAtIndex:13] isEqualToString:@"noLat"]) {
            
            //*************************************************************************************************
            // arm LAT
            NSString *armLatRounded = [NSString stringWithFormat:numberFormat,  [[_arrayName5 objectAtIndex: itemNr ] doubleValue] * factorApplyToNativeDistanceInchMM ];
            
            label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1 + width1 + 3 * width2, (yPosTable + yPix ) + addY, width2, bHeight)];
            label.font = [UIFont systemFontOfSize:fontSize];
            label.textAlignment = NSTextAlignmentRight;
            valueText =  [ [NSString alloc] initWithFormat:numberFormat, [[_arrayName5 objectAtIndex: itemNr ] doubleValue] *  factorApplyToNativeDistanceInchMM ];
            //float tempArmLat = [valueText floatValue];
           
            
            [label  setText: armLatRounded ];
            if (itemNr == 1|| itemNr == 2 ) {             [label  setText: [_arrayName5 objectAtIndex: itemNr ]  ];       }
            if (flagAddStations == 0) {
                 [_viewManifestListo addSubview: label];
            }
            
            
            
            //*************************************************************************************************
            // moment LAT            
            
            label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1 + width1 + 4 * width2, (yPosTable + yPix ) + addY, width2, bHeight)];
            label.font = [UIFont systemFontOfSize:fontSize];
            label.textAlignment = NSTextAlignmentRight;
          
            valueText = [NSString stringWithFormat:numberFormat2, [weightRounded doubleValue] * [armLatRounded doubleValue] ];
            if ([weightRounded doubleValue]  == 0) {
                valueText = @"0";
            }                
           
            if (itemNr == 3   ){            
                //NSLog(@" [[_arrayName4 objectAtIndex: itemNr ] doubleValue] %f ",  [[_arrayName4 objectAtIndex: itemNr ] doubleValue]);            
                valueText = [NSString stringWithFormat:@"%.2f",  [[_arrayName6 objectAtIndex: itemNr ] doubleValue] * factorApplyToNativeMoment ];              
                //NSLog(@"BEW valueText %@", valueText);                
            }          
            
            
            if ([AC_Type rangeOfString:@"R44Raven"].location != NSNotFound   || [AC_Type rangeOfString:@"R44Cadet"].location != NSNotFound  || [AC_Type rangeOfString:@"R22Beta"].location != NSNotFound  ) {
                
                // Robinson specials LAT
                
                if (itemNr != lineZFW & itemNr != lineTOW & itemNr != lineLDW ){                
                    if ([[_arrayName1 objectAtIndex: itemNr]isEqualToString:@"Takeoff Fuel TOTAL"] ) {
                        //do not add the fuel tank                     
                    }else if ([[_arrayName1 objectAtIndex: itemNr]isEqualToString:@"Landing Fuel TOTAL"] ) {
                        //do not add the fuel tank                      
                    }else if ([[_arrayName1 objectAtIndex: itemNr  ] rangeOfString:@"Takeoff Fuel Main"].location != NSNotFound ) {              
                        totalNativeFuelMomentLat = totalNativeFuelMomentLat + [valueText doubleValue];
                        //NSLog(@"%@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText floatValue]); 
                        //NSLog(@"totalNativeFuelMoment %f ", totalNativeFuelMoment);  
                    }else if ([[_arrayName1 objectAtIndex: itemNr  ] rangeOfString:@"Takeoff Fuel Aux"].location != NSNotFound ) {              
                        totalNativeFuelMomentLat = totalNativeFuelMomentLat + [valueText doubleValue];
                        //NSLog(@"%@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText floatValue]); 
                        //NSLog(@"totalNativeFuelMoment %f ", totalNativeFuelMoment);  
                    }else if ([[_arrayName1 objectAtIndex: itemNr ] rangeOfString:@"Landing Fuel Main"].location != NSNotFound ) {              
                        totalNativeFuelMomentLatLanding = totalNativeFuelMomentLatLanding + [valueText doubleValue];
                        //NSLog(@"%@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText doubleValue]);  
                        //NSLog(@"totalNativeFuelMomentLanding %f ", totalNativeFuelMomentLanding);  
                    }else if ([[_arrayName1 objectAtIndex: itemNr ] rangeOfString:@"Landing Fuel Aux"].location != NSNotFound ) {              
                        totalNativeFuelMomentLatLanding = totalNativeFuelMomentLatLanding + [valueText doubleValue];
                        //NSLog(@"%@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText doubleValue]);  
                        //NSLog(@"totalNativeFuelMomentLanding %f ", totalNativeFuelMomentLanding);  
                    }else{                    
                        //add the normal stuff
                        totalNativeMomentLat = totalNativeMomentLat + [valueText doubleValue];
                        //NSLog(@"%@ %.2f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText doubleValue]);  
                        //NSLog(@"totalNativeMoment %.2f ", totalNativeMoment);  
                    } 
                    
                    if (itemNr == lineTOW -1  ){
                        valueText = [NSString stringWithFormat:@"%.1f", totalNativeMomentLat  ];
                        //NSLog(@"totalNativeFuelMomentLanding %f ", totalNativeFuelMomentLanding); 
                    }                
                    if (itemNr == lineLDW -1  ){
                        valueText = [NSString stringWithFormat:@"%.1f", totalNativeFuelMomentLatLanding  ];
                        //NSLog(@"totalNativeFuelMomentLanding %f ", totalNativeFuelMomentLanding); 
                    }                
                }
                
                if (itemNr == lineZFW  ){
                    valueText = [NSString stringWithFormat:@"%.2f", totalNativeMomentLat  ];
                    //NSLog(@"lineZFW totalNativeMoment %f", totalNativeMoment);
                    zfwMomentLat = totalNativeMomentLat;
                }
                if (itemNr == lineTOW  ){
                    valueText = [NSString stringWithFormat:@"%.2f", totalNativeMomentLat + totalNativeFuelMomentLat ];
                    //NSLog(@"lineTOW totalNativeMoment %f", totalNativeMoment);
                    totalNativeMomentLat = 0;            
                }        
                if (itemNr == lineLDW  ){
                    valueText = [NSString stringWithFormat:@"%.2f", zfwMomentLat + totalNativeFuelMomentLatLanding  ];
                    //NSLog(@"lineLDW totalNativeMoment %f", zfwMoment + totalNativeFuelMomentLanding );
                }
                
                
            }else{
                
                if (itemNr != lineZFW & itemNr != lineTOW & itemNr != lineLDW ){
                    
                    if (flagMultipleFuelTanks == 1) { 
                        
                        if ([[_arrayName10 objectAtIndex: itemNr]isEqualToString:@"fuelTankTotal"] ) {
                            //do not add the fuel tank  
                            //NSLog(@"3 %@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText floatValue]);  
                        }else if ([[_arrayName1 objectAtIndex: itemNr  ] rangeOfString:@"Fuel TO"].location != NSNotFound ) {              
                            totalNativeMomentLat = totalNativeMomentLat + [valueText doubleValue];
                            //NSLog(@"%@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText floatValue]); 
                            //NSLog(@"totalNativeMoment %f ", totalNativeMoment);  
                        }else if ([[_arrayName1 objectAtIndex: itemNr ] rangeOfString:@"Fuel LD"].location != NSNotFound ) {              
                            totalNativeFuelMomentLatLanding = totalNativeFuelMomentLatLanding + [valueText doubleValue];
                            //NSLog(@"%@ %f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText doubleValue]);  
                            //NSLog(@"totalNativeFuelMomentLanding %f ", totalNativeFuelMomentLanding);  
                        }else{                    
                            //add the normal stuff
                            totalNativeMomentLat = totalNativeMomentLat + [valueText doubleValue];
                            //NSLog(@"%@ %.2f ", [_arrayName1 objectAtIndex: itemNr  ], [valueText doubleValue]);  
                            //NSLog(@"totalNativeMoment %.2f ", totalNativeMoment);  
                        }  
                        
                        if (itemNr == lineLDW -1  ){
                            valueText = [NSString stringWithFormat:@"%.1f", totalNativeFuelMomentLatLanding  ];
                            //NSLog(@"totalNativeFuelMomentLanding %f ", totalNativeFuelMomentLanding); 
                        }
                        
                    }else{                
                      
                        
                        
                        if ([[_arrayName12 objectAtIndex:itemNr] isEqualToString:@"addDOM"] ) {
                                               //do no add this to native
                            }else{
                                  totalNativeMomentLat = totalNativeMomentLat + [valueText doubleValue];
                                
                                if (itemNr == lineLDW -1  ){
                                    totalNativeFuelMomentLatLanding = totalNativeFuelMomentLatLanding + [valueText doubleValue]; 
                                    //NSLog(@"totalNativeFuelMomentLanding %f ", [valueText floatValue]); 
                                }
                            }
                        
                    }
                }
                
                
                
                if (itemNr == lineZFW  ){
                    valueText = [NSString stringWithFormat:@"%.2f", totalNativeMomentLat  ];
                    //NSLog(@"lineZFW totalNativeMoment %f", totalNativeMoment);
                    zfwMomentLat = totalNativeMomentLat;
                }
                if (itemNr == lineTOW  ){
                    valueText = [NSString stringWithFormat:@"%.2f", totalNativeMomentLat  ];
                    //NSLog(@"lineTOW totalNativeMoment %f", totalNativeMoment);
                    totalNativeMomentLat = 0;            
                }        
                if (itemNr == lineLDW  ){
                    valueText = [NSString stringWithFormat:@"%.2f", zfwMomentLat + totalNativeFuelMomentLatLanding  ];
                    //NSLog(@"lineLDW totalNativeMoment %f", zfwMoment + totalNativeFuelMomentLanding );
                }
                
                
            }
            
            
            
            
            
            [label  setText: valueText ];
            if (itemNr == 1|| itemNr == 2 ) {             [label  setText: [_arrayName6 objectAtIndex: itemNr ]  ];    }
            if (flagAddStations == 0) {
                [_viewManifestListo addSubview: label];
            }
            
        }
        
        
        
        // remarks = occupant name
        label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1 , (yPosTable + yPix + 16 ) + addY, width1 + 20, bHeight)];
        label.font = [UIFont systemFontOfSize:fontSize];
        label.textAlignment = NSTextAlignmentLeft;
        label.adjustsFontSizeToFitWidth = YES;   // trick to shrink fonts            
        label.minimumScaleFactor = 0.3;  
        [label  setText: [_arrayName1 objectAtIndex: itemNr ]  ];
        if (isSingleLine == 1) {
            label.hidden = YES;
        }else{
            label.textColor = [UIColor blackColor];
        }
        [label  setText: [_arrayName7 objectAtIndex: itemNr ]  ];
        
        if (![[_arrayName14 objectAtIndex: itemNr ] isEqualToString:@"fuelSlider"]) {
          [_viewManifestListo addSubview: label];   
        }
          
        
        yPix = yPix + lineDelta;
        if (itemInOut == 0) {
            yPix = yPix - yInc;
        }
        
        float topY = 2; // top line of manifest
        
        yBottomManifest = yPix - topY;
        
        if (i == listEnd) {
            UIImageView * vline =[[UIImageView alloc] initWithFrame:CGRectMake(noLatXpush + xPos1 + width1 +30, topY, 1.0,  yBottomManifest  ) ];
            vline.backgroundColor = [UIColor blackColor];
            vline.alpha = 0.6;
            [_viewManifestListo addSubview: vline];           
            
            vline =[[UIImageView alloc] initWithFrame:CGRectMake(noLatXpush +  xPos1 + width1 + 1 * width2 + 10 , topY, 1.0,  yBottomManifest  ) ];
            vline.backgroundColor = [UIColor blackColor];
            vline.alpha = 0.6;
            [_viewManifestListo addSubview: vline];            
            vline =[[UIImageView alloc] initWithFrame:CGRectMake(noLatXpush + xPos1 + width1 + 2 * width2 + 10 - 10 , topY, 1.0,  yBottomManifest  ) ];
            vline.backgroundColor = [UIColor blackColor];
            vline.alpha = 0.6;
            [_viewManifestListo addSubview: vline];            
            if ( ![[_arrayName21 objectAtIndex:13] isEqualToString:@"noLat"]) {
                
            vline =[[UIImageView alloc] initWithFrame:CGRectMake(xPos1 + width1 + 3 * width2 + 10 , topY, 1.0,  yBottomManifest  ) ];
            vline.backgroundColor = [UIColor blackColor];
            vline.alpha = 0.6;
            [_viewManifestListo addSubview: vline];
            
            vline =[[UIImageView alloc] initWithFrame:CGRectMake(xPos1 + width1 + 4 * width2 + 10 , topY, 1.0,  yBottomManifest  ) ];
            vline.backgroundColor = [UIColor blackColor];
            vline.alpha = 0.6;
            [_viewManifestListo addSubview: vline];
                
            }
        }
    }// end make al to list End
    

    _buttonSignManifest.hidden = NO;
    _buttonSendLoadManifestViaEmail.frame = CGRectMake(216,0,211,49);    
    if (flagSpecialPHIFlightSettingPage == 1) {
        //hide pilot signature option
        _buttonSignManifest.hidden = YES;        
        UIView *hideSigView = [[UIView alloc] initWithFrame:CGRectMake(80, 1115, 190, 25)];
        hideSigView.backgroundColor = [UIColor whiteColor];      
        [_viewManifestListo addSubview:hideSigView];
        _buttonSendLoadManifestViaEmail.frame = CGRectMake(0,0,427,49);        
    }
    
    return;
    
    
} // buttons sliders and interior



 



- (void) setSliders {
    
    
    for (int i = 0; i < lineZFW ; i++) {
      
        
        // check if station is on
        if ([[_arrayName8 objectAtIndex:i] isEqualToString:@"1"]) {
            
            // check if station is a slider
            
            if ([[_arrayName14 objectAtIndex:i] isEqualToString:@"-"]) {
                
             //NSLog(@"slider is i %d ", i);
                
                
                UISlider *slider = (UISlider*)[_viewStationsSlider viewWithTag:  i];
                if (!slider) {
                    slider = (UISlider*)[_viewStationsSliderRight viewWithTag:  i];
                }
                slider.value = [[_arrayName2 objectAtIndex:i] floatValue];
                
                valueField = (UITextField*)[_viewStationsSlider viewWithTag: i + 1000];
                if (valueField == nil) {
                    valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: i + 1000];
                }

                [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [[_arrayName2 objectAtIndex:i]  floatValue]]  ];
                
            }
            
            
            
            
        }
        
        
       
        
    }
    
    
}



- (void) createListoItemsSlidersAndInterior {
    
    //NSLog(@"createListoItemsSlidersAndInterior *************************************");    
    //NSLog(@"_arrayName1 %@", _arrayName1);    
    [self findLines];
    
    for(UIView *subview in [_viewStationsSlider subviews]) {
        [subview removeFromSuperview];
    }
    for(UIView *subview in [_viewStationsSliderRight subviews]) {
        [subview removeFromSuperview];
    }
    for(UIView *subview in [_viewInterior subviews]) {
        [subview removeFromSuperview];
    }
    for(UIView *subview in [_viewCargoInterior subviews]) {
        [subview removeFromSuperview];
    }
    for(UIView *subview in [_viewOptions subviews]) {
        [subview removeFromSuperview];
    }
    
    UIImageView *transparentBack =[[UIImageView alloc] initWithFrame:CGRectMake(0,0,_viewStationsSlider.frame.size.width, _viewStationsSlider.frame.size.height  ) ];
    transparentBack.backgroundColor = [UIColor blackColor];
    transparentBack.alpha = [[_arrayName24 objectAtIndex:9] floatValue];
    [_viewStationsSlider addSubview: transparentBack];
    [_viewStationsSlider sendSubviewToBack:transparentBack];
    _viewStationsSlider.clipsToBounds = YES;
    
    transparentBack =[[UIImageView alloc] initWithFrame:CGRectMake(0,0,_viewStationsSliderRight.frame.size.width, _viewStationsSliderRight.frame.size.height  ) ];
    transparentBack.backgroundColor = [UIColor blackColor];
    transparentBack.alpha = [[_arrayName24 objectAtIndex:9] floatValue];
    [_viewStationsSliderRight addSubview: transparentBack];
    [_viewStationsSliderRight sendSubviewToBack:transparentBack];
    _viewStationsSliderRight.clipsToBounds = YES;       
    
    [self createSegments];
    
    ghostImage =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 90 , 90) ];
    ghostImage.image=[UIImage imageNamed:@"swapStation.png"];
    [_viewInterior addSubview:ghostImage];
    ghostImage.hidden = YES;
    
    float yInc = 40;
    xPos1 = 74;
    width1 = 130;
    width2 = 91;
    yPosTable = 0 - yInc;
    float yPix = 0;  float yPixSlider = 0;
    float lineDeltaSlider = 0;
    
    
    // slider settings   **************************************************************************************************************
    
    float sliderWindowWidth = 200;
    float stationYincrement = 70;  // pixel vertical gap
    float gapLeft = 5;
    float gapRight= 40;
    float sliderYposition = 135 - stationYincrement;  // top of all sliders
    float sliderLR = 0;
    float countLeft = 0;
    float countRight = 0;
    
    int doorInOut = 0;
    
    int forceSeatLabel = 0;
    
    if ( [[_arrayName22 objectAtIndex:41] isEqualToString:@"yes"] ) {
        largeTopViewMode = 1;
        sliderWindowWidth = 255;
        yPixSlider = yPixSlider - stationYincrement;
    }else{
        largeTopViewMode = 0;
    }
    
    /// check if boxed sliders
   if ( [[_arrayName24 objectAtIndex:5] isEqualToString:@"yes"] ) {
       sliderYposition = [[_arrayName24 objectAtIndex:13] floatValue];
   }
    
    
    // other preparations
    
    // scale of interor view
    _viewMeasureRearSeats.hidden = YES;
    _viewMeasureLatRight.hidden = YES;
    _viewMeasureCenter.hidden = YES;
    _viewMeasureFrontSeats.hidden = YES;
    _viewSeatSize.hidden = YES;
    
    for(int i=0; i<_labelCollectionWeightUnits.count; i++) {
        
        UITextField* field = [_labelCollectionWeightUnits objectAtIndex: i  ];
        
        [field  setText: selectedUnitForItems]; // weight units
        
    }
    
    for(int i=0; i<_labelCollectionCGunits.count; i++) {
        if ( [selectedUnitForItems isEqualToString:@"lbs"]) {
            UITextField* field = [_labelCollectionCGunits objectAtIndex: i  ];
            [field  setText: @"In"];
        }else{
            
            if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {                
                UITextField* field = [_labelCollectionCGunits objectAtIndex: i  ];
                [field  setText: @"m"];
            }else{
                
                UITextField* field = [_labelCollectionCGunits objectAtIndex: i  ];
                [field  setText: @"mm"];
                
            }
            
           
        }
    }
    
    
    
    
    
    
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    
    //                                                                 MAKE items for Heli Top View
    
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    
    
    flagCreateFuelPage = 0;
    
    for (int i = listStart; i < listEnd+1 ; i++) {
        //NSLog(@"i   listEnd  %d  %.0f", i,  listEnd);
        
        
        int showItemIfOff = 0;
        
        float itemNr = i;
        float sliderInOut = 1;
        int flagMakeSeatLabels = 1;  // if HOIST or EQUIP then make no seat labels and no quick load
        lineDeltaSlider = 0;
        
        
        // check multiplicator
        if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] < 1) {
            sliderInOut = 0;
        }
        
        // make standby symbol
        if ([[_arrayName16 objectAtIndex: itemNr ] isEqualToString:@"standby"]) {
            sliderInOut = 3;
        }
        
        if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] == 1) {
            sliderInOut = 1;
        }
        
        // check specials and seat names
        if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"NoLabel"].location != NSNotFound) {
            flagMakeSeatLabels = 0;
        }
        
        
        if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"single"].location != NSNotFound) {
            if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] < 1) {
                sliderInOut = 0;
            }
            if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] == 1) {
                lineDeltaSlider = - 10; stationYincrement = 70;
            }
        }else{
            
            stationYincrement = 70;
        }
        
        
        if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"fuel"].location != NSNotFound) {
            sliderInOut = 1;
        }
        
        
        if  ([[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"equip"]) {
            // check multiplicator
            if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] < 1) {
                sliderInOut = 2;
            }
            if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] == 1) {
                //lineDelta = - 12;  itemInOut = 1; sliderInOut = 0; isSingleLine = 1;
                sliderInOut = 2;
            }           
            
        }
        
        
        if  ([[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"door"]) {
            sliderInOut = 4;
            
            if ([[_arrayName8 objectAtIndex: itemNr ] doubleValue] < 1) {
                doorInOut = 0;
            }else{
                doorInOut = 1;
            }            
        }
        
        
        
       
        if  ([[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"showWhenOff"]) {
            sliderInOut = 2; //showItemIfOff = 1;
        }
       
        
        
        
        if  ([[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"noSlider"]) {
            sliderInOut = 0;
        }
        
       
        
        if  ([[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"noSliderNoPicNotOnManifest"]) {
            sliderInOut = 0;
        }
        
      
        
        
        if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"picOnly"].location != NSNotFound) {
            sliderInOut = 2;
        }
        
        if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"picAndLabel"].location != NSNotFound) {
           
            sliderInOut = 2;
        }
        
        if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"picAndLabelLocked"].location != NSNotFound) {
            
            sliderInOut = 2;
        }
        
        //NSLog(@"_arrayName14 %@", _arrayName14);
        
        // if NEXT item is result, then make thick line
        if  ([[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"result"] || [[_arrayName14 objectAtIndex: itemNr  ]  isEqualToString:@"resultIntermediate"]) {
            //NSLog(@"this is a result line ");
            sliderInOut = 0;
            //NSLog(@"i = %d this is a result line ", i);
        }
        
        //NSLog(@"_arrayName10 %@", _arrayName10);
        
        if ([[_arrayName10 objectAtIndex: i  ] rangeOfString:@"fuelTank"].location != NSNotFound   ) {
            
            sliderInOut = 2;            
            flagCreateFuelPage = 1;            
            
        }
        
        
        
        
        yPix = yPix + yInc;
        
        //NSLog(@"ok we have sliderInOut %.0f  for item  %@", sliderInOut, [_arrayName1 objectAtIndex: itemNr  ]);
        
        
        
        // ****************************************************************************************************************************************************
        // ****************************************************************************************************************************************************
        // ****************************************************************************************************************************************************
        // ****************************************************************************************************************************************************
        
        //                                                                 MAKE SLIDERS
        
        
        // ****************************************************************************************************************************************************
        // ****************************************************************************************************************************************************
        // ****************************************************************************************************************************************************
        // ****************************************************************************************************************************************************
        
        
        //NSLog(@"sliderInOut %.0f", sliderInOut);
        
        
        
        
        
        
        /// check if boxed sliders
        if ([[_arrayName24 objectAtIndex:5]isEqualToString:@"yes"]) {
            stationYincrement = [[_arrayName24 objectAtIndex:11] floatValue];
        }
        
        //NSLog(@"stationYincrement %.0f ", stationYincrement);
        
        int mountSliderToRight =0;
        
        if (sliderInOut >= 1 ) {
            
            if (sliderInOut == 1) {
                
                //NSLog (@"making slider i %@ ", [ [NSString alloc] initWithFormat:@"%d ", i]);
                float tagNr = i ;
                // get Lat Postiion for station
                float itemLatPos = [[_arrayName5 objectAtIndex:i] floatValue];
                // check if item contains LH or RH to position the slider right or left
                if ([[_arrayName14 objectAtIndex: tagNr  ] rangeOfString:@"LH"].location != NSNotFound){
                    itemLatPos = -1;
                }
                if ([[_arrayName14 objectAtIndex: tagNr  ] rangeOfString:@"RH"].location != NSNotFound){
                    //NSLog (@"found RH %.0f", itemNr);
                    itemLatPos = 1;
                }
                if (largeTopViewMode == 1) {
                    itemLatPos = -1;
                }
                if (itemLatPos < 0.0 || [ [_arrayName16 objectAtIndex: tagNr  ]  isEqualToString:@"L"] || [ [self.arrayName16 objectAtIndex: tagNr  ]  isEqualToString:@"crew L"] ) {
                    // left
                    sliderLR = 0;
                    if (largeTopViewMode == 1) {
                        yPixSlider = yPixSlider + stationYincrement;
                    }else{
                        yPixSlider = countLeft * stationYincrement;
                    }
                    countLeft = countLeft +1;
                }else{
                    if (itemLatPos >= 0.0 || [ [_arrayName16 objectAtIndex: tagNr  ]  isEqualToString:@"R"] || [ [self.arrayName16 objectAtIndex: tagNr  ]  isEqualToString:@"crew R"] ) {
                        // right
                        sliderLR = 0;
                        if (largeTopViewMode == 1) {
                            yPixSlider = yPixSlider + stationYincrement;
                        }else{
                           yPixSlider = countRight * stationYincrement;
                            
                            mountSliderToRight = 1;
                        }
                        countRight = countRight + 1;
                    }
                }
                
                
                // |||||||||||||| make sliders  in yellow with slider scale
                
                CGRect sliderFrame = CGRectMake(sliderLR+gapLeft, sliderYposition + yPixSlider, (sliderWindowWidth -  gapLeft - gapRight +35) , 10.0);
                UISlider *slider = [[UISlider alloc] initWithFrame:sliderFrame];
                [slider addTarget:self action:@selector(WeightSliderAction:) forControlEvents:UIControlEventValueChanged];
                [slider setBackgroundColor:[UIColor clearColor]];
                slider.minimumValue = 0.0;
                
                // get max weight for slider
                slider.maximumValue = [[_arrayName9 objectAtIndex: itemNr ] doubleValue];
                slider.continuous = YES;
                
                
                
                
                UIImageView *sliderScale =[[UIImageView alloc] initWithFrame:CGRectMake(sliderLR+gapLeft+5, sliderYposition + yPixSlider - 13, (sliderWindowWidth -  gapLeft - gapRight) -10 +35 , 12.0) ];
                sliderScale.image=[UIImage imageNamed:@"sliderScale_wide20forPA-01.png"]; // sliderScale120-01.png  // sliderScale_wide20forPA-01.png
                sliderScale.alpha = 0.6;
                
                
                if (mountSliderToRight == 1) {
                    [self.viewStationsSliderRight addSubview:sliderScale];
                }else{
                    [self.viewStationsSlider addSubview:sliderScale];
                }
                
                UIImage *sliderImage = [UIImage imageNamed:@"sliderEmpty.png"];
                UIImage *sliderThumb = [UIImage imageNamed:@"triangle3.png"]; //triangle3.png
                UIImage *sliderImageEmpty;
                
                if ([[_arrayName21 objectAtIndex:47] isEqualToString:@"Yellow"]) {
                    sliderImageEmpty = [UIImage imageNamed:@"sliderYellowLine thin.png"];
                }else{
                    sliderImageEmpty = [UIImage imageNamed:@"sliderGreenLine thin.png"];
                }
                
                [slider setMaximumTrackImage:sliderImage forState:UIControlStateNormal];
                [slider setMinimumTrackImage:sliderImageEmpty forState:UIControlStateNormal];
                [slider setThumbImage:sliderThumb forState:UIControlStateNormal];
                
                // set slider to weight
                slider.value = [[_arrayName2 objectAtIndex:tagNr] floatValue];
                slider.tag = tagNr;
                //NSLog(@"adding slider tag %d ", slider.tag );
                
                if (mountSliderToRight == 1) {
                    [self.viewStationsSliderRight addSubview:slider];
                }else{
                    [self.viewStationsSlider addSubview:slider];
                }
                
                
                // |||||||||||||| make slider weightLabels
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(sliderLR+gapLeft+18, sliderYposition + yPixSlider - 46- lineDeltaSlider, (sliderWindowWidth -  gapLeft - gapRight - 23), 15.0)];
                label.font = [UIFont boldSystemFontOfSize:17.0];
                label.textColor = [UIColor whiteColor];
                label.textAlignment = NSTextAlignmentRight;
                label.text = [ [NSString alloc] initWithFormat:@"%.0f", slider.value * factorApplyToNativeWeightforItems   ];
                label.tag = tagNr + 1000;
                if (mountSliderToRight == 1) {
                    [self.viewStationsSliderRight addSubview:label];
                }else{
                   [self.viewStationsSlider addSubview:label];
                }
                
                if (tagNr == lineHoistLoad) {                  
                    label= [[UILabel alloc] initWithFrame:CGRectMake(sliderLR+gapLeft + 10, sliderYposition + yPixSlider + 5  , (sliderWindowWidth ), 17.0) ];
                    label.font = [UIFont boldSystemFontOfSize:13.0];
                    label.textColor = [UIColor whiteColor];                    
                    label.textAlignment = NSTextAlignmentLeft;                    
                    label.text = @"";                    
                    label.tag = tagNr + 1500;  
                   
                  
                    if (mountSliderToRight == 1) {
                        [self.viewStationsSliderRight addSubview:label];
                    }else{
                       [self.viewStationsSlider addSubview:label];
                    }
                     
                }
                
                
                // |||||||||||||| make station names
                //NSLog(@"lineDeltaSlider %.0f ", lineDeltaSlider);
                label= [[UILabel alloc] initWithFrame:CGRectMake(sliderLR+gapLeft + 10, sliderYposition + yPixSlider - 47 - lineDeltaSlider, (sliderWindowWidth -  gapLeft - gapRight - 57), 17.0)];
                label.font = [UIFont boldSystemFontOfSize:15.0];
                //label.textColor =[UIColor colorWithRed:140.0f/255.0f green:186.0f/255.0f blue:253.0f/255.0f alpha:1.0f]; // light blue
                label.textColor = [UIColor whiteColor];          
                label.adjustsFontSizeToFitWidth = YES;   // trick to shrink fonts            
                label.minimumScaleFactor = 0.3;                
                label.alpha = 1.0;
                // get name for station
                label.text = [_arrayName1 objectAtIndex:tagNr];
                label.tag = tagNr + 1100;
                
                if (mountSliderToRight == 1) {
                   [self.viewStationsSliderRight addSubview:label];
                }else{
                    [self.viewStationsSlider addSubview:label];
                }
                
                // |||||||||||||| make occupant names
                label= [[UILabel alloc] initWithFrame:CGRectMake(sliderLR+gapLeft + 10, sliderYposition + yPixSlider - 29 , (sliderWindowWidth -  gapLeft - gapRight), 17.0) ];
                label.font = [UIFont systemFontOfSize:15.0];
                label.textColor =[UIColor colorWithRed:140.0f/255.0f green:186.0f/255.0f blue:253.0f/255.0f alpha:1.0f]; // light blue
                //label.textColor = [UIColor whiteColor];
                label.alpha = 1.0;
                label.adjustsFontSizeToFitWidth = YES;   // trick to shrink fonts            
                label.minimumScaleFactor = 0.3;      
                if (lineDeltaSlider < 0) {
                    label.hidden = YES;
                }else{
                    label.hidden = NO;
                }
                // get name for station ( 0is station name, 700 is remarks or Name of occupant)
                label.text = [_arrayName7 objectAtIndex:tagNr];
                label.tag = tagNr + 1200;
               
                if (mountSliderToRight == 1) {
                     [self.viewStationsSliderRight addSubview:label];
                }else{
                     [self.viewStationsSlider addSubview:label];
                }
                
                
                // |||||||||||||| make enter pad buttons
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(sliderLR+sliderWindowWidth - gapRight - 45, sliderYposition + yPixSlider - 49 - lineDeltaSlider , 50, 20); // pos x, pos y, width x, width y
                [btn addTarget:self  action:@selector(buttonActionEnterPadListo:)  forControlEvents:UIControlEventTouchUpInside];
                btn.tag = tagNr + 1300;
                btn.backgroundColor = [UIColor clearColor];
                btn.alpha = 1.0;
                UIImage *buttonKlammern = [UIImage imageNamed:@"Klammern.png"];
                [btn  setBackgroundImage:buttonKlammern forState:UIControlStateNormal];
                if (mountSliderToRight == 1) {
                     [self.viewStationsSliderRight addSubview:btn];
                }else{
                     [self.viewStationsSlider addSubview:btn];
                }
                
                
                if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"single"].location != NSNotFound) {
                    
                }else{
                    
                    // |||||||||||||| make ride along button
                    btn = [UIButton buttonWithType:UIButtonTypeCustom];
                    btn.frame = CGRectMake(sliderLR+gapLeft + 10, sliderYposition + yPixSlider - 50 - lineDeltaSlider , 90, 42) ;
                    [btn addTarget:self  action:@selector(buttonActionEnterRideAlong:)  forControlEvents:UIControlEventTouchUpInside];
                    btn.tag = tagNr + 1300;
                    btn.backgroundColor = [UIColor clearColor];
                    if (mountSliderToRight == 1) {
                         [self.viewStationsSliderRight addSubview:btn];
                    }else{
                         [self.viewStationsSlider addSubview:btn];
                    }
                    
                    
                }
                
               
                
                // |||||||||||||| make unit labels
                label= [[UILabel alloc] initWithFrame:CGRectMake(sliderLR+sliderWindowWidth - gapRight +9, sliderYposition + yPixSlider - 53 - lineDeltaSlider, 35, 27) ];
                label.font = [UIFont systemFontOfSize:15.0];
                label.textColor =[UIColor colorWithRed:140.0f/255.0f green:186.0f/255.0f blue:253.0f/255.0f alpha:1.0f]; // light blue
                //label.textColor = [UIColor whiteColor];
                label.alpha = 1.0;
                label.textAlignment = NSTextAlignmentLeft;
                label.text = selectedUnitForItems;
                label.tag = tagNr + 1400;
               
                if (mountSliderToRight == 1) {
                    [self.viewStationsSliderRight addSubview:label];
                }else{
                    [self.viewStationsSlider addSubview:label];
                }
                
                }
            
            /// check if boxed sliders
            if ( [[_arrayName24 objectAtIndex:5] isEqualToString:@"yes"] ) {
                
                //= CGRectMake(sliderLR+gapLeft, sliderYposition + yPixSlider, (sliderWindowWidth -  gapLeft - gapRight +35) , 10.0);
                float boxHeight = 0;
                float YposAdjust = 0;
                if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"single"].location != NSNotFound) {
                    boxHeight = 80; YposAdjust = 10;
                }else{
                   boxHeight = 105;
                }
                UIImageView *sliderBox =[[UIImageView alloc] initWithFrame:CGRectMake(0, sliderYposition + yPixSlider - 65 + YposAdjust, 195 , boxHeight ) ];
                sliderBox.backgroundColor = [UIColor clearColor];
                sliderBox.image=[UIImage imageNamed: [_arrayName24 objectAtIndex:15 ] ];
                sliderBox.alpha = [[_arrayName24 objectAtIndex:7] floatValue];
                
                if (mountSliderToRight == 1) {
                    [_viewStationsSliderRight addSubview: sliderBox];
                    [_viewStationsSliderRight sendSubviewToBack:sliderBox];
                }else{
                    [_viewStationsSlider addSubview: sliderBox];
                    [_viewStationsSlider sendSubviewToBack:sliderBox];
                }
            }
            
           
           
            
            
            
            
            // ****************************************************************************************************************************************************
            // ****************************************************************************************************************************************************
            // ****************************************************************************************************************************************************
            // ****************************************************************************************************************************************************
            
            //                                                                 MAKE INTERIOR  (seats tag = 1500,   quick load tag = 1600
            
            // ****************************************************************************************************************************************************
            // ****************************************************************************************************************************************************
            // ****************************************************************************************************************************************************
            // ****************************************************************************************************************************************************
            
            
            float LongScale = (_viewMeasureRearSeats.center.y - _viewMeasureFrontSeats.center.y) / (LongArmRearSeat - LongArmFrontSeat) ;
            float LatPixLeftSeat    = _viewMeasureCenter.center.x;
            float LatPixRightSeat  = _viewMeasureLatRight.center.x;
            float LatScale = (LatPixRightSeat - LatPixLeftSeat) / (LatArmRightSeat - LatArmLeftSeat) ;
            
            
            //NSLog (@"LatArmRightSeat %f@ ", LatArmRightSeat);
            float itemWidth = _viewSeatSize.layer.frame.size.width;
            float itemHeight = _viewSeatSize.layer.frame.size.height;
            
           
            
            _viewCargoInterior.frame = CGRectMake(_viewInterior.frame.origin.x, _viewInterior.frame.origin.y, _viewInterior.frame.size.width, _viewInterior.frame.size.height);
            
            if (i >= linePilot  & i <= lineLDW-1 ) {
                
                // get Long Postiion for station
                float itemLong = [[_arrayName3 objectAtIndex:i] floatValue];
                // get Lat Postiion for station
                float itemLat = [[_arrayName5 objectAtIndex:i] floatValue];
                
                if ([[_arrayName18 objectAtIndex: i ] rangeOfString:@"fixed"].location != NSNotFound   ) {
                    itemLong = [[_arrayName18 objectAtIndex:i] floatValue];
                    itemLat = 0;
                }
                
                
                float LongPixPosition = 0;
                float LatPixPosition = 0;
                //NSLog (@"itemLong  %@ ", [ [NSString alloc] initWithFormat:@"%.1f ", itemLong ]);
                //NSLog (@"LongPixPosition  %@ ", [ [NSString alloc] initWithFormat:@"%.1f ", LongPixPosition ]);
                
                
                float yOffset = [[_arrayName11 objectAtIndex: i  ] doubleValue];
                float latOffset = [[_arrayName13 objectAtIndex: i  ] doubleValue];
                
                UIImageView *interiorItem =[[UIImageView alloc] initWithFrame:CGRectMake(LatPixPosition + latOffset, LongPixPosition + yOffset, itemWidth , itemHeight ) ];
                
                if ([[_arrayName10 objectAtIndex: i  ]  isEqualToString:@"0"] || [[_arrayName10 objectAtIndex: i  ]  isEqualToString:@""] ) {
                    interiorItem.image=[UIImage imageNamed: @"empty.png" ];
                    itemWidth = 0;
                    itemHeight = 0;
                    
                    //NSLog(@"showing  %.0f  for item  %@", itemNr, [_arrayName1 objectAtIndex: itemNr  ]);
                    
                }
                
                if ([[_arrayName10 objectAtIndex: i  ] rangeOfString:@"!"].location != NSNotFound    ) {
                    interiorItem.image=[UIImage imageNamed: @"empty.png" ];
                }
                
                
                int isIndividualSize = 0;
                // set special size (if entered in Excel)
                if (![[_arrayName19 objectAtIndex: i  ]  isEqualToString:@""]      ) {
                    itemWidth =  [[_arrayName19 objectAtIndex: i  ]floatValue];
                    itemHeight = [[_arrayName20 objectAtIndex: i  ]floatValue];
                    interiorItem.frame = CGRectMake(LatPixPosition + latOffset, LongPixPosition + yOffset, itemWidth , itemHeight );
                    isIndividualSize = 1;
                }
                
                LongPixPosition =  (( (LongScale * (itemLong - LongArmFrontSeat)) + _viewMeasureFrontSeats.center.y  )  - (itemHeight/2))   ;
                LatPixPosition =   ( (LatScale *  (itemLat -  LatArmLeftSeat))   + LatPixLeftSeat      )  - (itemWidth/2);
                interiorItem.frame = CGRectMake(LatPixPosition + latOffset, LongPixPosition + yOffset, itemWidth , itemHeight );
                
                
                interiorItem.alpha = 1.0;
                interiorItem.tag = i + 1500;
                
                float rotationAngle = [[_arrayName15 objectAtIndex: i] floatValue];
                if (rotationAngle != 0) {
                    float angleRadiants =  rotationAngle * 0.01745;
                    interiorItem.transform =CGAffineTransformMakeRotation(angleRadiants);
                }
                
                // check if item goes on normal or cargo level
                
                int itemForCargoLevel = 0;
                if ([[_arrayName24 objectAtIndex: i  ]  isEqualToString:@"cargoLevel"] ) {
                    itemForCargoLevel = 1;
                }
                
                
                if (itemForCargoLevel == 0) {
                    
                    if (showItemIfOff == 0) {
                        
                       if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"picAndLabel"].location != NSNotFound) {                           
                           if ([[_arrayName8 objectAtIndex: itemNr  ] floatValue] > 0) {
                               [_viewInterior addSubview:interiorItem]; 
                           }
                       }else{
                          [_viewInterior addSubview:interiorItem]; 
                           
                       }
                       
                        
                        //NSLog(@"showing  %.0f  for item  %@", itemNr, [_arrayName1 objectAtIndex: itemNr  ]);
                        
                        
                    }
                }else{
                    [_viewCargoInterior addSubview:interiorItem];
                    //NSLog (@"item goes on cargo level");
                }
                
                int picException = 0;
                if ([[_arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"picAndLabel"].location != NSNotFound) {
                    picException = 1;
                }
                
                if (sliderInOut == 1 & flagMakeSeatLabels == 1 || picException == 1 ) {
                    
                    int seatIsForward = 0;
                    if (rotationAngle < -95) {
                        seatIsForward = 0;
                    }else if (rotationAngle > 95)  {
                        seatIsForward = 0;
                    }else{
                        seatIsForward = 1;
                    }
                    
                    float yOffsetLabel1 = 0;
                    float yOffsetLabel2= 0;
                    if (seatIsForward == 1) {
                        yOffsetLabel1 = -35;
                        yOffsetLabel2 = 2;
                    }else{
                        // rearward seat
                        yOffsetLabel1 = -7;
                        yOffsetLabel2 = 9;
                    }
                    
                    
                    //NSLog(@"yOffsetLabel1 %@ seatIsForward %d", [_arrayName1 objectAtIndex: itemNr  ], seatIsForward);
                    
                    
                    //NSLog(@"yOffsetLabel1 %.0f",  yOffsetLabel1);
                    
                    //NSLog(@"yOffsetLabel2 %.0f", yOffsetLabel2);
                    
                    // ||||||||||||||   make seat labels
                    
                    if ([[_arrayName8 objectAtIndex: itemNr  ] floatValue] > 0) {
                        
                        if (_segmentNamesOnSeats.selectedSegmentIndex == 0 ) {
                            //old style
                            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(LatPixPosition + latOffset + 6, LongPixPosition + yOffset, itemWidth - 12 , itemHeight ) ];
                            label.font = [UIFont systemFontOfSize:14.0];
                            //label.textColor =[UIColor colorWithRed:160.0f/255.0f green:186.0f/255.0f blue:253.0f/255.0f alpha:1.0f]; // light blue
                            label.textColor = [UIColor blackColor];
                            label.textAlignment = NSTextAlignmentCenter;
                            label.text = [_arrayName12 objectAtIndex: i  ];
                            label.adjustsFontSizeToFitWidth = YES;   // trick to shrink fonts            
                            label.minimumScaleFactor = 0.3;  
                            label.tag = i ;
                            if (itemForCargoLevel == 0) {
                                [_viewInterior addSubview:label];                           
                                
                            }else{
                                [_viewCargoInterior addSubview:label];
                            }
                        }
                      
                        
                        if (_segmentNamesOnSeats.selectedSegmentIndex == 1 || _segmentNamesOnSeats.selectedSegmentIndex == 2) {
                              
                            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(LatPixPosition + latOffset, LongPixPosition + yOffset + yOffsetLabel1, itemWidth , itemHeight ) ];
                            if (isIndividualSize == 1) {  
                                if (seatIsForward == 1) {
                                     label.frame = CGRectMake(interiorItem.frame.origin.x + 2, interiorItem.frame.origin.y + (interiorItem.frame.size.height/2) - 21, interiorItem.frame.size.width - 4, 25);
                                }else{
                                    label.frame = CGRectMake(interiorItem.frame.origin.x + 2, interiorItem.frame.origin.y + (interiorItem.frame.size.height/2) - 17, interiorItem.frame.size.width - 4, 25); 
                                    
                                }
                               
                            }
                            label.font = [UIFont systemFontOfSize:14.0];
                            label.textColor = [UIColor blackColor];
                            label.textAlignment = NSTextAlignmentCenter;
                            label.text = [NSString stringWithFormat:@"%.0f", [[_arrayName2 objectAtIndex: i  ] floatValue]];
                            label.adjustsFontSizeToFitWidth = YES;   // trick to shrink fonts            
                            label.minimumScaleFactor = 0.3;                             
                            label.tag = i + 200 ;
                            if (itemForCargoLevel == 0) {
                                [_viewInterior addSubview:label];
                            }else{
                                [_viewCargoInterior addSubview:label];
                            }
                            label= [[UILabel alloc] initWithFrame:CGRectMake(LatPixPosition + latOffset + 2, LongPixPosition + yOffset + yOffsetLabel2, itemWidth - 4 , itemHeight ) ];
                            if (isIndividualSize == 1) {
                                
                                 if (seatIsForward == 1) {
                                     label.frame = CGRectMake(interiorItem.frame.origin.x, interiorItem.frame.origin.y + (interiorItem.frame.size.height/2) -7, interiorItem.frame.size.width, 25);
                                     
                                 }else{
                                     label.frame = CGRectMake(interiorItem.frame.origin.x, interiorItem.frame.origin.y + (interiorItem.frame.size.height/2) -4, interiorItem.frame.size.width, 25);
                                     
                                 }
                                
                            }
                            
                            label.font = [UIFont systemFontOfSize:9.5];
                            //label.textColor =[UIColor colorWithRed:160.0f/255.0f green:186.0f/255.0f blue:253.0f/255.0f alpha:1.0f]; // light blue
                            label.numberOfLines = 2;
                            label.textColor = [UIColor blackColor];
                            label.textAlignment = NSTextAlignmentCenter;
                            label.adjustsFontSizeToFitWidth = YES;   // trick to shrink fonts 
                            label.tag = i + 700 ;
                            if (itemForCargoLevel == 0) {
                                [_viewInterior addSubview:label];
                            }else{
                                [_viewCargoInterior addSubview:label];
                            }
                        }
                        
                        //NSLog(@"make quick load buttons  %d  %@", i, [_arrayName1 objectAtIndex:i]);
                        
                        // |||||||||||||| make quick load buttons
                        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                        btn.frame = CGRectMake(LatPixPosition + latOffset , LongPixPosition + yOffset, itemWidth , itemHeight ) ;                    
                        float rotationAngle = [[_arrayName15 objectAtIndex: i] floatValue];
                        if (rotationAngle != 0) {
                            float angleRadiants =  rotationAngle * 0.01745;
                            btn.transform =CGAffineTransformMakeRotation(angleRadiants);
                        }                    
                        [btn addTarget:self  action:@selector(actionTapOnStation:)  forControlEvents:UIControlEventTouchUpInside];
                        [btn addTarget:self  action:@selector(actionTapOnStationHOLD:)  forControlEvents:UIControlEventTouchDown];
                        
                        
                        btn.tag = i + 1600;
                        btn.backgroundColor = [UIColor clearColor];
                        
                        UILongPressGestureRecognizer *recognizerTapAndHold = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(actionTapAndHold:)];
                        [btn addGestureRecognizer:recognizerTapAndHold];
                        
                        if (itemForCargoLevel == 0) {
                            [_viewInterior addSubview:btn];
                        }else{
                            [_viewCargoInterior addSubview:btn];
                        }
                        
                    }
                    
                    
                
                    
                    
                    
                    
                    
                } // end if slider IN - this adds names and seat labels
                
                
                if (sliderInOut == 3  ) {
                    
                    //  make quick load buttons for STANDBY (open pilot list)
                    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                    btn.frame = CGRectMake(LatPixPosition + latOffset , LongPixPosition + yOffset, itemWidth , itemHeight ) ;
                    [btn addTarget:self  action:@selector(actionTapOnStationStandby:)  forControlEvents:UIControlEventTouchUpInside];
                    
                    btn.tag = i + 1600;
                    btn.backgroundColor = [UIColor clearColor];
                    if (itemForCargoLevel == 0) {
                        [_viewInterior addSubview:btn];
                    }else{
                        [_viewCargoInterior addSubview:btn];
                    }
                }
                
                if (sliderInOut == 4  ) {
                    
                    //  make doors "door"
                    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                    btn.frame = CGRectMake(LatPixPosition + latOffset , LongPixPosition + yOffset, itemWidth , itemHeight ) ;
                    [btn addTarget:self  action:@selector(actionDoorOnOff:)  forControlEvents:UIControlEventTouchUpInside];
                    
                    btn.tag = i + 1700;
                    btn.backgroundColor = [UIColor clearColor];
                    [_viewInterior addSubview:btn];
                }
                
                
                if (forceSeatLabel == 1 ) {
                    //NSLog(@"make pic label  %@", [_arrayName12 objectAtIndex: i  ]);
                    UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(LatPixPosition + latOffset, LongPixPosition + yOffset, itemWidth , itemHeight ) ];
                    label.font = [UIFont systemFontOfSize:14.0];
                    //label.textColor =[UIColor colorWithRed:160.0f/255.0f green:186.0f/255.0f blue:253.0f/255.0f alpha:1.0f]; // light blue
                    label.textColor = [UIColor blackColor];
                    label.textAlignment = NSTextAlignmentCenter;
                    label.text = [_arrayName12 objectAtIndex: i  ];
                    label.tag = i ;
                    label.backgroundColor = [UIColor yellowColor];
                    [_viewInterior addSubview:label];
                    
                }

                
                
                
                
            } // for next end make interior
            
            
        }// ende make a slider
        
        
        
        
        
        
    }// end make al to list End
    
    
    int maxCount = 0;
    if (countLeft >= countRight) {
        maxCount = countLeft;
    }else{
        maxCount = countRight;
    }
    if (maxCount < 10 ) {
        maxCount = 10;
    }
    
   
    
    if (largeTopViewMode == 1) {
        UIView *balken =[[UIView alloc] initWithFrame:CGRectMake(250, 0, 1 , maxCount * (stationYincrement+20)) ];
        balken.backgroundColor = [UIColor lightGrayColor];
        [self.viewStationsSlider addSubview:balken];
    }
    
    //NSLog(@"yPixSlider %.0f", yPixSlider);
    //NSLog(@"sliderYposition %.0f", sliderYposition);
    //NSLog(@"flagFuelVisisble %.0f", flagFuelVisisble);
    
    yPixSliderValue = yPixSlider;
  
    float addForPanelHeight = 0;
    if (flagFuelVisisble == 1) {
        addForPanelHeight = [[_arrayName22 objectAtIndex:37] floatValue]; //fuelPanelHeight
    }
    
    //NSLog(@"addForPanelHeight %@f", [_arrayName22 objectAtIndex:37] );
    
    [_scrollViewStations setContentSize:CGSizeMake(_viewStationsSlider.frame.size.width, yPixSliderValue + 150 + addForPanelHeight)];
    [_scrollViewStationsRight setContentSize:CGSizeMake(_viewStationsSliderRight.frame.size.width, yPixSliderValue + 150 + addForPanelHeight)];
   
    
    
    /*
     UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(0 , 0, 30, 30 ) ];
     label.font = [UIFont systemFontOfSize:15.0];
     label.textColor = [UIColor whiteColor];
     label.textAlignment = NSTextAlignmentCenter;
     label.backgroundColor = [UIColor greenColor];
     label.text = @"Hello";
     [_viewCargoInterior addSubview:label];
     */
    
    //NSLog(@"1 flagCreateFuelPage %d", flagCreateFuelPage);
    if (flagCreateFuelPage == 1) {
        [self createFuelPage];
    }
    
    
    previousConfiguration = configuration;
    //[self searchbutSelHeli];
    
    return;
    
    
} // buttons sliders and interior







- (void) createFuelPage {
    
    //NSLog(@"createFuelPage");
    
    for(UIView *subview in [_viewFuelSliders subviews]) {
        [subview removeFromSuperview];
    }
    
    
    // how many fuel tanks do we have?
    // count fuel tanks
    int fuelTankCountTO = 0;
    int fuelTankCountTotalTO = 0;
    int fuelTankCountLD = 0;
    int fuelTankCountTotalLD = 0;
    
    int fuelTanksTotalTakeoff = 0;
    int fuelTanksTotalLanding = 0;
    
    for (int i = 3; i < _arrayName1.count ; i++) {
        
        if ([[_arrayName10 objectAtIndex: i  ] isEqualToString:@"fuelTank"]) {
            if (i < lineTOW) {
                fuelTanksTotalTakeoff = fuelTanksTotalTakeoff +1;
            }else{
                fuelTanksTotalLanding = fuelTanksTotalLanding +1;
            }
            
        }
        
        
        if ([[_arrayName10 objectAtIndex: i  ] isEqualToString:@"fuelTank"] && [[_arrayName8 objectAtIndex: i] isEqualToString:@"1"] ){
            if (i < lineTOW) {
                 fuelTankCountTO = fuelTankCountTO +1;
            }else{
                 fuelTankCountLD = fuelTankCountLD +1;
            }
        }
        
        if ([[_arrayName10 objectAtIndex: i  ] isEqualToString:@"fuelTankTotal"] && [[_arrayName8 objectAtIndex: i] isEqualToString:@"1"] ){
            if (i < lineTOW) {
                fuelTankCountTotalTO = fuelTankCountTotalTO +1;
            }else{
                fuelTankCountTotalLD = fuelTankCountTotalLD +1;
            }
        }
    }
    
    //NSLog(@"fuelTanksTotalTakeoff %d", fuelTanksTotalTakeoff);
    //NSLog(@"fuelTanksTotalLanding %d", fuelTanksTotalLanding);
    
    
     //NSLog(@"fuelTankCountTO %d", fuelTankCountTO);
     //NSLog(@"fuelTankCountTotalTO %d", fuelTankCountTotalTO);
     //NSLog(@"fuelTankCountLD %d", fuelTankCountLD);
     //NSLog(@"fuelTankCountTotalLD %d", fuelTankCountTotalLD);
    
    
    
    
    
    float yInc = 40;
    xPos1 = 74;
    width1 = 130;
    width2 = 91;
    yPosTable = 0 - yInc;
    
    // slider settings   **************************************************************************************************************
    
    if ( [selectedUnitForFuel isEqualToString:@"kg"]) {
        if ([fuelEnterMode isEqualToString:@"mass"]) {
            fuelUnitsPresented = @"kg";
        }else{
            fuelUnitsPresented = @"ltr";
        }
    }else{
        if ([fuelEnterMode isEqualToString:@"mass"]) {
            fuelUnitsPresented = @"lbs";
        }else{
            fuelUnitsPresented = @"gal";
        }
    }
    
  
    
    
    float yVersatz = -70;
    
    // |||||||||||||| takeoff label
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, _viewFuelSliders.frame.size.width, 25.0)];
    label.font = [UIFont systemFontOfSize:15.0];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentLeft;
    label.text = [ [NSString alloc] initWithFormat:@"Takeoff"   ];
    [_viewFuelSliders addSubview:label];
    
    // |||||||||||||| landing label to the right
    label = [[UILabel alloc] initWithFrame:CGRectMake(450, 5, _viewFuelSliders.frame.size.width, 25.0)];
    label.font = [UIFont systemFontOfSize:15.0];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentLeft;
    label.text = [ [NSString alloc] initWithFormat:@"Landing"   ];
    [_viewFuelSliders addSubview:label];

    
    
    
    // total fuel display
           label = [[UILabel alloc] initWithFrame:CGRectMake(0, 80 + yVersatz, _viewFuelSliders.frame.size.width, 25.0)];
           label.font = [UIFont systemFontOfSize:15.0];
           label.textColor = [UIColor whiteColor];
           label.textAlignment = NSTextAlignmentCenter;
           label.text = [ [NSString alloc] initWithFormat:@"Total Fuel Takeoff"   ];
           [_viewFuelSliders addSubview:label];
           
           
           // |||||||||||||| total fuel display
           label = [[UILabel alloc] initWithFrame:CGRectMake(0, 100 + yVersatz, _viewFuelSliders.frame.size.width, 25.0)];
           label.font = [UIFont boldSystemFontOfSize:16.0];
           label.textColor = [UIColor whiteColor];
           label.textAlignment = NSTextAlignmentCenter;
           label.text = [ [NSString alloc] initWithFormat:@"%.0f %@", 999.9, fuelUnitsPresented  ];
           label.tag = 2000;
           [_viewFuelSliders addSubview:label];
           
           // |||||||||||||| total fuel display
           label = [[UILabel alloc] initWithFrame:CGRectMake(0, 140 + yVersatz, _viewFuelSliders.frame.size.width, 25.0)];
           label.font = [UIFont systemFontOfSize:15.0];
           label.textColor = [UIColor whiteColor];
           label.textAlignment = NSTextAlignmentCenter;
           label.text = [ [NSString alloc] initWithFormat:@"Total Fuel Landing"   ];
           [_viewFuelSliders addSubview:label];
           
           
           // |||||||||||||| total fuel display
           label = [[UILabel alloc] initWithFrame:CGRectMake(0, 160 + yVersatz, _viewFuelSliders.frame.size.width, 25.0)];
           label.font = [UIFont boldSystemFontOfSize:16.0];
           label.textColor = [UIColor whiteColor];
           label.textAlignment = NSTextAlignmentCenter;
           label.text = [ [NSString alloc] initWithFormat:@"%.0f %@", 999.9 , fuelUnitsPresented  ];
           label.tag = 2010;
           [_viewFuelSliders addSubview:label];
    
    
   
    //takeoff fuel
    fuelStart = lineZFW + 1;
    fuelEnd = lineZFW + fuelTanksTotalTakeoff;
    fuelSliderTopPosition = 128 - 60;
    [self createFuelSliders];
    
    // landing fuel
    fuelStart = lineTOW + 1;
    fuelEnd = lineTOW + fuelTanksTotalLanding;
    fuelSliderTopPosition = 128 - 60;
    [self createFuelSliders];
    
    
    
    
    
    
    
}

- (void) createFuelSliders {
    
    //NSLog(@"createFuelSliders");
    
    float sliderWindowWidth = 200;
    float stationYincrement = 60;  // pixel vertical gap
    float gapLeft = 5;
    float gapRight= 40;
    float sliderYposition = fuelSliderTopPosition;  // top of all sliders
    float sliderLR = 0;
    float countLeft = 0;
    float countRight = 0;
    float lineDeltaSlider = -10;
    
    
    
    float yPixSlider = 0;
    
   
    
    // create fuel sliders
    
    for (int i = fuelStart; i < fuelEnd+1 ; i++) {
        
        
        float tagNr = i ;
        float itemNr = i;
        if ([[self.arrayName10 objectAtIndex: itemNr  ] rangeOfString:@"fuelTank"].location == NSNotFound){
            continue;
        }
        
        if ([[_arrayName8 objectAtIndex:i] isEqualToString:@"0"]){
            continue;
        }
        
        yPixSlider = yPixSlider + stationYincrement;
        
        
        
        // get Lat Postiion for station
        float itemLatPos = [[_arrayName5 objectAtIndex:i] floatValue];
        // check if item contains LH or RH to position the slider right or left
        if ([[self.arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"LH"].location != NSNotFound){
            //NSLog (@"found LH %.0f", itemNr);
            itemLatPos = -1;
        }
        if ([[self.arrayName14 objectAtIndex: itemNr  ] rangeOfString:@"RH"].location != NSNotFound){
            //NSLog (@"found RH %.0f", itemNr);
            itemLatPos = 1;
        }
        if (itemLatPos < 0.0 || [ [self.arrayName16 objectAtIndex: tagNr  ]  isEqualToString:@"L"]) {
            // left
            sliderLR = 0;
            yPixSlider = countLeft * stationYincrement;
            countLeft = countLeft +1;
        }else{
            if (itemLatPos >= 0.0 || [ [self.arrayName16 objectAtIndex: tagNr  ]  isEqualToString:@"R"]) {
                // right
                sliderLR = 450;
                yPixSlider = countRight * stationYincrement;
                countRight = countRight + 1;
            }
        }
        
        if ([[self.arrayName16 objectAtIndex: itemNr  ] rangeOfString:@"C"].location != NSNotFound){
            //NSLog (@"found RH %.0f", itemNr);
            sliderLR = 220;
            
            sliderYposition = sliderYposition - 60;
        }else{
            
            sliderYposition = fuelSliderTopPosition;
        }
        
        //NSLog(@"sliderLR %f", sliderLR);
        
        if ([[self.arrayName10 objectAtIndex: itemNr  ] rangeOfString:@"fuelTankTotal"].location != NSNotFound){
            
        }else{
            // |||||||||||||| make sliders  in yellow with slider scale
            //NSLog (@"sliderLR  %.0f ", sliderLR );
            CGRect sliderFrame = CGRectMake(sliderLR+gapLeft, sliderYposition + yPixSlider, (sliderWindowWidth -  gapLeft - gapRight +35) , 10.0);
            UISlider *slider = [[UISlider alloc] initWithFrame:sliderFrame];
            [slider addTarget:self action:@selector(WeightSliderAction:) forControlEvents:UIControlEventValueChanged];
            [slider setBackgroundColor:[UIColor clearColor]];
            slider.minimumValue = 0.0;
            // get max weight for slider
            
            
            
            slider.maximumValue = [[self.arrayName9 objectAtIndex: itemNr ] doubleValue];
            
            slider.continuous = YES;
            UIImageView *sliderScale =[[UIImageView alloc] initWithFrame:CGRectMake(sliderLR+gapLeft+5, sliderYposition + yPixSlider - 13, (sliderWindowWidth -  gapLeft - gapRight) -10 +35 , 12.0) ];
            sliderScale.image=[UIImage imageNamed:@"sliderScale_wide20forPA-01.png"]; // sliderScale120-01.png  // sliderScale_wide20forPA-01.png
            sliderScale.alpha = 0.6;
            [_viewFuelSliders addSubview:sliderScale];
            UIImage *sliderImage = [UIImage imageNamed:@"sliderEmpty.png"];
            UIImage *sliderThumb = [UIImage imageNamed:@"triangle3.png"];
            UIImage *sliderImageEmpty = [UIImage imageNamed:@"sliderYellowLine thin.png"];
            [slider setMaximumTrackImage:sliderImage forState:UIControlStateNormal];
            [slider setMinimumTrackImage:sliderImageEmpty forState:UIControlStateNormal];
            [slider setThumbImage:sliderThumb forState:UIControlStateNormal];
            // set slider to weight
            slider.value = [[_arrayName2 objectAtIndex:tagNr] floatValue];
            
            
            
            slider.tag = tagNr;
            //NSLog(@"adding slider tag %d ", slider.tag );
            [_viewFuelSliders addSubview:slider];
            
            // |||||||||||||| make slider weightLabels
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(sliderLR+gapLeft+18, sliderYposition + yPixSlider - 46- lineDeltaSlider, (sliderWindowWidth -  gapLeft - gapRight - 23), 15.0)];
            label.font = [UIFont boldSystemFontOfSize:15.0];
            label.textColor = [UIColor whiteColor];
            label.textAlignment = NSTextAlignmentRight;
            
            //NSLog(@"slider.value %.0f ", slider.value);
            //NSLog(@"factorApplyToNativeFuelWeight %.0f ", factorApplyToNativeFuelWeight);
            
            //NSLog(@"slider.value %.0f ", slider.value);
            
            
            if ([fuelEnterMode isEqualToString:@"mass"]) {
                //NSLog(@"1");
                label.text = [ [NSString alloc] initWithFormat:@"%.0f", slider.value * factorApplyToNativeFuelWeight ];
            }else{
                 //NSLog(@"2");
                label.text = [ [NSString alloc] initWithFormat:@"%.0f", slider.value  / [_inputSpecificFuelMassPerVolume.text floatValue] * factorApplyToNativeFuelVolumeGalLiter ];
            }
            
            //NSLog(@" label.text %@ ",  label.text);
            
            label.tag = tagNr + 1000;
            [_viewFuelSliders addSubview:label];
            
            // |||||||||||||| make station names
            //NSLog(@"lineDeltaSlider %.0f ", lineDeltaSlider);
            label= [[UILabel alloc] initWithFrame:CGRectMake(sliderLR+gapLeft + 10, sliderYposition + yPixSlider - 47 - lineDeltaSlider, (sliderWindowWidth -  gapLeft - gapRight), 17.0)];
            label.font = [UIFont boldSystemFontOfSize:13.0];
            //label.textColor =[UIColor colorWithRed:140.0f/255.0f green:186.0f/255.0f blue:253.0f/255.0f alpha:1.0f]; // light blue
            label.textColor = [UIColor whiteColor];
            label.alpha = 0.9;
            // get name for station
            label.text = [_arrayName1 objectAtIndex:tagNr];
            label.tag = tagNr + 1100;
            [_viewFuelSliders addSubview:label];
            // |||||||||||||| make enter pad buttons
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(sliderLR+sliderWindowWidth - gapRight - 45, sliderYposition + yPixSlider - 49 - lineDeltaSlider, 50, 20); // pos x, pos y, width x, width y
            [btn addTarget:self  action:@selector(buttonActionEnterPadListo:)  forControlEvents:UIControlEventTouchUpInside];
            btn.tag = tagNr + 1300;
            btn.backgroundColor = [UIColor clearColor];
            btn.alpha = 1.0;
            UIImage *buttonKlammern = [UIImage imageNamed:@"Klammern.png"];
            [btn  setBackgroundImage:buttonKlammern forState:UIControlStateNormal];
            [_viewFuelSliders addSubview:btn];
            // |||||||||||||| make unit labels
            label= [[UILabel alloc] initWithFrame:CGRectMake(sliderLR+sliderWindowWidth - gapRight +9, sliderYposition + yPixSlider - 53 - lineDeltaSlider, 35, 27) ];
            label.font = [UIFont systemFontOfSize:15.0];
            label.textColor =[UIColor colorWithRed:140.0f/255.0f green:186.0f/255.0f blue:253.0f/255.0f alpha:1.0f]; // light blue
            //label.textColor = [UIColor whiteColor];
            label.alpha = 1.0;
            label.textAlignment = NSTextAlignmentLeft;
            label.text = fuelUnitsPresented;
            label.tag = tagNr + 1400;
            [_viewFuelSliders addSubview:label];
            //unitsWeight.text = [_arrayName21 objectAtIndex: 5  ];
            //NSLog(@"createFuelSliders");
        }
    }// end for next fuel slider
    
    
    
}













- (void) createSegments {
        
    //NSLog(@"createSegments ");    
    //NSLog(@"lineEnd  %.0f", lineEnd);
    //NSLog(@"lineOptions  %.0f", lineOptions);
    //NSLog(@"[_arrayName25 objectAtIndex:41]  %@", [_arrayName25 objectAtIndex:41]);
    
    for(UIView *subview in [_viewFuelPanelFuelTankSegment subviews]) {
        [subview removeFromSuperview];
    }     
    if (lineEnd ==0 & lineOptions == 0) {        
        if (![[_arrayName25 objectAtIndex:41]isEqualToString:@""]) {            
            //we have an entry in extra4 - for extra fuel tank!
        }else{            
         return;   
        }        
    }
    
  
    
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************    
    
    //                                                                 MAKE Options  make segment controls
    
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    // ****************************************************************************************************************************************************
    
    float lineForOptionsEnd = 0;
    
    if ([[_arrayName1 objectAtIndex: lineOptions ] isEqualToString:@"Options"] & [[_arrayName14 objectAtIndex: lineOptions ] isEqualToString:@"OptionsLine"]) {        
        lineForOptionsEnd = lineOptionsEnd;
    }else{       
        lineForOptionsEnd = lineEnd;
    }
   
        // |||||||||||||| make segements
        
        float segmentYStart = 10;
        float segmentYIncrement = 45;
        float yfact = 0 ;
        float yfactAdd = 0.8;
        _labelExtrasOnHeli.text = @"";
        
        for (int segNr = lineOptions+1; segNr < lineForOptionsEnd ; segNr++) {
            
            //NSLog(@"segNr %d", segNr);
            
            if ([[_arrayName1 objectAtIndex: lineOptions ] isEqualToString:@"Options"] & [[_arrayName14 objectAtIndex: lineOptions ] isEqualToString:@"OptionsLine"]) {
                //NSLog(@"getting options info from backend");                
                NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"_"];
                NSArray *components = [ [_arrayName7 objectAtIndex:segNr] componentsSeparatedByCharactersInSet:charSet1];
                //NSLog(@"components %@", components);    
                
                if (flagOverwriteOptionsDefault == 1) {
                    //NSLog(@"overwriting");                   
                     [_arrayName2 replaceObjectAtIndex:segNr withObject:[components objectAtIndex:1]];
                }                               
                [_arrayName1 replaceObjectAtIndex:segNr withObject:[components objectAtIndex:0]];
                [_arrayName3 replaceObjectAtIndex:segNr withObject:[components objectAtIndex:2]];
                [_arrayName8 replaceObjectAtIndex:segNr withObject:[components objectAtIndex:3]]; // also for scenario switch! 
                if (components.count>4) {                   
                     [_arrayName9 replaceObjectAtIndex:segNr withObject:[components objectAtIndex:4]];
                }
            }
            
           
            
            // segment name
            // check if segment is a drilling
            if ([[_arrayName1 objectAtIndex: segNr ] isEqualToString:@"3Segments"]) {
                // get ON / OFF values for segment:
                NSArray *itemArray = [NSArray arrayWithObjects: [_arrayName8 objectAtIndex: segNr ]    , [_arrayName9 objectAtIndex: segNr ] , [_arrayName1 objectAtIndex: segNr ],  nil];
                UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
                                segmentedControl.frame = CGRectMake(3,  segmentYStart - 3 + yfact * segmentYIncrement, 328, 28);
                
                [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents: UIControlEventValueChanged];
                segmentedControl.tag = segNr;
                segmentedControl.backgroundColor = segmentdarkGrayColor;
                [_viewOptions addSubview:segmentedControl];
                yfact = yfact + yfactAdd;
                
            }else if ([[_arrayName1 objectAtIndex: segNr ] isEqualToString:@"scenarioSwitch"] || [[_arrayName1 objectAtIndex: segNr ] isEqualToString:@"scenarioNewSwitch"]) {                
                NSArray *componentItems  = [[_arrayName8 objectAtIndex: segNr ] componentsSeparatedByString:@"+"];
                int scenarios = componentItems.count;                
               
                NSMutableArray *segmentNamesArray = [[NSMutableArray alloc] init];
                
                for (int i = 0; i < scenarios ; i++) {                    
                    NSString *scenarioString = [componentItems objectAtIndex:i];                    
                    // get segment name
                    NSArray *componentItems  = [scenarioString componentsSeparatedByString:@"&"];
                    NSString *segmentName = [componentItems objectAtIndex:0];
                    [segmentNamesArray addObject:segmentName];                   
                    
                }
                // create segment                
                UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentNamesArray];
                segmentedControl.frame = CGRectMake(3,  segmentYStart - 3 + yfact * segmentYIncrement, 328, 28);
                [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents: UIControlEventValueChanged];
                segmentedControl.tag = segNr;
                segmentedControl.backgroundColor = segmentdarkGrayColor; 
                [_viewOptions addSubview:segmentedControl];
                yfact = yfact + yfactAdd;
                
            }else if ([[_arrayName1 objectAtIndex: segNr ] isEqualToString:@"equipPackSwitch"]) {
                
                
                UILabel *textField = [[UILabel alloc] initWithFrame:CGRectMake(5, segmentYStart + yfact * segmentYIncrement , 320, 20)];
                textField.font = [UIFont boldSystemFontOfSize:15];
                textField.textAlignment = NSTextAlignmentLeft;
                textField.textColor = [UIColor whiteColor];
                [textField  setText: [_arrayName4 objectAtIndex: segNr ]  ];
                [_viewOptions addSubview:textField];
                
                // get ON / OFF values for segment:
                NSArray *itemArray = [NSArray arrayWithObjects: [_arrayName8 objectAtIndex: segNr ], [_arrayName9 objectAtIndex: segNr ],  nil];
                UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
                segmentedControl.frame = CGRectMake(180,  segmentYStart - 3 + yfact * segmentYIncrement, 150, 28);
                [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents: UIControlEventValueChanged];
                segmentedControl.tag = segNr;
                segmentedControl.backgroundColor = segmentdarkGrayColor;
                [_viewOptions addSubview:segmentedControl];
                
                yfact = yfact +yfactAdd;
                
            }else{
                
               
                UILabel *textField = [[UILabel alloc] initWithFrame:CGRectMake(5, segmentYStart + yfact * segmentYIncrement , 320, 20)];
                textField.font = [UIFont boldSystemFontOfSize:15];
                textField.textAlignment = NSTextAlignmentLeft;
                textField.textColor = [UIColor whiteColor];
                [textField  setText: [_arrayName1 objectAtIndex: segNr ]  ];
                [_viewOptions addSubview:textField];
                
                //NSLog(@"make standard option switch %@", [_arrayName1 objectAtIndex: segNr ]);
                
                // get ON / OFF values for segment:
                NSArray *itemArray = [NSArray arrayWithObjects: [_arrayName8 objectAtIndex: segNr ]   , [_arrayName9 objectAtIndex: segNr ],  nil];
                UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
                segmentedControl.frame = CGRectMake(180,  segmentYStart - 3 + yfact * segmentYIncrement, 150, 28);
                [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents: UIControlEventValueChanged];
                segmentedControl.tag = segNr;
                //segmentedControl.backgroundColor = yellowSpecialColor;
                [_viewOptions addSubview:segmentedControl];
                
                yfact = yfact +yfactAdd;                
            }
            
       }// end make segments
    
    flagOverwriteOptionsDefault = 0;
    //NSLog(@"createSegments [_arrayName25 objectAtIndex:41] %@", [_arrayName25 objectAtIndex:41]);
    
    
    if (![[_arrayName25 objectAtIndex:41]isEqualToString:@""]) {
        
        for(UIView *subview in [_viewFuelPanelFuelTankSegment subviews]) {
            [subview removeFromSuperview];
        }        
        [_viewFuelSettings bringSubviewToFront:_viewFuelPanelFuelTankSegment];
        
        //NSLog(@"creating fuel tank segment");        
        NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"@"];
        NSArray *components = [ [_arrayName25 objectAtIndex:41] componentsSeparatedByCharactersInSet:charSet1];        
        charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"_"];
                
        NSArray *tankNames = [ [components objectAtIndex:1] componentsSeparatedByCharactersInSet:charSet1]; 
        NSMutableArray *arrayTankNames   = [[NSMutableArray alloc] init];        
        for(int i=0; i<tankNames.count; i++) {
            if ([[tankNames objectAtIndex:i] isEqualToString:@""]) {                
            }else{
                [arrayTankNames addObject:[tankNames objectAtIndex:i] ]; 
            }            
        }
        NSArray *settingItems = [ [components objectAtIndex:0] componentsSeparatedByCharactersInSet:charSet1];                
        UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:arrayTankNames];
        float xPosSegment = [[settingItems objectAtIndex:2] floatValue];
        float yPosSegment = [[settingItems objectAtIndex:3] floatValue];
        float widthSegment = [[settingItems objectAtIndex:4] floatValue];  
        
        _viewFuelPanelFuelTankSegment.frame = CGRectMake(xPosSegment, yPosSegment,widthSegment, 28);   
        
        segmentedControl.frame = CGRectMake(0, 0,widthSegment, 28);        
        [segmentedControl addTarget:self action:@selector(segmentFuelTanksAction:) forControlEvents: UIControlEventValueChanged];
        segmentedControl.tag = 1;
        segmentedControl.tintColor = [UIColor whiteColor];
        segmentedControl.backgroundColor = segmentdarkGrayColor;
        segmentedControl.selectedSegmentIndex = [[settingItems objectAtIndex:0] floatValue];
        [_viewFuelPanelFuelTankSegment addSubview:segmentedControl];        
      
    }
    
    // penalty labels
   
    UILabel *textField = [[UILabel alloc] initWithFrame:CGRectMake(5, segmentYStart + yfact * segmentYIncrement , 320, 20)];
    textField.font = [UIFont boldSystemFontOfSize:15];
    textField.textAlignment = NSTextAlignmentLeft;
    textField.textColor = [UIColor whiteColor];
    [textField  setText: @""  ];
    textField.tag = 1000;    
    [_viewOptions addSubview:textField];    
    yfact = yfact +0.5;    
    textField = [[UILabel alloc] initWithFrame:CGRectMake(5, segmentYStart + yfact * segmentYIncrement , 320, 20)];
    textField.font = [UIFont boldSystemFontOfSize:15];
    textField.textAlignment = NSTextAlignmentLeft;
    textField.textColor = [UIColor whiteColor];
    [textField  setText: @""  ];
    textField.tag = 1001;    
    [_viewOptions addSubview:textField];    
    yfact = yfact +0.5;    
    
    textField = [[UILabel alloc] initWithFrame:CGRectMake(5, segmentYStart + yfact * segmentYIncrement , 320, 20)];
    textField.font = [UIFont boldSystemFontOfSize:15];
    textField.textAlignment = NSTextAlignmentLeft;
    textField.textColor = [UIColor whiteColor];
    [textField  setText: @""  ];
    textField.tag = 1002;    
    [_viewOptions addSubview:textField];
   
    
    // set segments    
    //NSLog(@"set segments ")   
    
    
    [self setSegments];    
    [self setSliders];
    
    // adjust scroll view    
    numberOfSwitches =  yfact /  yfactAdd;
    
    
}


- (void) setSegments {
    
    
   
    if (![[_arrayName25 objectAtIndex:41]isEqualToString:@""]) {        
        //get segment selection
        UISegmentedControl* segment =(UISegmentedControl*)[_viewFuelPanelFuelTankSegment viewWithTag: 1] ;
        if (segment.selectedSegmentIndex == 0) {           
            
            NSRange range = NSMakeRange(0,1);
            NSString *newText = [[_arrayName25 objectAtIndex:41] stringByReplacingCharactersInRange:range withString:@"0"];            
            [_arrayName25 replaceObjectAtIndex:41 withObject:newText];
            //NSLog (@"0 newText %@", newText);
        }else{
             
             NSRange range = NSMakeRange(0,1);
             NSString *newText = [[_arrayName25 objectAtIndex:41] stringByReplacingCharactersInRange:range withString:@"1"];            
             [_arrayName25 replaceObjectAtIndex:41 withObject:newText];
            //NSLog (@"1 newText %@", newText);
        }
    }
    
    if (lineOptions == 0 & lineEnd == 0) {
        return;
    }
    
    
    float lineForOptionsEnd = 0;
    
    if ([[_arrayName1 objectAtIndex: lineOptions ] isEqualToString:@"Options"] & [[_arrayName14 objectAtIndex: lineOptions ] isEqualToString:@"OptionsLine"]) {        
        lineForOptionsEnd = lineOptionsEnd;
    }else{       
        lineForOptionsEnd = lineEnd;
    }
   
    
    NSString *previousAlternateCGEnvelope = alternateCGenvelope;
    
    //NSLog (@"previousAlternateCGEnvelope %@", previousAlternateCGEnvelope);
    
    for (int segNr = lineOptions+1; segNr < lineForOptionsEnd ; segNr++) {
        
   
        
        UISegmentedControl* segment =(UISegmentedControl*)[_viewOptions viewWithTag: segNr] ;
        
        if ( ![[_arrayName14 objectAtIndex:segNr] isEqualToString:@""]) {
            // we need to use a different CG envelope if the segment is selected
            if (![[_arrayName2 objectAtIndex:segNr] isEqualToString:@"0"]) {
                //alternateCGenvelope = [_arrayName14 objectAtIndex:segNr];
            }else{
                //alternateCGenvelope = @"";
            }
        }
        
        if ([[_arrayName2 objectAtIndex:segNr] isEqualToString:@"1"]) {
             //NSLog (@"1");
            segment.selectedSegmentIndex = 1;
            segment.tintColor = [UIColor whiteColor];
            segment.backgroundColor = segmentdarkGrayColor; 
        }
        
        if ([[_arrayName2 objectAtIndex:segNr] isEqualToString:@"2"]) {
            //NSLog (@"2");
            segment.selectedSegmentIndex = 2;
            segment.tintColor = [UIColor whiteColor];
            segment.backgroundColor = segmentdarkGrayColor; 
        }
        
        
        if ([[_arrayName2 objectAtIndex:segNr] isEqualToString:@"0"]) {
            //NSLog (@"0");
            segment.selectedSegmentIndex = 0;
            segment.tintColor = [UIColor lightGrayColor];
            segment.backgroundColor = segmentdarkGrayColor; 
        }
        
    }
    
    if (![previousAlternateCGEnvelope isEqualToString:alternateCGenvelope]) {        
        [self setCGenvelope];
    }
    
    
    
    
}

- (void)segmentFuelTanksAction :(UISegmentedControl *)segment{  
    
    NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"@"];
    NSArray *components = [ [_arrayName25 objectAtIndex:41] componentsSeparatedByCharactersInSet:charSet1];        
    charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"_"];
    
    //get segment selection
    //UISegmentedControl* segment =(UISegmentedControl*)[_viewFuelPanelFuelTankSegment viewWithTag: 1] ;        
    //NSLog(@"setFuelTankSettings segment.selectedSegmentIndex %ld", (long)segment.selectedSegmentIndex);
    
    NSArray *maxVolumes = [ [components objectAtIndex:2] componentsSeparatedByCharactersInSet:charSet1];
    //NSLog(@"smaxVolumes %@", maxVolumes );
    
    tankCapacityVolume = [[maxVolumes objectAtIndex:segment.selectedSegmentIndex] floatValue];
    [_arrayName21 replaceObjectAtIndex:17 withObject:[maxVolumes objectAtIndex:segment.selectedSegmentIndex]];
    
    _sliderFuelMain1.maximumValue = tankCapacityVolume;
    _sliderFuelLanding.maximumValue = tankCapacityVolume - (tankCapacityVolume * 0.05);        
    //NSLog(@"setFuelTankSettings setting extra tankCapacityVolume %.1f", tankCapacityVolume);
    
    [self setSegments];
    [self setFuelTankSettings];
    [self MainRoutine];
}


- (void)segmentAction :(UISegmentedControl *)segment{
    
  
     
    //NSLog (@"segNr selected %@ ", [ [NSString alloc] initWithFormat:@"%d ", segment.selectedSegmentIndex  ]);
    //NSLog (@"---------- ");
    //NSLog (@"segment.tag %ld ", (long)segment.tag );
    
  
     NSString *dependencyText = [_arrayName25 objectAtIndex:49]; // extra8
    //NSLog(@"dependencyText %@", dependencyText);
     if (dependencyText.length > 0) {
         //NSLog(@"2");
            NSCharacterSet*charSet1 = [NSCharacterSet characterSetWithCharactersInString:@";"];
            NSArray *arrayDependencies = [dependencyText componentsSeparatedByCharactersInSet:charSet1];
         
            for(int i=0; i<arrayDependencies.count; i++) {
                
                NSCharacterSet*charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"_"];
                NSArray *arrayDependencyItem = [[arrayDependencies objectAtIndex:i] componentsSeparatedByCharactersInSet:charSet1];
                NSString *depend1 = [arrayDependencyItem objectAtIndex:0];
                NSString *logicOperator = [arrayDependencyItem objectAtIndex:1]; 
                NSString *depend2 = [arrayDependencyItem objectAtIndex:2];
                
                //NSLog(@"depend1 %@", depend1);
                //NSLog(@"logicOperator %@", logicOperator);
                //NSLog(@"depend2 %@", depend2);
                //NSLog(@"segment.tag %d", segment.tag);
                
                if ([logicOperator isEqualToString:@"OR"]) {  
                    
                    
                    
                    //is segment in dependency? if yes, switch other to off                  
                    if ([depend1 intValue] == segment.tag) {  
                       
                        //NSLog(@"1 segment.selectedSegmentIndex of segment %ld  is = %.1ld", (long)segment.tag , (long)segment.selectedSegmentIndex);                       
                        if (segment.selectedSegmentIndex >= 1) {  
                            
                       
                            
                            if ([[_arrayName1 objectAtIndex: segment.tag ] isEqualToString:@"scenarioSwitch"]) {                            
                                
                                 [_arrayName2 replaceObjectAtIndex:[depend2 intValue] withObject: @"0" ];
                                // get info for scenario
                                NSArray *componentItems  = [[_arrayName8 objectAtIndex: [depend2 intValue]  ] componentsSeparatedByString:@"+"];
                                float scenarios = 0;
                                NSString *scenarioString = [componentItems objectAtIndex:scenarios];                                
                                NSArray *scenarioItems  = [scenarioString componentsSeparatedByString:@"&"];
                                for (int i = 1; i < scenarioItems.count ; i++) {
                                    NSArray *componentItems  = [[scenarioItems objectAtIndex: i  ] componentsSeparatedByString:@"="];
                                    //NSLog (@"scenarioString 0 %@", [componentItems objectAtIndex:0]);
                                    //NSLog (@"scenarioString 1 %@", [componentItems objectAtIndex:1]);
                                    [_arrayName8 replaceObjectAtIndex:[[componentItems objectAtIndex:0] integerValue] withObject: [componentItems objectAtIndex:1]];
                                }
                                [_arrayName2 replaceObjectAtIndex:segment.tag withObject: [[NSString alloc] initWithFormat:@"%d", segment.selectedSegmentIndex] ];
                                [self createListoItemsSlidersAndInterior];
                                
                            }else if ([[_arrayName1 objectAtIndex: segment.tag ] isEqualToString:@"scenarioNewSwitch"]){                                
                                [_arrayName2 replaceObjectAtIndex:[depend2 intValue] withObject: @"0" ];
                                NSArray *componentItems  = [[_arrayName8 objectAtIndex: [depend2 intValue]  ] componentsSeparatedByString:@"+"];
                                float scenarios = 0;
                                NSString *scenarioString = [componentItems objectAtIndex:scenarios];
                                       NSArray *scenarioItems  = [scenarioString componentsSeparatedByString:@"&"];
                                       for (int i = 1; i < scenarioItems.count ; i++) {
                                           NSArray *componentItems  = [[scenarioItems objectAtIndex: i  ] componentsSeparatedByString:@"="];
                                           int itemID = 0;
                                           for (int switchID = 3; switchID < lineZFW ; switchID++) {                                               
                                               if ([[componentItems objectAtIndex:0] isEqualToString:[_arrayName1 objectAtIndex:switchID]]) {
                                                   itemID = switchID;
                                                   break;
                                               }                                               
                                           }
                                           [_arrayName8 replaceObjectAtIndex:itemID withObject: [componentItems objectAtIndex:1]];
                                       }                                       
                                       [_arrayName2 replaceObjectAtIndex:segment.tag withObject: [[NSString alloc] initWithFormat:@"%d", segment.selectedSegmentIndex] ];                                       
                                       [self createListoItemsSlidersAndInterior];                                
                            } else{                          
                                [_arrayName2 replaceObjectAtIndex:[depend2 intValue] withObject: @"0" ];
                                //NSLog (@"switching Standard Segment");
                                // check if switch is connected to an item:
                                int flagItemIsConnected = 0;
                                for (int itemIndex = listStart; itemIndex < listEnd+1 ; itemIndex++) {            
                                   if ( [[_arrayName1 objectAtIndex: itemIndex ] isEqualToString: [_arrayName3 objectAtIndex: [depend2 intValue] ]] ) {
                                   //NSLog (@"Switch is connected to item %@ ", [ [NSString alloc] initWithFormat:@"%d ", itemIndex ]);
                                   flagItemIsConnected = 1;
                                   [_arrayName2 replaceObjectAtIndex:itemIndex withObject: @"0"];
                                   //NSLog (@"0 segment.tag %@ ", [ [NSString alloc] initWithFormat:@"%d ", segment.tag]);                                                    
                                   [_arrayName8 replaceObjectAtIndex:itemIndex withObject: @"0" ];
                                   [self createListoItemsSlidersAndInterior];                
                                   break;
                                   }            
                                }
                                
                            }  
                          
                        }
                    }
                    
                    if ([depend2 intValue] == segment.tag) {                   
                        //NSLog(@"2 segment.selectedSegmentIndex of segment %ld  is = %.1ld", (long)segment.tag , (long)segment.selectedSegmentIndex);                           
                        if (segment.selectedSegmentIndex == 1) {                        
                            if ([[_arrayName1 objectAtIndex: segment.tag ] isEqualToString:@"scenarioSwitch"]) {                           
                                //NSLog (@"1 switching scenario");                               
                                [_arrayName2 replaceObjectAtIndex:[depend1 intValue] withObject: @"0" ];                                                               
                                // get info for scenario                                                               
                                NSArray *componentItems  = [[_arrayName8 objectAtIndex: [depend1 intValue]  ] componentsSeparatedByString:@"+"];  
                                float scenarios = 0;                                                               
                                NSString *scenarioString = [componentItems objectAtIndex:scenarios]; 
                                NSArray *scenarioItems  = [scenarioString componentsSeparatedByString:@"&"];
                               for (int i = 1; i < scenarioItems.count ; i++) {
                                  NSArray *componentItems  = [[scenarioItems objectAtIndex: i  ] componentsSeparatedByString:@"="];
                                  //NSLog (@"scenarioString 0 %@", [componentItems objectAtIndex:0]);
                                  //NSLog (@"scenarioString 1 %@", [componentItems objectAtIndex:1]);
                                   [_arrayName8 replaceObjectAtIndex:[[componentItems objectAtIndex:0] integerValue] withObject: [componentItems objectAtIndex:1]];
                                  }
                                                               
                               [_arrayName2 replaceObjectAtIndex:segment.tag withObject: [[NSString alloc] initWithFormat:@"%d", segment.selectedSegmentIndex] ];                                                               
                                [self createListoItemsSlidersAndInterior];
                                
                                
                            }else if ([[_arrayName1 objectAtIndex: segment.tag ] isEqualToString:@"scenarioNewSwitch"]){                                
                                [_arrayName2 replaceObjectAtIndex:[depend1 intValue] withObject: @"0" ];
                                NSArray *componentItems  = [[_arrayName8 objectAtIndex: [depend1 intValue]  ] componentsSeparatedByString:@"+"];
                                float scenarios = 0;
                                NSString *scenarioString = [componentItems objectAtIndex:scenarios];
                                       NSArray *scenarioItems  = [scenarioString componentsSeparatedByString:@"&"];
                                       for (int i = 1; i < scenarioItems.count ; i++) {
                                           NSArray *componentItems  = [[scenarioItems objectAtIndex: i  ] componentsSeparatedByString:@"="];
                                           int itemID = 0;
                                           for (int switchID = 3; switchID < lineZFW ; switchID++) {                                               
                                               if ([[componentItems objectAtIndex:0] isEqualToString:[_arrayName1 objectAtIndex:switchID]]) {
                                                   itemID = switchID;
                                                   break;
                                               }                                               
                                           }
                                           [_arrayName8 replaceObjectAtIndex:itemID withObject: [componentItems objectAtIndex:1]];
                                       }                                       
                                       [_arrayName2 replaceObjectAtIndex:segment.tag withObject: [[NSString alloc] initWithFormat:@"%d", segment.selectedSegmentIndex] ];                                       
                                       [self createListoItemsSlidersAndInterior];                                
                            }else{                            
                                [_arrayName2 replaceObjectAtIndex:[depend1 intValue] withObject: @"0" ];
                                //NSLog (@"2 switching Standard Segment");
                                // check if switch is connected to an item:
                                int flagItemIsConnected = 0;
                                for (int itemIndex = listStart; itemIndex < listEnd+1 ; itemIndex++) {            
                                   if ( [[_arrayName1 objectAtIndex: itemIndex ] isEqualToString: [_arrayName3 objectAtIndex: [depend1 intValue] ]] ) {
                                   //NSLog (@"Switch is connected to item %@ ", [ [NSString alloc] initWithFormat:@"%d ", itemIndex ]);
                                   flagItemIsConnected = 1;
                                   [_arrayName2 replaceObjectAtIndex:itemIndex withObject: @"0"];
                                   //NSLog (@"0 segment.tag %@ ", [ [NSString alloc] initWithFormat:@"%d ", segment.tag]);                                                    
                                   [_arrayName8 replaceObjectAtIndex:itemIndex withObject: @"0" ];
                                   [self createListoItemsSlidersAndInterior];                
                                   break;
                                   }            
                                }
                                
                            }  
                          
                        }
                    }
                    
                }
                

                
            }
         
     }//end dependency text
   
     
    if ([[_arrayName3 objectAtIndex: segment.tag  ] rangeOfString:@"&"].location != NSNotFound   ) {
        // switch multiple items on or off
        // collect items
        NSArray *componentItems  = [[_arrayName3 objectAtIndex: segment.tag  ] componentsSeparatedByString:@"&"];
        //NSLog (@"componentItems %@", componentItems);
        for(int i=0; i<componentItems.count; i++) {
            NSString *compItem = [componentItems objectAtIndex:i];
            
            for (int itemIndex = listStart; itemIndex < listEnd+1 ; itemIndex++) {
                if ( [[_arrayName1 objectAtIndex: itemIndex ] isEqualToString: compItem  ] ) {
                    //NSLog (@"Switch is connected to item %@ ", [ [NSString alloc] initWithFormat:@"%d ", itemIndex ]);
                    if (segment.selectedSegmentIndex == 1) {
                        [_arrayName2 replaceObjectAtIndex:segment.tag withObject: @"1"];
                        //NSLog (@"1 segment.tag %@ ", [ [NSString alloc] initWithFormat:@"%d ", segment.tag]);
                    }else{
                        [_arrayName2 replaceObjectAtIndex:segment.tag withObject: @"0"];
                        //NSLog (@"0 segment.tag %@ ", [ [NSString alloc] initWithFormat:@"%d ", segment.tag]);
                    }
                    [_arrayName8 replaceObjectAtIndex:itemIndex withObject: [_arrayName2 objectAtIndex: segment.tag ]  ];
                    
                    break;
                }
            }// end for itemIndex
        }// end for comp items
        
        
       
        [self createListoItemsSlidersAndInterior];
        [self MainRoutine];
        
        
        
    }else  if ([[_arrayName1 objectAtIndex: segment.tag ] isEqualToString:@"3Segments"]) {
        //NSLog(@"a3");
        //NSLog (@"3Segments !");
        // look for item that is selected, switch it on, then switch the other off.
        // if it is the 0 item, switch both off
        
        
        if (segment.selectedSegmentIndex == 1) {
            
            //NSLog (@"= 1");
            
            // get line for selected item 1
            for (int itemIndex = listStart; itemIndex < listEnd+1 ; itemIndex++) {
                if ( [[_arrayName1 objectAtIndex: itemIndex ] isEqualToString: [_arrayName9 objectAtIndex: segment.tag ]] ) {
                    
                    //NSLog (@"line 1 is %d", itemIndex);
                    
                    //switch on item 1
                    [_arrayName8 replaceObjectAtIndex:itemIndex withObject: @"1" ];
                    break;
                }
            }
            // get line for selected item 2
            for (int itemIndex = listStart; itemIndex < listEnd+1 ; itemIndex++) {
                if ( [[_arrayName1 objectAtIndex: itemIndex ] isEqualToString: [_arrayName10 objectAtIndex: segment.tag ]] ) {
                    //NSLog (@"line 1 is %d", itemIndex);
                    
                    //switch off item 2
                    [_arrayName8 replaceObjectAtIndex:itemIndex withObject: @"0" ];
                    break;
                }
            }
            
            
        }
        
        
        if (segment.selectedSegmentIndex == 2) {
            
            //NSLog (@"= 2");
            
            // get line for selected item 2
            for (int itemIndex = listStart; itemIndex < listEnd+1 ; itemIndex++) {
                if ( [[_arrayName1 objectAtIndex: itemIndex ] isEqualToString: [_arrayName10 objectAtIndex: segment.tag ]] ) {
                    //NSLog (@"line 1 is %d", itemIndex);
                    
                    //switch on item 2
                    [_arrayName8 replaceObjectAtIndex:itemIndex withObject: @"1" ];
                    break;
                }
            }
            // get line for selected item 1
            for (int itemIndex = listStart; itemIndex < listEnd+1 ; itemIndex++) {
                if ( [[_arrayName1 objectAtIndex: itemIndex ] isEqualToString: [_arrayName9 objectAtIndex: segment.tag ]] ) {
                    //NSLog (@"line 1 is %d", itemIndex);
                    
                    //switch off item 2
                    [_arrayName8 replaceObjectAtIndex:itemIndex withObject: @"0" ];
                    break;
                }
            }
        }
        
        
        
        if (segment.selectedSegmentIndex == 0) {
            
            //NSLog (@"= 0");
            
            
            // get line for selected item 1
            for (int itemIndex = listStart; itemIndex < listEnd+1 ; itemIndex++) {
                if ( [[_arrayName1 objectAtIndex: itemIndex ] isEqualToString: [_arrayName9 objectAtIndex: segment.tag ]] ) {
                    //NSLog (@"line 1 is %d", itemIndex);
                    
                    //switch off item 1
                    [_arrayName8 replaceObjectAtIndex:itemIndex withObject: @"0" ];
                    break;
                }
            }
            // get line for selected item 2
            for (int itemIndex = listStart; itemIndex < listEnd+1 ; itemIndex++) {
                if ( [[_arrayName1 objectAtIndex: itemIndex ] isEqualToString: [_arrayName10 objectAtIndex: segment.tag ]] ) {
                    //NSLog (@"line 2 is %d", itemIndex);
                    
                    //switch off item 2
                    [_arrayName8 replaceObjectAtIndex:itemIndex withObject: @"0" ];
                    break;
                }
            }
        }
        
        [_arrayName2 replaceObjectAtIndex:segment.tag withObject: [[NSString alloc] initWithFormat:@"%d", segment.selectedSegmentIndex] ];
        
        //NSLog (@"replacing with  %@",  [[NSString alloc] initWithFormat:@"%d", segment.selectedSegmentIndex]);
        
        
       
        [self createListoItemsSlidersAndInterior];
        [self MainRoutine];
        
    }else  if ([[_arrayName1 objectAtIndex: segment.tag ] isEqualToString:@"scenarioSwitch"]) {
        
        //NSLog (@"scenarioSwitch  %@", [_arrayName8 objectAtIndex: segment.tag  ]);
        
        // get info for scenario
        NSArray *componentItems  = [[_arrayName8 objectAtIndex: segment.tag  ] componentsSeparatedByString:@"+"];
        float scenarios = segment.selectedSegmentIndex;
        NSString *scenarioString = [componentItems objectAtIndex:scenarios];
        //NSLog (@"scenarioString %@", scenarioString);
        
        
        NSArray *scenarioItems  = [scenarioString componentsSeparatedByString:@"&"];
        for (int i = 1; i < scenarioItems.count ; i++) {
            NSArray *componentItems  = [[scenarioItems objectAtIndex: i  ] componentsSeparatedByString:@"="];
            //NSLog (@"scenarioString 0 %@", [componentItems objectAtIndex:0]);
            //NSLog (@"scenarioString 1 %@", [componentItems objectAtIndex:1]);
            [_arrayName8 replaceObjectAtIndex:[[componentItems objectAtIndex:0] integerValue] withObject: [componentItems objectAtIndex:1]];
        }
        
        [_arrayName2 replaceObjectAtIndex:segment.tag withObject: [[NSString alloc] initWithFormat:@"%d", segment.selectedSegmentIndex] ];
        
        [self createListoItemsSlidersAndInterior];
        [self MainRoutine];
        
    }else  if ([[_arrayName1 objectAtIndex: segment.tag ] isEqualToString:@"scenarioNewSwitch"]) {
        
        //NSLog (@"scenarioNewSwitch !!  %@", [_arrayName8 objectAtIndex: segment.tag  ]);
        
        // get info for scenario
        NSArray *componentItems  = [[_arrayName8 objectAtIndex: segment.tag  ] componentsSeparatedByString:@"+"];
        float scenarios = segment.selectedSegmentIndex;
        NSString *scenarioString = [componentItems objectAtIndex:scenarios];
        //NSLog (@"scenarioNewString %@", scenarioString);
        
        
        NSArray *scenarioItems  = [scenarioString componentsSeparatedByString:@"&"];
        for (int i = 1; i < scenarioItems.count ; i++) {
            NSArray *componentItems  = [[scenarioItems objectAtIndex: i  ] componentsSeparatedByString:@"="];
            //NSLog (@"scenarioString %@ %@", [componentItems objectAtIndex:0], [componentItems objectAtIndex:1]);
            //NSLog (@"scenarioString 1 %@", [componentItems objectAtIndex:1]);
            
            int itemID = 0;
            for (int switchID = 3; switchID < lineZFW ; switchID++) {
                
                if ([[componentItems objectAtIndex:0] isEqualToString:[_arrayName1 objectAtIndex:switchID]]) {
                    itemID = switchID;
                    //NSLog (@"found item ID %d", itemID);
                    break;
                }
                
            }
            
            
            
            [_arrayName8 replaceObjectAtIndex:itemID withObject: [componentItems objectAtIndex:1]];
        }
        
        [_arrayName2 replaceObjectAtIndex:segment.tag withObject: [[NSString alloc] initWithFormat:@"%d", segment.selectedSegmentIndex] ];
        
        [self createListoItemsSlidersAndInterior];
        [self MainRoutine];
        
    }else  if ([[self.arrayName1 objectAtIndex: segment.tag ] isEqualToString:@"equipPackSwitch"]) {
        
        //NSLog (@"equipPackSwitch");
        // check if switch is connected to an item:
        int flagItemIsConnected = 0;
        for (int itemIndex = listStart; itemIndex < listEnd+1 ; itemIndex++) {
            if ( [[self.arrayName1 objectAtIndex: itemIndex ] isEqualToString: [self.arrayName3 objectAtIndex: segment.tag ]] ) {
                //NSLog (@"Switch is connected to item %@ ", [ [NSString alloc] initWithFormat:@"%d ", itemIndex ]);
                flagItemIsConnected = 1;
                if (segment.selectedSegmentIndex == 1) {
                    [self.arrayName2 replaceObjectAtIndex:segment.tag withObject: @"1"];
                    //NSLog (@"1 segment.tag %@ ", [ [NSString alloc] initWithFormat:@"%d ", segment.tag]);
                }else{
                    [self.arrayName2 replaceObjectAtIndex:segment.tag withObject: @"0"];
                    //NSLog (@"0 segment.tag %@ ", [ [NSString alloc] initWithFormat:@"%d ", segment.tag]);
                }
                
                
                [self setEquipPack: [_arrayName5 objectAtIndex: segment.tag ]  status:segment.selectedSegmentIndex ]; // transferEquipPack name
                
                
                [self.arrayName8 replaceObjectAtIndex:itemIndex withObject: [self.arrayName2 objectAtIndex: segment.tag ]  ];
                [self createListoItemsSlidersAndInterior];
                break;
            }
        }
        
        
        if (flagItemIsConnected == 0) {
            //NSLog (@"not connected ******************************************");
            // switch the segment that is not connected
            if (segment.selectedSegmentIndex == 1) {
                [self.arrayName2 replaceObjectAtIndex:segment.tag withObject: @"1"];
                //NSLog (@"1 segment.tag %@ ", [ [NSString alloc] initWithFormat:@"%d ", segment.tag]);
            }else{
                [self.arrayName2 replaceObjectAtIndex:segment.tag withObject: @"0"];
                //NSLog (@"0 segment.tag %@ ", [ [NSString alloc] initWithFormat:@"%d ", segment.tag]);
            }
            [self createListoItemsSlidersAndInterior];
            
            [self setEquipPack: [_arrayName5 objectAtIndex: segment.tag ]  status:segment.selectedSegmentIndex ]; // transferEquipPack name
            
        }
        
        //NSLog (@"flagItemIsConnected %d", flagItemIsConnected);
        
        [self MainRoutine];
        
        
    }else{
        
   
        // check if switch is connected to an item:
        int flagItemIsConnected = 0;
        for (int itemIndex = listStart; itemIndex < listEnd+1 ; itemIndex++) { 
            if ( [[_arrayName1 objectAtIndex: itemIndex ] isEqualToString: [_arrayName3 objectAtIndex: segment.tag ]] ) {             
                flagItemIsConnected = 1;
                if (segment.selectedSegmentIndex == 1) {
                    [_arrayName2 replaceObjectAtIndex:segment.tag withObject: @"1"];
                }else{
                    [_arrayName2 replaceObjectAtIndex:segment.tag withObject: @"0"];
                    segment.selectedSegmentIndex = 0;
                }                
                [_arrayName8 replaceObjectAtIndex:itemIndex withObject: [_arrayName2 objectAtIndex: segment.tag ]  ];
                
                [self createListoItemsSlidersAndInterior];                
                break;
            }            
        }
        
        
        if (flagItemIsConnected == 0) {
            
            //NSLog (@"not connected ******************************************");
            // switch the segment that is not connected
            
            if (segment.selectedSegmentIndex == 1) {
                
                [_arrayName2 replaceObjectAtIndex:segment.tag withObject: @"1"];
                //NSLog (@"1 segment.tag %@ ", [ [NSString alloc] initWithFormat:@"%d ", segment.tag]);
                
            }else{
                
                [_arrayName2 replaceObjectAtIndex:segment.tag withObject: @"0"];
                //NSLog (@"0 segment.tag %@ ", [ [NSString alloc] initWithFormat:@"%d ", segment.tag]);
            }
            
            
            [self createListoItemsSlidersAndInterior];
            
            
        }
        
      
        [self MainRoutine];
        
        
        
        
        
        
    }
    
    
    
    
    
}



- (void)saveArrayListo {
    
    
    
    // save list
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    NSString *configSetup  = [NSString stringWithFormat:@"%@_%@", actypeForConfig, defaultConfigName ];

    //NSLog(@"saveArrayListo configSetup  %@", configSetup);
    
    [defaults  setObject:_arrayName1       forKey:[configSetup stringByAppendingString:@"arrayName1"]];
    [defaults  setObject:_arrayName2       forKey:[configSetup stringByAppendingString:@"arrayName2"]];
    [defaults  setObject:_arrayName3       forKey:[configSetup stringByAppendingString:@"arrayName3"]];
    [defaults  setObject:_arrayName4       forKey:[configSetup stringByAppendingString:@"arrayName4"]];
    [defaults  setObject:_arrayName5       forKey:[configSetup stringByAppendingString:@"arrayName5"]];
    [defaults  setObject:_arrayName6       forKey:[configSetup stringByAppendingString:@"arrayName6"]];
    [defaults  setObject:_arrayName7       forKey:[configSetup stringByAppendingString:@"arrayName7"]];
    [defaults  setObject:_arrayName8       forKey:[configSetup stringByAppendingString:@"arrayName8"]];
    [defaults  setObject:_arrayName9       forKey:[configSetup stringByAppendingString:@"arrayName9"]];
    [defaults  setObject:_arrayName10      forKey:[configSetup stringByAppendingString:@"arrayName10"]];
    [defaults  setObject:_arrayName11      forKey:[configSetup stringByAppendingString:@"arrayName11"]];
    [defaults  setObject:_arrayName12      forKey:[configSetup stringByAppendingString:@"arrayName12"]];
    [defaults  setObject:_arrayName13      forKey:[configSetup stringByAppendingString:@"arrayName13"]];
    [defaults  setObject:_arrayName14      forKey:[configSetup stringByAppendingString:@"arrayName14"]];
    [defaults  setObject:_arrayName15      forKey:[configSetup stringByAppendingString:@"arrayName15"]];
    [defaults  setObject:_arrayName16      forKey:[configSetup stringByAppendingString:@"arrayName16"]];
    [defaults  setObject:_arrayName17      forKey:[configSetup stringByAppendingString:@"arrayName17"]];
    [defaults  setObject:_arrayName18      forKey:[configSetup stringByAppendingString:@"arrayName18"]];
    [defaults  setObject:_arrayName19      forKey:[configSetup stringByAppendingString:@"arrayName19"]];
    [defaults  setObject:_arrayName20      forKey:[configSetup stringByAppendingString:@"arrayName20"]];
    [defaults  setObject:_arrayName21      forKey:[configSetup stringByAppendingString:@"arrayName21"]];
    [defaults  setObject:_arrayName22      forKey:[configSetup stringByAppendingString:@"arrayName22"]];
    [defaults  setObject:_arrayName23      forKey:[configSetup stringByAppendingString:@"arrayName23"]];
    [defaults  setObject:_arrayName24      forKey:[configSetup stringByAppendingString:@"arrayName24"]];
    [defaults  setObject:_arrayName25      forKey:[configSetup stringByAppendingString:@"arrayName25"]];

    
    //NSLog(@"saving  arrayName1  %@", _arrayName1 );
    //NSLog(@"saving  arrayName22  %@", _arrayName22 );
    
    return;
    
    
    
    
    
}


- (void)checkIfConfigAvailableForThisAC {
  
    
    NSMutableArray *arrayConfigButtonsRegistration   = [[NSMutableArray alloc] init];
    [arrayConfigButtonsRegistration setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"arrayConfigButtonsRegistration%@", AC_Type] ] mutableCopy]];
    
    if (![arrayConfigButtonsRegistration containsObject:vFlightRegistration.text]) {
        //NSLog (@"importing ......");
        [self importConfigsFromFleetControl];
    }else{
       
    }
}



- (IBAction)actionOpenEditCustomStation:(id)sender {
    
    //NSLog(@"actionOpenEditCustomStation");
    
    if (modeEquipListOrInterior == 2) {
        modeEquipListOrInterior = 3;          
        configMode = 0;   
        [_buttonOpenCustomStations setTitle:@"Back To Stations" forState:UIControlStateNormal];
        
    }else{
         modeEquipListOrInterior = 2; 
         configMode = 0;
        [_buttonOpenCustomStations setTitle:@"Edit Custom Stations" forState:UIControlStateNormal];
    }
    
    
    [self setConfigWindow];
    [self setCGenvelope];    
    [self createCustomStationList];  
    [self MainRoutine];
   
}


- (void) initializeCustomStation {
    
    customStationDictionary = [[NSMutableDictionary alloc] init];
    customStationDictionary[@"stationName"] = @"Station X";
    customStationDictionary[@"ID"] =  @"X";        
    customStationDictionary[@"symbol"] = @"Seat";
    customStationDictionary[@"rotation"] =  @"0";
    customStationDictionary[@"weight"] =  @"50";        
    customStationDictionary[@"armLong"] = [_arrayName3 objectAtIndex: linePilot]; // pilot arm
    customStationDictionary[@"armLat"] =   @"0";
    customStationDictionary[@"status"] =   @"new";
    float randomID = arc4random()% 9999999;
    customStationDictionary[@"randomID"] = [NSString stringWithFormat:@"%.0f", randomID ];
    int insertIndex = lineZFW ; 
    if (lineEquipment > 0 ) {
        insertIndex = lineEquipment;
    }
    if (lineSeats > 0 ) {
        if (lineSeats > insertIndex) {
            insertIndex = lineSeats;
        }
    }
    if (lineEquipment > 0 ) {
        insertIndex = lineEquipment;
        //NSLog(@" insertIndex = lineEquipment");
    }
    
    if (lineSeats > 0 ) {
        if (lineSeats < insertIndex) {
            insertIndex = lineEquipment;
            //NSLog(@" insertIndex = lineEquipment");
        }
    }
    
    
    
    //NSLog (@"insertIndex %d", insertIndex);         
    customStationDictionary[@"insertIndex"] = [NSString stringWithFormat:@"%d", insertIndex ];
    [arrayCustomStations addObject:customStationDictionary];
}

- (void) createCustomStationList {
    
    for(UIView *subview in [_viewCustomStationList subviews]) {
        [subview removeFromSuperview];
    }  
    
    
    
    _labelSpecialEquipConfigName.text = arrayConfigurations[configuration]; 
    
    float yPos = 0;
    int stationID = 1;
    float yStep = 190; 
    int flagAllowCreateAnotherFlight = 1;
    
    arrayCustomStations = [[NSMutableArray alloc] init]; 
    NSString *internalFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];    
    arrayCustomStations = [[[NSUserDefaults standardUserDefaults] objectForKey:[[NSString alloc] initWithFormat:@"%@%@", internalFlightID, @"arrayCustomStations" ]] mutableCopy];
  
    //NSLog(@"internalFlightID %@", internalFlightID);
    if (arrayCustomStations.count < 1) {
        
        arrayCustomStations = [[NSMutableArray alloc] init];         
        //NSLog(@"creating");
        [self initializeCustomStation];
        flagAllowCreateAnotherFlight = 0;
        
    }
       
    [_scrollViewConfiguratorItems setContentSize:CGSizeMake(_viewCustomStationList.frame.size.width, arrayCustomStations.count * 310 + 400)];
    
    for (int i = 0; i < arrayCustomStations.count  ; i++) {
        
        customStationDictionary = [[NSMutableDictionary alloc] init]; 
        customStationDictionary = [arrayCustomStations objectAtIndex:i];
       //NSLog(@"customStationDictionary %@", customStationDictionary);       
        stationID = i;        
        if ([customStationDictionary[@"status"] isEqualToString:@"new"]) {
            flagAllowCreateAnotherFlight = 0;
        }
        UIImageView *box =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0 + yPos, 559, 177 ) ];
        box.backgroundColor = verydarkGrayColor;
        [_viewCustomStationList addSubview: box];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(19, 17 + yPos, 166, 21)];
        label.font = [UIFont systemFontOfSize:16.0];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = @"Station Name";
        [_viewCustomStationList addSubview:label];        
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(19, 46+yPos , 149, 30)];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:16];
        textField.textAlignment = NSTextAlignmentLeft;
        textField.textColor = [UIColor blackColor];
        textField.tag = stationID + 100;
        [textField  setText:  customStationDictionary[@"stationName"]]; 
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        [textField setKeyboardType:UIKeyboardTypeDefault];
        [textField addTarget:self action:@selector(moveScrollViewCustomStation:)  forControlEvents:UIControlEventEditingDidBegin];
        [textField addTarget:self action:@selector(closeKeyboardCustomStation:)  forControlEvents:UIControlEventEditingDidEndOnExit];
        [_viewCustomStationList addSubview:textField];
        
        //--------------------------------------------------------
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(193, 17 + yPos, 38, 21)];
        label.font = [UIFont systemFontOfSize:16.0];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = @"ID";
        [_viewCustomStationList addSubview:label];
        
        textField = [[UITextField alloc] initWithFrame:CGRectMake(193, 46+yPos , 66, 30)];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:16];
        textField.textAlignment = NSTextAlignmentLeft;
        textField.textColor = [UIColor blackColor];
        textField.tag = stationID + 200;
        [textField  setText: customStationDictionary[@"ID"]  ];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        [textField setKeyboardType:UIKeyboardTypeDefault];
        [textField addTarget:self action:@selector(moveScrollViewCustomStation:)  forControlEvents:UIControlEventEditingDidBegin];
         [textField addTarget:self action:@selector(closeKeyboardCustomStation:)  forControlEvents:UIControlEventEditingDidEndOnExit];
        [_viewCustomStationList addSubview:textField];
        
        //--------------------------------------------------------
        
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(284, 17 + yPos, 123, 21)];
        label.font = [UIFont systemFontOfSize:16.0];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = @"Symbol";
        [_viewCustomStationList addSubview:label];
        
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(284, 50 + yPos, 123, 21)];
        label.font = [UIFont systemFontOfSize:16.0];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentLeft;
        label.tag = stationID + 300;
        label.text = customStationDictionary[@"symbol"];
        [_viewCustomStationList addSubview:label];
        
        UIImageView *symbolImage = [[UIImageView alloc] initWithFrame:CGRectMake(360,19 + yPos, 55, 63)];
        
        
        float symSizeX = 0, symSizeY = 0;
        if ([label.text isEqualToString:@"Seat"]) {
            symbolImage.image=[UIImage imageNamed:@"seatYellow.png"];
            symSizeX = 45; symSizeY = 55;
            symbolImage.frame = CGRectMake(360, 19 + yPos, symSizeX, symSizeY);
            
        }
        if ([label.text isEqualToString:@"Box 1"]) {
            symbolImage.image=[UIImage imageNamed:@"baggageBoxYellow.png"];
            symSizeX = 45; symSizeY = 80;
            symbolImage.frame = CGRectMake(360, 19 + yPos, symSizeX, symSizeY);
        }
        if ([label.text isEqualToString:@"Box 2"]) {
            symbolImage.image=[UIImage imageNamed:@"baggageBoxYellow.png"];
            symSizeX = 80; symSizeY = 45;
            symbolImage.frame = CGRectMake(360, 19 + yPos, symSizeX, symSizeY);
        }
        
        if ([label.text isEqualToString:@"Hook"]) {
            symbolImage.image=[UIImage imageNamed:@"hookYellow.png"];
            symSizeX = 35; symSizeY = 55;
            symbolImage.frame = CGRectMake(360, 19 + yPos, symSizeX, symSizeY);
        }
        if ([label.text isEqualToString:@"Basket"]) {
            symbolImage.image=[UIImage imageNamed:@"heliBasketYellow.png"];
            symSizeX = 45; symSizeY = 90;
            symbolImage.frame = CGRectMake(360, 19 + yPos, symSizeX, symSizeY);
        }
        
        
        
        [_viewCustomStationList addSubview:symbolImage];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(277, 17 + yPos , 157, 67);
        [btn addTarget:self action:@selector(actionSetSymbol:)  forControlEvents:UIControlEventTouchUpInside];
        btn.tag = stationID + 350;   
        [btn setTitle:@"" forState:UIControlStateNormal];
        [_viewCustomStationList addSubview:btn];
        
        //--------------------------------------------------------
        
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(453, 17 +yPos, 85, 21)];
        label.font = [UIFont systemFontOfSize:16.0];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = @"Rotation º";
        [_viewCustomStationList addSubview:label];
        
        textField = [[UITextField alloc] initWithFrame:CGRectMake(453, 46  + yPos , 78, 30)];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:16];
        textField.textAlignment = NSTextAlignmentLeft;
        textField.textColor = [UIColor blackColor];
        textField.tag = stationID + 400;
        [textField  setText: customStationDictionary[@"rotation"]  ];  
        [textField setKeyboardType:UIKeyboardTypeNumberPad];
        [textField addTarget:self action:@selector(moveScrollViewCustomStation:)  forControlEvents:UIControlEventEditingDidBegin];
         [textField addTarget:self action:@selector(closeKeyboardCustomStation:)  forControlEvents:UIControlEventEditingDidEndOnExit];
        [_viewCustomStationList addSubview:textField];
        
        //--------------------------------------------------------
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(19, 92 +yPos, 74, 21)];
        label.font = [UIFont systemFontOfSize:16.0];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = @"Weight";
        [_viewCustomStationList addSubview:label];
        
        
        textField = [[UITextField alloc] initWithFrame:CGRectMake(19, 121  + yPos , 80, 30)];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:16];
        textField.textAlignment = NSTextAlignmentLeft;
        textField.textColor = [UIColor blackColor];
        textField.tag = stationID + 450;
        [textField  setText: customStationDictionary[@"weight"]   ];
        [textField setKeyboardType:UIKeyboardTypeNumberPad];
        [textField addTarget:self action:@selector(moveScrollViewCustomStation:)  forControlEvents:UIControlEventEditingDidBegin];
         [textField addTarget:self action:@selector(closeKeyboardCustomStation:)  forControlEvents:UIControlEventEditingDidEndOnExit];
        [_viewCustomStationList addSubview:textField];
        
        //--------------------------------------------------------
        
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(115, 92 +yPos, 93, 21)];
        label.font = [UIFont systemFontOfSize:16.0];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = @"Arm (Long)";
        [_viewCustomStationList addSubview:label];
        
        
        textField = [[UITextField alloc] initWithFrame:CGRectMake(115, 121  + yPos , 80, 30)];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:16];
        textField.textAlignment = NSTextAlignmentLeft;
        textField.textColor = [UIColor blackColor];
        textField.tag = stationID + 500;
        [textField  setText: customStationDictionary[@"armLong"]   ];
        [textField setKeyboardType:UIKeyboardTypeNumberPad];
        [textField addTarget:self action:@selector(moveScrollViewCustomStation:)  forControlEvents:UIControlEventEditingDidBegin];
         [textField addTarget:self action:@selector(closeKeyboardCustomStation:)  forControlEvents:UIControlEventEditingDidEndOnExit];
        [_viewCustomStationList addSubview:textField];
        
        //--------------------------------------------------------
        
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(216, 92 +yPos, 110, 21)];
        label.font = [UIFont systemFontOfSize:16.0];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = @"Arm (Lateral)";    
        [_viewCustomStationList addSubview:label];
        
       
        textField = [[UITextField alloc] initWithFrame:CGRectMake(216, 121  + yPos , 80, 30)];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:16];
        textField.textAlignment = NSTextAlignmentLeft;
        textField.textColor = [UIColor blackColor];
        textField.tag = stationID + 600;
        [textField  setText: customStationDictionary[@"armLat"]  ];
        [textField setKeyboardType:UIKeyboardTypeNumberPad];
        [textField addTarget:self action:@selector(moveScrollViewCustomStation:)  forControlEvents:UIControlEventEditingDidBegin];
        [textField addTarget:self action:@selector(closeKeyboardCustomStation:)  forControlEvents:UIControlEventEditingDidEndOnExit];
        [_viewCustomStationList addSubview:textField];
        
        //--------------------------------------------------------
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(500, 92 +yPos, 110, 21)];
        label.font = [UIFont systemFontOfSize:16.0];
        label.textColor = [UIColor clearColor];
        label.textAlignment = NSTextAlignmentLeft;
        [label  setText: customStationDictionary[@"insertIndex"]   ];
        label.tag = stationID + 700;
        [_viewCustomStationList addSubview:label];
        
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(520, 92 +yPos, 150, 21)];
        label.font = [UIFont systemFontOfSize:16.0];
        label.textColor = [UIColor clearColor];
        label.textAlignment = NSTextAlignmentLeft;
        [label  setText: customStationDictionary[@"randomID"]   ];
        label.tag = stationID + 750;
        [_viewCustomStationList addSubview:label];
        
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(450, 92 +yPos, 150, 21)];
        label.font = [UIFont systemFontOfSize:16.0];
        label.textColor = [UIColor clearColor];
        label.textAlignment = NSTextAlignmentLeft;
        [label  setText: customStationDictionary[@"status"]   ];
        label.tag = stationID + 1000;
        [_viewCustomStationList addSubview:label];
        
         //--------------------------------------------------------
        
        
        if ([customStationDictionary[@"status"] isEqualToString:@"new"]) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            btn.frame = CGRectMake(392, 118 + yPos , 139, 40);
            [btn addTarget:self action:@selector(actionAddThisStation:)  forControlEvents:UIControlEventTouchUpInside];
            btn.tag = stationID ;
            [btn setTitle:@"Add This Station" forState:UIControlStateNormal];
            [btn  setBackgroundImage:[UIImage imageNamed: @"button generic blue.png"] forState:UIControlStateNormal];
            btn.tintColor = [UIColor whiteColor];
            btn.showsTouchWhenHighlighted = YES;
            [_viewCustomStationList addSubview:btn];
            
            
        }else{
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            btn.frame = CGRectMake(464, 118 + yPos , 67, 40);
            [btn addTarget:self action:@selector(actionDeleteThisStation:)  forControlEvents:UIControlEventTouchUpInside];
            btn.tag = stationID + 800;                
            //UIImage *buttonBack = [UIImage imageNamed:@"delete Icon 100x100.png"];
            //[btn setBackgroundImage:buttonBack forState:UIControlStateNormal]; 
            [btn setTitle:@"Delete" forState:UIControlStateNormal];
            [btn  setBackgroundImage:[UIImage imageNamed: @"button generic red.png"] forState:UIControlStateNormal];
            btn.tintColor = [UIColor whiteColor];
            [_viewCustomStationList addSubview:btn];
            
            btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            btn.frame = CGRectMake(325, 118 + yPos , 131, 38);
            [btn addTarget:self action:@selector(actionUpdateStation:)  forControlEvents:UIControlEventTouchUpInside];   
            btn.tag = stationID ;
            [btn setTitle:@"Update Station" forState:UIControlStateNormal];
            [btn  setBackgroundImage:[UIImage imageNamed: @"button generic blue.png"] forState:UIControlStateNormal];
            btn.tintColor = [UIColor whiteColor];
            btn.showsTouchWhenHighlighted = YES;
            [_viewCustomStationList addSubview:btn];
            
         
        }
        
      
        
        
        //--------------------------------------------------------
        
        yPos = yPos + yStep;
        
    }
    
    
    if (flagAllowCreateAnotherFlight == 1 & arrayCustomStations.count < 2) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(19, 5 + (arrayCustomStations.count * 190) , 166, 21);
        [btn addTarget:self action:@selector(actionCreateNewStation:)  forControlEvents:UIControlEventTouchUpInside];
        btn.tag = 900 ;
        [btn setTitle:@"Create Another Station" forState:UIControlStateNormal];
        [_viewCustomStationList addSubview:btn];
    }
    
    
      

}



- (IBAction)actionSetSymbol:(UIButton *)sender {
    
    //NSLog(@"actionSetSymbol %lu", sender.tag);
    UILabel *label = (UILabel*)[_viewCustomStationList viewWithTag: sender.tag - 350  + 300]; 
    
    //NSLog(@"label %@", label.text);
    if ([label.text isEqualToString:@"Seat"]) {
        label.text = @"Box 1";
        [self saveCustomStationFields];
        [self createCustomStationList];
        [self updateAllStations];
        return;
    }
    
    if ([label.text isEqualToString:@"Box 1"]) {
        label.text = @"Box 2";
        [self saveCustomStationFields];
         [self createCustomStationList];
        [self updateAllStations];
        return;
    }
    
    if ([label.text isEqualToString:@"Box 2"]) {
        label.text = @"Hook";
        [self saveCustomStationFields];
        [self createCustomStationList];
        [self updateAllStations];
        return;
    }
   
    
    if ([label.text isEqualToString:@"Hook"]) {
        label.text = @"Basket";
        [self saveCustomStationFields];
        [self createCustomStationList];
        [self updateAllStations];
        return;
    }
    
    if ([label.text isEqualToString:@"Basket"]) {
        label.text = @"Seat";
        [self saveCustomStationFields];
        [self createCustomStationList];
        [self updateAllStations];
        return;
    }
    
    
}


- (void) translateSymbolName : (NSString*)receivedName {
    
    translatedSymbolName = receivedName;
    
     
    
    if ([receivedName isEqualToString:@"Seat"]) {
        translatedSymbolName = @"seat";
        symSizeX = 45; symSizeY = 55;
        return;
    }
    
    if ([receivedName isEqualToString:@"Box 1"]) {
        translatedSymbolName = @"baggageBox";
        symSizeX = 45; symSizeY = 80;
        return;
    }
    
    if ([receivedName isEqualToString:@"Box 2"]) {
        translatedSymbolName = @"baggageBox";
        symSizeX = 80; symSizeY = 45;        
        return;
    }
    
    if ([receivedName isEqualToString:@"Hook"]) {
        translatedSymbolName = @"hook";
        symSizeX = 35; symSizeY = 55;
        return;
    }
    if ([receivedName isEqualToString:@"Basket"]) {
        translatedSymbolName = @"heliBasket";
        symSizeX = 45; symSizeY = 90;
        return;
    }
    
    
}

- (void) updateAllStations {
    
    [self saveCustomStationFields];    
    for (int i = 0; i < arrayCustomStations.count  ; i++) {         
        // customStationDictionary[@"status"] =   @"saved";        
        int insertIndex = [[[arrayCustomStations objectAtIndex: i ]  objectForKey:@"insertIndex"] intValue];         
        NSString *content;        
        content = [[arrayCustomStations objectAtIndex: i]  objectForKey:@"status"]; 
        if ([content isEqualToString:@"new"]) {
            continue;
        }
       
        content = [[arrayCustomStations objectAtIndex: i]  objectForKey:@"stationName"];    
        [_arrayName1 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:content];  
        content = [[arrayCustomStations objectAtIndex: i]  objectForKey:@"weight"];
        [_arrayName2 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:content];  //weight
        float weightValX = [content floatValue];
        content = [[arrayCustomStations objectAtIndex: i]  objectForKey:@"armLong"];   
        [_arrayName3 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:content];  //arm long 
        
        NSString *newMom = [NSString stringWithFormat:@"%.0f", [content floatValue] * weightValX ];
        [_arrayName4 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:newMom]; //mom 
        
        content = [[arrayCustomStations objectAtIndex: i]  objectForKey:@"armLat"]; 
        [_arrayName5 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:content]; 
        
        NSString *newMomLat = [NSString stringWithFormat:@"%.0f", [content floatValue] * weightValX ];
        [_arrayName6 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:newMomLat]; //mom lat
        
        [_arrayName7 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:@"-"]; //OCC name
        [_arrayName8 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:@"1"]; //ON/Off
        [_arrayName9 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:@"400"]; //max weight    
        content = [[arrayCustomStations objectAtIndex: i]  objectForKey:@"symbol"]; 
        [self translateSymbolName:content];
        content = translatedSymbolName;
        [_arrayName10 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:content];  //symbol  
        [_arrayName11 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:@"0"]; //offset long 
        content = [[arrayCustomStations objectAtIndex: i]  objectForKey:@"ID"]; 
        [_arrayName12 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:content];  //seat label 
        [_arrayName13 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:@"0"]; //lat offset 
        [_arrayName14 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:@"-"]; //specials   
        content = [[arrayCustomStations objectAtIndex: i]  objectForKey:@"rotation"]; 
        [_arrayName15 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:content];  //rotation 
        content = [[arrayCustomStations objectAtIndex: i]  objectForKey:@"randomID"];  
        [_arrayName16 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:content];  //l/r/crew     
        [_arrayName17 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:@""]; // item wegt
        [_arrayName18 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:@"free"]; // item arm retain (item arm if different)
        [_arrayName19 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:[NSString stringWithFormat:@"%.0f", symSizeX ]];  //symbol width
        [_arrayName20 replaceObjectAtIndex:(NSUInteger)insertIndex withObject:[NSString stringWithFormat:@"%.0f", symSizeY ]];  // symbol height
    }
    
  
    [self saveArrayListo];  
    [self createListoItemsSlidersAndInterior];    
    [self SaveValues];
    [self MainRoutine];
    [self createCustomStationList];
   
}

- (IBAction)moveScrollViewItemsFlightLegData:(UITextField *)sender {  
    
    if (flagIsLandscape == 0) {
        return;
    }
    //NSLog(@"moveScrollViewItemsFlightLegData %lu", sender.tag);
    // it works! scroll to the damn thing
    UIView *view = (UIView*)[_viewLegDataItems viewWithTag: sender.tag ];    
    CGRect zoomRect = CGRectMake(0, view.frame.origin.y - 50, _scrollViewLegData.frame.size.width, _scrollViewLegData.frame.size.height);  
    //NSLog(@"textField.frame.origin.y %f", view.frame.origin.y);
    [_scrollViewLegData scrollRectToVisible:zoomRect animated:YES];
}

- (IBAction)moveScrollViewCustomStation:(UITextField *)sender {  
    if (flagIsLandscape == 0) {
        return;
    }
    //NSLog(@"moveScrollViewCustomStation %lu", sender.tag);
    // it works! scroll to the damn thing
    UITextField *textField = (UITextField*)[_viewCustomStationList viewWithTag: sender.tag ];    
    CGRect zoomRect = CGRectMake(0, textField.frame.origin.y - 50, _scrollViewConfiguratorItems.frame.size.width, _scrollViewConfiguratorItems.frame.size.height);    
    [_scrollViewConfiguratorItems scrollRectToVisible:zoomRect animated:YES];
}


- (IBAction)closeKeyboardCustomStation:(UITextField *)sender { 
    [self.view endEditing:TRUE];    
    [self updateAllStations];
}


- (void) saveCustomStationFields {
    
    
    //NSLog(@"saveCustomStationFields %d", customStationID);   
    //NSLog(@"saveCustomStationFields arrayCustomStations.count  %lu", (unsigned long)arrayCustomStations.count ); 
    
    for (int i = 0; i < arrayCustomStations.count  ; i++) {        
        customStationDictionary = [[NSMutableDictionary alloc] init];        
        UILabel *label = (UILabel*)[_viewCustomStationList viewWithTag: i + 100 ]; 
        customStationDictionary[@"stationName"] =  label.text;        
        //NSLog(@"saving %@", label.text);        
        label = (UILabel*)[_viewCustomStationList viewWithTag: i + 200 ]; 
        customStationDictionary[@"ID"] =  label.text;        
        label = (UILabel*)[_viewCustomStationList viewWithTag: i + 300 ]; 
        customStationDictionary[@"symbol"] =  label.text;        
        label = (UILabel*)[_viewCustomStationList viewWithTag: i + 400 ]; 
        customStationDictionary[@"rotation"] =  label.text;  
        label = (UILabel*)[_viewCustomStationList viewWithTag: i + 450 ]; 
        customStationDictionary[@"weight"] =  label.text;        
        label = (UILabel*)[_viewCustomStationList viewWithTag: i + 500 ]; 
        customStationDictionary[@"armLong"] =  label.text;        
        label = (UILabel*)[_viewCustomStationList viewWithTag: i + 600 ]; 
        customStationDictionary[@"armLat"] =  label.text;        
        label = (UILabel*)[_viewCustomStationList viewWithTag: i + 700 ]; 
        customStationDictionary[@"insertIndex"] =  label.text; 
        label = (UILabel*)[_viewCustomStationList viewWithTag: i + 750 ]; 
        customStationDictionary[@"randomID"] =  label.text; 
        label = (UILabel*)[_viewCustomStationList viewWithTag: i + 1000 ]; 
        customStationDictionary[@"status"] =  label.text; 
        
        
        //NSLog(@"customStationDictionar status %@", customStationDictionary[@"status"]);
        //NSLog(@"flagAddCustomStation %@", customStationDictionary[@"status"]);
        
        if (flagAddCustomStation == 1) {
            if (i == customStationID) {
                customStationDictionary[@"status"] =   @"saved";
            }
        }
        [arrayCustomStations replaceObjectAtIndex:i withObject:customStationDictionary];          
    }
    
     flagAddCustomStation = 0;
    
    NSString *internalFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];                              
    [[NSUserDefaults standardUserDefaults]  setObject: arrayCustomStations  forKey:[ [NSString alloc] initWithFormat:@"%@%@", internalFlightID, @"arrayCustomStations" ]];
    
    //NSLog (@"saveCustomStationFields _arrayName1 %@", _arrayName1);
    
    
}

- (IBAction)actionUpdateStation:(UIButton *)sender {
    
    [self updateAllStations];
    
}

- (IBAction)actionAddThisStation:(UIButton *)sender {
    
    
    // save dictionary for each item    
    //NSLog(@"actionAddThisStation *****************");
    //NSLog(@"customStationDictionary %@", customStationDictionary);
        
    //NSLog(@"actionAddThisStation %lu", sender.tag);
    customStationID = sender.tag;
    flagAddCustomStation = 1;
    [self saveCustomStationFields];
    //NSLog (@"arrayCustomStations %@", arrayCustomStations);  
    
    int insertIndex = lineZFW;

   
 
    if (lineEquipment > 0 ) {
        insertIndex = lineEquipment;
        //NSLog(@" insertIndex = lineEquipment");
    }
   
    if (lineSeats > 0 ) {
        if (lineSeats < insertIndex) {
             insertIndex = lineEquipment;
            //NSLog(@" insertIndex = lineEquipment");
        }
    }
    
    NSString *content;
    content = [[arrayCustomStations objectAtIndex: sender.tag]  objectForKey:@"stationName"];
    [_arrayName1 insertObject:content atIndex:insertIndex];  
    content = [[arrayCustomStations objectAtIndex: sender.tag]  objectForKey:@"weight"];
    [_arrayName2 insertObject:content atIndex:insertIndex]; //weight    
    content = [[arrayCustomStations objectAtIndex: sender.tag]  objectForKey:@"armLong"]; 
    [_arrayName3 insertObject:content atIndex:insertIndex]; //arm long
    [_arrayName4 insertObject:@"0" atIndex:insertIndex];  //mom    
    content = [[arrayCustomStations objectAtIndex: sender.tag]  objectForKey:@"armLat"]; 
    [_arrayName5 insertObject:content atIndex:insertIndex]; //arm lat
    [_arrayName6 insertObject:@"0" atIndex:insertIndex]; //mom lat
    [_arrayName7 insertObject:@"-" atIndex:insertIndex]; //OCC name
    [_arrayName8 insertObject:@"1" atIndex:insertIndex]; //ON/Off
    [_arrayName9 insertObject:@"400" atIndex:insertIndex]; //max weight       
    content = [[arrayCustomStations objectAtIndex: sender.tag]  objectForKey:@"symbol"];    
    [self translateSymbolName:content]; 
    content = translatedSymbolName ;
    [_arrayName10 insertObject:content atIndex:insertIndex];//symbol    
    [_arrayName11 insertObject:@"0" atIndex:insertIndex]; //offset long    
    content = [[arrayCustomStations objectAtIndex: sender.tag]  objectForKey:@"ID"]; 
    [_arrayName12 insertObject:content atIndex:insertIndex]; //seat label
    [_arrayName13 insertObject:@"0" atIndex:insertIndex]; //lat offset
    [_arrayName14 insertObject:@"-" atIndex:insertIndex]; // specials
    content = [[arrayCustomStations objectAtIndex: sender.tag]  objectForKey:@"rotation"]; 
    [_arrayName15 insertObject:content atIndex:insertIndex]; //rotation
    content = [[arrayCustomStations objectAtIndex: sender.tag]  objectForKey:@"randomID"];
    [_arrayName16 insertObject:content atIndex:insertIndex]; //l/r/crew   
    [_arrayName17 insertObject:@"0" atIndex:insertIndex]; //item weight
    [_arrayName18 insertObject:@"free" atIndex:insertIndex]; // item arm retain (item arm if different)
    
    //[_arrayName19 insertObject:@"" atIndex:insertIndex]; //symbol width
    //[_arrayName20 insertObject:@"" atIndex:insertIndex]; // symbol height
    
    [_arrayName19 insertObject:[NSString stringWithFormat:@"%.0f", symSizeX ] atIndex:insertIndex]; //symbol width
    [_arrayName20 insertObject:[NSString stringWithFormat:@"%.0f", symSizeY ] atIndex:insertIndex]; // symbol height 

    
    [self saveArrayListo];    
    [self createListoItemsSlidersAndInterior];    
    [self SaveValues];
    [self MainRoutine];
    [self createCustomStationList];
   
}




- (IBAction)actionCreateNewStation:(UIButton *)sender {
    
    //NSLog(@"actionCreateNewStation sender.tag %lu", sender.tag);    
    [self initializeCustomStation];
    //NSLog(@"2 arrayCustomStations %@", arrayCustomStations);    
    NSString *internalFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];                              
    [[NSUserDefaults standardUserDefaults]  setObject: arrayCustomStations  forKey:[ [NSString alloc] initWithFormat:@"%@%@", internalFlightID, @"arrayCustomStations" ]];    
    [self createCustomStationList];
    
}




- (IBAction)actionDeleteThisStation:(UIButton *)sender {
    
    //NSLog(@"actionDeleteThisStation sender.tag %lu", sender.tag);
    
    //NSLog(@"1 arrayCustomStations %@", arrayCustomStations);
    
   
    
   
   int indexToDelete = 0;
   for (int i = 4; i < _arrayName1.count  ; i++) {
       NSString *randomIDwanted = [[arrayCustomStations objectAtIndex:  sender.tag - 800 ]  objectForKey:@"randomID"];
       //NSLog(@"randomIDwanted %@", randomIDwanted);
       if ([[_arrayName16 objectAtIndex: i] isEqualToString:randomIDwanted]) {
           indexToDelete = i;
           //NSLog(@"indexToDelete %d", indexToDelete);
           break;
       }
    }
    
    if (indexToDelete == 0) {
        return;
    }
    
    NSString *insertIndex = [NSString stringWithFormat:@"%d", indexToDelete ];
    
    
    //NSLog(@"deleting insertIndex %@", insertIndex);
    
    [_arrayName1 removeObjectAtIndex:[insertIndex integerValue]];  
    
    [_arrayName2 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName3 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName4 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName5 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName6 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName7 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName8 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName9 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName10 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName11 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName12 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName13 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName14 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName15 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName16 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName17 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName18 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName19 removeObjectAtIndex:[insertIndex integerValue]];
    [_arrayName20 removeObjectAtIndex:[insertIndex integerValue]];
    
    //[self MainRoutine];
    //[self SaveValues];
    
    [self createListoItemsSlidersAndInterior];
    
    [self MainRoutine];
    
    
    [arrayCustomStations removeObjectAtIndex:sender.tag - 800];
    NSString *internalFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];                              
    [[NSUserDefaults standardUserDefaults]  setObject: arrayCustomStations  forKey:[ [NSString alloc] initWithFormat:@"%@%@", internalFlightID, @"arrayCustomStations" ]];
    [self createCustomStationList];
    
    //NSLog(@"2 arrayCustomStations %@", arrayCustomStations);
    
    
}


- (void)loadArrayListo {
    
    if (AC_Type.length < 1) {
        AC_Type  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"AC_Type"];
    }    
  
    arrayConfigurations = [[NSMutableArray alloc] init];
    [arrayConfigurations setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"arrayConfigurations%@", AC_Type] ] mutableCopy]];
  
    NSMutableArray *arrayConfigButtonsRegistration   = [[NSMutableArray alloc] init];
    [arrayConfigButtonsRegistration setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"arrayConfigButtonsRegistration%@", AC_Type] ] mutableCopy]];
    
    if (flagLoadConfigDataForButton == 1) {
        flagLoadConfigDataForButton = 0;
        
    }else{
        for (int i = 0; i < arrayConfigButtonsRegistration.count  ; i++) {
            if ([[arrayConfigButtonsRegistration objectAtIndex:i] isEqualToString:vFlightRegistration.text]) {
                configuration = i;
                activeConfigButton = i;
                //NSLog (@"found at  configuration %d" , configuration );
                break;
            }
            configuration = 1;  
        }
    }
    if (configuration > arrayConfigurations.count) {
        configuration = 1;
    }
    
    NSString *configName = [arrayConfigurations objectAtIndex:configuration];
     NSString *configSetup = @"";    
    //NSLog (@"configuration %d", configuration);    
    //NSLog (@"arrayConfigButtonsRegistration %@", arrayConfigButtonsRegistration);    
    //NSLog (@"[arrayConfigButtonsRegistration objectAtIndex:configuration] %@", [arrayConfigButtonsRegistration objectAtIndex:configuration]);
    
    if ([[arrayConfigButtonsRegistration objectAtIndex:configuration] isEqualToString:@"noReg"]) {
        //NSLog (@"4");
        configSetup  = [NSString stringWithFormat:@"%@_%@_%@", AC_Type, @"noReg", configName ];
    }else{
        //NSLog (@"5");
        configSetup  = [NSString stringWithFormat:@"%@_%@_%@", AC_Type, vFlightRegistration.text, configName ];        
    }    
   //NSLog(@"configSetup; %@ ", configSetup);    
    //NSLog(@"AC_Type %@ ", AC_Type);
    //NSLog(@"previousACType %@ ", previousACType);
    //NSLog(@"loadArrayListo configSetup %@ ", configSetup);
    
    if (_arrayName21.count > 10) {
        previousOriginalWeightUnits =  [_arrayName21 objectAtIndex:5];
        previousOriginalFuelUnits =  [_arrayName21 objectAtIndex:15];
        
    }
    //NSLog(@"previousOriginalWeightUnits = %@", previousOriginalWeightUnits); 
    //NSLog(@"previousOriginalFuelUnits = %@", previousOriginalFuelUnits);
    
    [_arrayName1 setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName1"]]  mutableCopy]];    
    //NSLog (@"arrayName1 %@" , _arrayName1 );    
    [_arrayName2 setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName2"]]  mutableCopy]];    
    //NSLog (@"loadArrayListo arrayName2 %@" , _arrayName2 );    
    [_arrayName3 setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName3"]]  mutableCopy]];    
    [_arrayName4 setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName4"]]  mutableCopy]];    
    [_arrayName5 setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName5"]]  mutableCopy]];    
    [_arrayName6 setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName6"]]  mutableCopy]];    
    [_arrayName7 setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName7"]]  mutableCopy]];    
    [_arrayName8 setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName8"]]  mutableCopy]];    
    [_arrayName9 setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName9"]]  mutableCopy]];    
    [_arrayName10 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName10"]] mutableCopy]];    
    [_arrayName11 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName11"]] mutableCopy]];    
    [_arrayName12 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName12"]] mutableCopy]];    
    [_arrayName13 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName13"]] mutableCopy]];    
    [_arrayName14 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName14"]] mutableCopy]];    
    [_arrayName15 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName15"]] mutableCopy]];    
    [_arrayName16 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName16"]] mutableCopy]];    
    [_arrayName17 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName17"]] mutableCopy]];    
    [_arrayName18 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName18"]] mutableCopy]];    
    [_arrayName19 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName19"]] mutableCopy]];    
    [_arrayName20 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName20"]] mutableCopy]];    
    [_arrayName21 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName21"]] mutableCopy]];    
    [_arrayName22 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName22"]] mutableCopy]];    
    [_arrayName23 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName23"]] mutableCopy]];    
    [_arrayName24 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName24"]] mutableCopy]];    
    [_arrayName25 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[configSetup stringByAppendingString:@"arrayName25"]] mutableCopy]];
    
    //NSLog (@"loading arrayName1 %@" , _arrayName1 );    
    [self guidanceResetTotal];    
    [self setDefaultsForConfig];    
    [self setBasicsForConfiguration];    
    return;
    
}





// END el listo  END el listo END el listo END el listo END el listo END el listo END el listo END el listo END el listo END el listo END el listo END el listo END el listo END el listo


- (IBAction)buttonActionCheckE6B:(id)sender {
    
    
        [self SaveValues];
    

    
    
    
}









- (IBAction)butSelHeli_Cancel:(id)sender {
    
    _viewSelectHelicopter.hidden = YES;
    
    flagChangeCallsign = 0;
    flagShowOnlySameACType = 0;
     [self addHelicopterButtons];  
   
}




-(void) interpolateFuelMomentsLongitudinal {
    
    //NSLog(@"interpolateFuelMomentsLongitudinal ---- tankNumber %d", tankNumber);
    
   
  
    //NSLog(@"tankNumber %.0f", tankNumber);
    //NSLog(@"arrayFuelVolumeLONG %@", arrayFuelVolumeLONG);
    
    if (tankNumber == 1 ) {
        
              
        // fixed fuel arm for OLDER apps
        if (arrayFuelMomentLONG.count == 1) {
          
            fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * [[arrayFuelMomentLONG objectAtIndex: 0] floatValue]; 
            //NSLog(@"[[arrayFuelMomentLONG objectAtIndex: 0] floatValue] %.1f", [[arrayFuelMomentLONG objectAtIndex: 0] floatValue]);            
            //NSLog(@"[[arrayFuelMomentLONG objectAtIndex: 0] floatValue] %.0f", [[arrayFuelMomentLONG objectAtIndex: 0] floatValue]);            
            //NSLog(@" fuelMoment %.0f", fuelMoment);
           
             if ([AC_Type rangeOfString:@"R44Raven"].location != NSNotFound   || [AC_Type rangeOfString:@"R44Cadet"].location != NSNotFound   ) {   
                       
                 fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * 106.0;               
                 if (listoItemNr == lineZFW+1 || listoItemNr == lineTOW+1) {  
                     //NSLog(@"l interpolate");
                     fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * 106.0;
                 }
                 if (listoItemNr == lineZFW+2 || listoItemNr == lineTOW+2) {
                     fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * 102.0;
                     //NSLog(@"2 interpolate");
                 }
             }
            
            if ([AC_Type rangeOfString:@"R22Beta"].location != NSNotFound    ) {                 
                if (listoItemNr == lineZFW+1 || listoItemNr == lineTOW+1) {                    
                    fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * 108.6;
                }
                if (listoItemNr == lineZFW+2 || listoItemNr == lineTOW+2) {
                    fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * 103.8;
                }
            }
            
            //NSLog(@"long fuelVolume %.1f", fuelVolume);
            //NSLog(@"long fuelMoment %.1f", fuelMoment);
           
           
                
                
            return;
        }
        
               
        if ([[_arrayName18 objectAtIndex:(firstLineFuelTank-1) + tankNumber] rangeOfString:@"fix"].location != NSNotFound  ) {
            
            float fuelArm = [[_arrayName3 objectAtIndex:(firstLineFuelTank-1) + tankNumber] floatValue];
            //NSLog(@"1fuelArm %.1f", fuelArm);
            
            fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * fuelArm;
            //NSLog(@"11 fuelMoment %.0f", fuelMoment);
            return;
        }
        
       
      
        
        float GroupAkg = fuelVolume;
        //NSLog(@"GroupAkg %.0f", GroupAkg);
        
        fuelMoment = 0; OutLow2 = 0; OutHigh2 = 0; InLow2 = 0; InHigh2 = 0;
        
        for (int i = 0+addToStartIDforVariableTanks ; i<arrayFuelVolumeLONG.count-1; i++) {
            //NSLog(@"i %d", i);
            if (GroupAkg >= [[arrayFuelVolumeLONG objectAtIndex:i] floatValue]     & GroupAkg <= [[arrayFuelVolumeLONG objectAtIndex:i+1] floatValue]    ) {
                OutLow2 = [[arrayFuelMomentLONG objectAtIndex:i] floatValue];
                OutHigh2 = [[arrayFuelMomentLONG objectAtIndex:i +1] floatValue];
                InLow2 = [[arrayFuelVolumeLONG objectAtIndex:i] floatValue];
                InHigh2 = [[arrayFuelVolumeLONG objectAtIndex:i+1] floatValue];
                break;
            }
        }
        
        
        //NSLog(@"OutLow2 %.0f", OutLow2);
        //NSLog(@"OutHigh2 %.0f", OutHigh2);
        //NSLog(@"InLow2 %.0f", InLow2);
        //NSLog(@"InHigh2 %.0f", InHigh2);
        
        fuelMoment =  OutLow2  +  ((OutHigh2 - OutLow2)  *  (((GroupAkg - InLow2) * (100 / (InHigh2 - InLow2))) / 100 ));
        
        //NSLog(@"fuelMoment %.4f", fuelMoment);
        
        
        if (OutLow2 + OutHigh2 + InLow2 + InHigh2 == 0) {
            fuelMoment = 0;
        }
        if (GroupAkg < 1) {
            fuelMoment = 0;
        }
        //NSLog(@"1 fuelMoment %.0f", fuelMoment);
        return;
        
    }else{
        
        //NSLog(@"2tankNumber %d", tankNumber);
        
        if ([[_arrayName18 objectAtIndex:(firstLineFuelTank-1) + tankNumber] rangeOfString:@"fix"].location != NSNotFound  ) {
            float fuelArm = [[_arrayName3 objectAtIndex:(firstLineFuelTank-1) + tankNumber] floatValue];
            //NSLog(@"2fuelArm %.1f", fuelArm);
            
            fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * fuelArm;
            //NSLog(@"33 fuelMoment %.0f", fuelMoment);
            return;
        }
        
        // multiple fuel tanks *************************
        //NSLog(@"multiple tanks!");
        NSMutableArray *trenner = [[NSMutableArray alloc] init];
        for (int i = 0; i<arrayFuelVolumeLONG.count-1; i++) {
            if ([[arrayFuelMomentLONG objectAtIndex:i] isEqualToString:@"|"]) {
                [trenner addObject: [[NSString alloc] initWithFormat:@"%d ", i]];
                //NSLog(@"trenner %d", i);
            }
        }
        
        int startValue =  1 + [[trenner objectAtIndex: tankNumber -2] intValue];
        //NSLog(@"startValue %d", startValue);
        float GroupAkg = fuelVolume;
        fuelMoment = 0; OutLow2 = 0; OutHigh2 = 0; InLow2 = 0; InHigh2 = 0;
        //NSLog(@"arrayFuelVolumeLONG %@", arrayFuelVolumeLONG);
        
        
        
        for (int i = startValue; i<arrayFuelVolumeLONG.count; i++) {
            //NSLog(@"GroupAkg %.0f", GroupAkg);
            //NSLog(@"[[arrayFuelVolumeLONG objectAtIndex:i]  %@", [arrayFuelVolumeLONG objectAtIndex:i]);
            
            if (GroupAkg >= [[arrayFuelVolumeLONG objectAtIndex:i] floatValue]     & GroupAkg <= [[arrayFuelVolumeLONG objectAtIndex:i+1] floatValue]    ) {
                OutLow2 = [[arrayFuelMomentLONG objectAtIndex:i] floatValue];
                OutHigh2 = [[arrayFuelMomentLONG objectAtIndex:i +1] floatValue];
                InLow2 = [[arrayFuelVolumeLONG objectAtIndex:i] floatValue];
                InHigh2 = [[arrayFuelVolumeLONG objectAtIndex:i+1] floatValue];
                
                fuelMoment =  OutLow2  +  ((OutHigh2 - OutLow2)  *  (((GroupAkg - InLow2) * (100 / (InHigh2 - InLow2))) / 100 ))    ;
                if (OutLow2 + OutHigh2 + InLow2 + InHigh2 == 0) {
                    fuelMoment = 0;
                }
                if (GroupAkg < 1) {
                    fuelMoment = 0;
                }
                
                //NSLog(@"2 fuelMoment %.0f", fuelMoment);
                break;
            }
        }
        return;
    }
}



-(void) interpolateFuelMomentsLateral {
    
    
    
    //NSLog(@"***************** AC_Type %@", AC_Type);
    //NSLog(@"tankNumber %d", tankNumber);
    
    if (tankNumber == 1 ) {
        //NSLog(@"just one tank or first tank");
        // fixed fuel arm for OLDER apps
        if (arrayFuelMomentLAT.count == 1) {
            fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * [[arrayFuelMomentLAT objectAtIndex: 0] floatValue];
            
           
            if ([AC_Type rangeOfString:@"R44Raven"].location != NSNotFound   || [AC_Type rangeOfString:@"R44Cadet"].location != NSNotFound   ) {                 
                if (listoItemNr == lineZFW+1 || listoItemNr == lineTOW+1) {                    
                    fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * -13.5;
                }
                if (listoItemNr == lineZFW+2 || listoItemNr == lineTOW+2) {
                    fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * 13.0;
                }
            }
            
            if ([AC_Type rangeOfString:@"R22Beta"].location != NSNotFound    ) {                 
                if (listoItemNr == lineZFW+1 || listoItemNr == lineTOW+1) {                    
                    fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * -11.0;
                }
                if (listoItemNr == lineZFW+2 || listoItemNr == lineTOW+2) {
                    fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * 11.2;
                }
            }
            
            return;
        }
        
        
        
        if ([[_arrayName18 objectAtIndex:(firstLineFuelTank-1) + tankNumber] rangeOfString:@"fix"].location != NSNotFound  ) {
            //NSLog(@"11 fixed fuel arm");
            float fuelArm = [[_arrayName5 objectAtIndex:(firstLineFuelTank-1) + tankNumber] floatValue];
            fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * fuelArm;
            return;
        }
        
        //NSLog(@"variable fuel arm");
        float GroupAkg = fuelVolume;
        fuelMoment = 0; OutLow2 = 0; OutHigh2 = 0; InLow2 = 0; InHigh2 = 0;
        for (int i = 0+addToStartIDforVariableTanks; i<arrayFuelVolumeLAT.count-1; i++) {
            if (GroupAkg >= [[arrayFuelVolumeLAT objectAtIndex:i] floatValue]     & GroupAkg <= [[arrayFuelVolumeLAT objectAtIndex:i+1] floatValue]    ) {
                OutLow2 = [[arrayFuelMomentLAT objectAtIndex:i] floatValue];
                OutHigh2 = [[arrayFuelMomentLAT objectAtIndex:i +1] floatValue];
                InLow2 = [[arrayFuelVolumeLAT objectAtIndex:i] floatValue];
                InHigh2 = [[arrayFuelVolumeLAT objectAtIndex:i+1] floatValue];
                break;
            }
        }
        
        fuelMoment =  OutLow2  +  ((OutHigh2 - OutLow2)  *  (((GroupAkg - InLow2) * (100 / (InHigh2 - InLow2))) / 100 ))    ;
        if (OutLow2 + OutHigh2 + InLow2 + InHigh2 == 0) {
            fuelMoment = 0;
        }
        if (GroupAkg < 1) {
            fuelMoment = 0;
        }
        //NSLog(@"1 fuelMoment %.0f", fuelMoment);
        return;
        
    }else{
        
        if ([[_arrayName18 objectAtIndex:(firstLineFuelTank-1) + tankNumber] rangeOfString:@"fix"].location != NSNotFound  ) {
            float fuelArm = [[_arrayName5 objectAtIndex:(firstLineFuelTank-1) + tankNumber] floatValue];
            fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * fuelArm;
            return;
        }
        
        // multiple fuel tanks *************************
        //NSLog(@"multiple tanks!");
        NSMutableArray *trenner = [[NSMutableArray alloc] init];
        for (int i = 0; i<arrayFuelVolumeLAT.count-1; i++) {
            if ([[arrayFuelMomentLAT objectAtIndex:i] isEqualToString:@"|"]) {
                [trenner addObject: [[NSString alloc] initWithFormat:@"%d ", i]];
                //NSLog(@"trenner %d", i);
            }
        }
        
        int startValue =  1 + [[trenner objectAtIndex: tankNumber -2] intValue];
        //NSLog(@"startValue %d", startValue);
        float GroupAkg = fuelVolume;
        fuelMoment = 0; OutLow2 = 0; OutHigh2 = 0; InLow2 = 0; InHigh2 = 0;
        
        
        
        for (int i = startValue; i<arrayFuelVolumeLAT.count; i++) {
            //NSLog(@"GroupAkg %.0f", GroupAkg);
            if (GroupAkg >= [[arrayFuelVolumeLAT objectAtIndex:i] floatValue]     & GroupAkg <= [[arrayFuelVolumeLAT objectAtIndex:i+1] floatValue]    ) {
                OutLow2 = [[arrayFuelMomentLAT objectAtIndex:i] floatValue];
                OutHigh2 = [[arrayFuelMomentLAT objectAtIndex:i +1] floatValue];
                InLow2 = [[arrayFuelVolumeLAT objectAtIndex:i] floatValue];
                InHigh2 = [[arrayFuelVolumeLAT objectAtIndex:i+1] floatValue];
                
                fuelMoment =  OutLow2  +  ((OutHigh2 - OutLow2)  *  (((GroupAkg - InLow2) * (100 / (InHigh2 - InLow2))) / 100 ))    ;
                if (OutLow2 + OutHigh2 + InLow2 + InHigh2 == 0) {
                    fuelMoment = 0;
                }
                if (GroupAkg < 1) {
                    fuelMoment = 0;
                }
                
                //NSLog(@"2 LAT fuelMoment %.0f", fuelMoment);
                break;
            }
        }
        return;
    }
}







// Slider for Performance 


- (IBAction)buttonActionShowPickerTime:(UIButton *)sender {
    
    [self.view endEditing:TRUE]; 
    

    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier: [_arrayName23 objectAtIndex:9] ];    
   // NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_JM"]; //@"de_CH"]; // @"en_US" // @"en_US", en_US_POSIX = us am/pm, en_NZ, en_GU, en_CA  =am/pm
    [self.datepick setLocale:locale];    
    flagSetPickerTimeForFields = sender.tag;    
    _viewDatePicker.hidden = NO;    
    datepick.datePickerMode = UIDatePickerModeDateAndTime;    
    [viewOne bringSubviewToFront:_viewDatePicker];    
    [self setDatePickToNow];   
  
}




- (IBAction) datepickCancelButton {
    
    _viewDatePicker.hidden = YES;  
    
}


- (IBAction) datepickSetToNowButton {
        
    [self setDatePickToNow];
   
}

- (void) setDatePickToNow {
    
    NSDate *now = [[NSDate alloc] init];
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *comps = [cal components: NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:now];
    NSDate *date = [cal dateFromComponents:comps];    
    [self.datepick setDate:date animated:TRUE];
    NSDateFormatter* df = [[NSDateFormatter alloc]init];    
    df.dateFormat = [_arrayName23 objectAtIndex: 38] ;
    // set GMT and Local Time    
    NSDate *currentTime = datepick.date;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    
    [dateFormatter setDateFormat: [_arrayName23 objectAtIndex: 38] ];    
    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [dateFormatter setTimeZone:gmt];
    NSString *resultString = [dateFormatter stringFromDate: currentTime];    
    NSTimeZone *localTZ = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTZ];    
    NSString *localTimeString = [dateFormatter stringFromDate: currentTime];
    //NSLog(@"-------- GMT Time %@", resultString);    
    //NSLog(@"-------- Local    %@", localTimeString);
    resultString = [resultString stringByAppendingString:@" [GMT]"];    
    localTimeString = [localTimeString stringByAppendingString:@""]; 
    /*
    if (flagSetPickerTimeForFields == 1) {
        _labelDepartureTimeLocal.text = localTimeString;        
        _labelDepartureTimeGMT.text = resultString;
    }else{        
        _labellandingtimeLocal.text = localTimeString;
    }
     */
}



- (IBAction) datepickButtonOK {    
    [self setDateFromPicker];
}


- (void) setDateFromPicker{
    [_depp becomeFirstResponder];    
    [self.view endEditing:TRUE];    
    _viewDatePicker.hidden = YES;   
    NSDateFormatter* df = [[NSDateFormatter alloc]init] ;    
    df.dateFormat = [_arrayName23 objectAtIndex: 38];    
    // set GMT or Local Time    
    NSDate *currentTime = datepick.date;    
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    
    [dateFormatter setDateFormat: [_arrayName23 objectAtIndex: 38] ];    
    NSTimeZone *localTZ = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTZ];    
    NSString *localTimeString = [dateFormatter stringFromDate: currentTime];    
    localTimeString = [localTimeString stringByAppendingString:@""]; //@" [LOCAL]"];   
    if (flagSetPickerTimeForFields == 1) {
        _labelDepartureTimeLocal.text = localTimeString;        
    }else{
        _labellandingtimeLocal.text = localTimeString;        
    }
    [self MainRoutine];    
    
}





- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
        
    //NSLog(@"touchesBegan:withEvent:");
    [self.view endEditing:YES];
    
    [_depp becomeFirstResponder];
    
    [self.view endEditing:TRUE];
    [super touchesBegan:touches withEvent:event];
}



- (void) findLines {
    
  
    
    lineJackets = 0;
    lineSeats = 0;
    lineSeatsOccupied = 0;
    lineDualControls = 0;
    linePatient = 0;
    
    lineExternal = 0;
    lineHoistSystem = 0;
    lineHoistLoad = 0;
    lineFuelTankTotal = 0;
    
    lineFirstFuelTankTO = 0;
    lineFirstFuelTankLD = 0;
    lineEquipment = 0;
    
    amountOfFuelTanksTO = 0;
    amountOfFuelTanksLD= 0;
    
    lineEnd = 0;
    lineOptions = 0;
    lineOptionsEnd = 0;

    
    //int externalLoadActivated = 0;
    
    for (int i = 1; i < _arrayName1.count  ; i++) {
        
        //NSLog(@"[_arrayName1 objectAtIndex: i  ] %@", [_arrayName1 objectAtIndex: i  ]);
        
        
        // find ZFW
        if ([[_arrayName1 objectAtIndex: i  ] rangeOfString:@"ZFW"].location != NSNotFound     ||[[_arrayName1 objectAtIndex: i  ] rangeOfString:@"ZFM"].location != NSNotFound                   ) {
            lineZFW = i;
        }
        
        //NSLog(@"lineZFW %.0f ", lineZFW);
        
        // find patient
        if ([[_arrayName1 objectAtIndex: i  ] rangeOfString:@"Patient"].location != NSNotFound     ) {
            linePatient = i;
        }
        
        if ([[_arrayName1 objectAtIndex:i] isEqualToString:[_arrayName23 objectAtIndex:50]]) {
            lineFreeLoad = i;
        }
        
        // find TOW
        if ([[_arrayName1 objectAtIndex: i  ] rangeOfString:@"TOW"].location != NSNotFound     ||[[_arrayName1 objectAtIndex: i  ] rangeOfString:@"TOM"].location != NSNotFound                   ) {
            lineTOW = i;
        }
        
        // find LDW
        if ([[_arrayName1 objectAtIndex: i  ] rangeOfString:@"LDW"].location != NSNotFound     ||[[_arrayName1 objectAtIndex: i  ] rangeOfString:@"LDM"].location != NSNotFound                   ) {
            lineLDW = i;
            listEnd = i;
        }
        
        if ([[self.arrayName14 objectAtIndex: i  ] rangeOfString:@"%MAC LD"].location != NSNotFound               ) {
            listEnd = i;
        }
        
       
        if ([[_arrayName10 objectAtIndex: i  ] isEqualToString:@"fuelTankTotal"] ) {
            lineFuelTankTotal = i;
        }

        
        // find MCM
        if ([[_arrayName1 objectAtIndex: i  ] isEqualToString:@"MCM"] ) {
            lineMCM = i;
        }
        
        // find "Seats
        if ([[_arrayName1 objectAtIndex: i  ] isEqualToString:@"Seats"] || [[_arrayName1 objectAtIndex: i  ] isEqualToString:@"Seats/Equip."]  || [[_arrayName1 objectAtIndex: i  ] isEqualToString:@"Seats/Sled"]) {
            lineSeats = i;
        }
        
        if ([[_arrayName1 objectAtIndex: i  ] isEqualToString:@"Seats Occupied"] ) {
            lineSeatsOccupied = i;
        }
        
        if ([[_arrayName1 objectAtIndex: i  ] rangeOfString:@"Wt. Jackets"].location != NSNotFound  ) {
            lineJackets = i;
        }
        
        
        // find "Equipment
        if ([[_arrayName1 objectAtIndex: i  ] rangeOfString:@"Equipment"].location != NSNotFound  ) {
            lineEquipment = i;
        }
        
        if ( [[_arrayName1 objectAtIndex: i  ] rangeOfString:@"External"].location != NSNotFound ||  [[_arrayName1 objectAtIndex: i  ] rangeOfString:@"Double Hook"].location != NSNotFound  || [[_arrayName1 objectAtIndex: i  ] isEqualToString:@"Aussenlast"] ) {
            if (lineExternal <=0) {
                lineExternal = i;
            }
        }
        
        if ([[_arrayName1 objectAtIndex: i  ] rangeOfString:@"Dual Controls"].location != NSNotFound   ) {
            if (lineDualControls <=0) {
                lineDualControls = i;
            }
           
        }
        
        // find "Hoist
        if ([[_arrayName1 objectAtIndex: i  ] rangeOfString:@"Hoist Load"].location != NSNotFound || [[_arrayName1 objectAtIndex: i  ] isEqualToString:@"Hoist RH"] || [[_arrayName1 objectAtIndex: i  ] isEqualToString:@"Hoist LH"] ) {
            
              if (lineHoistLoad <=0) {         
                lineHoistLoad = i;
              }
        }
        
        if ([[_arrayName1 objectAtIndex: i  ] rangeOfString:@"Hoist System"].location != NSNotFound || [[_arrayName1 objectAtIndex: i  ] isEqualToString:@"Hoist System LH"] || [[_arrayName1 objectAtIndex: i  ] isEqualToString:@"Hoist System RH"]  ) {
            
            if (lineHoistSystem <=0) {
                lineHoistSystem = i;
            }
        }
        
        
        if ([[_arrayName1 objectAtIndex: i  ] rangeOfString:@"Cargo Load"].location != NSNotFound  ) {
            lineCargoLoad = i;
        }
        
        // find Options
        if ([[_arrayName1 objectAtIndex: i  ] isEqualToString:@"Options"] ) {
            lineOptions = i;
        }
        
        if ([[_arrayName1 objectAtIndex: i  ] isEqualToString:@"OptionsEnd"] ) {
            lineOptionsEnd = i; 
            lineForPenaltyOptionsEnd = i;
        }
        
        // find End
        if ([[_arrayName1 objectAtIndex: i  ] isEqualToString:@"End"] ) {
            lineEnd = i;
            break;
        }
        
        
    }
    
    
    for (int i = 1; i < _arrayName1.count  ; i++) {
        if ([[self.arrayName10 objectAtIndex: i  ] isEqualToString:@"fuelTank"] ) {
            if (i < lineTOW) {
                amountOfFuelTanksTO = amountOfFuelTanksTO +1;
            }
            if (i > lineTOW) {
                amountOfFuelTanksLD = amountOfFuelTanksLD +1;
            }
            if (lineFirstFuelTankTO == 0 & i < lineTOW) {
                lineFirstFuelTankTO = i;
            }
            if (lineFirstFuelTankLD == 0 & i > lineTOW) {
                lineFirstFuelTankLD = i;
            }
        }
    }
    
  
    
    return;
    
}










// add buttons





- (void) addPerformanceButtons {
    
    
    _scrollViewUniversalButtons.backgroundColor = [UIColor clearColor];    
    //NSLog(@"addPerformanceButtons  amountofButtonsNeeded %d", amountofButtonsNeeded);  
    
    
    [self loadPerfChartData];    
    amountOfButtons = amountofButtonsNeeded ;
    if (flagIsLandscape == 1) {
         viewTopDisplayButtons.frame = CGRectMake( -2, 54, 1031, 73 ) ;
         _triangleWhite.frame = CGRectMake( 188, 13, 19, 38 );
        _viewButtonOATPA.frame = CGRectMake( -1, 6, 186, 52 );  buttonDisplayEnvironment.frame = CGRectMake( 1, 0, 182, 52 );
        _viewButtonOATlabelOAT.frame = CGRectMake( 2, 1, 90, 23 ); labelDisplayOAT.frame = CGRectMake( 2, 22, 92, 23 );
        _viewButtonOATLabelPA.frame = CGRectMake( 82, 1, 90, 23 ); labelDisplayPA.frame = CGRectMake( 75, 22, 92, 23 );
    }else{
         viewTopDisplayButtons.frame = CGRectMake( 645, 54, 150, 650 ) ;
        _triangleWhite.frame = CGRectMake( 45, 105, 38, 19 );
        float yGapEnvi = 5;
        _viewButtonOATPA.frame = CGRectMake( -1, 3, 128, 95 );  buttonDisplayEnvironment.frame = CGRectMake( 0, 0, 128, 95 ) ;
        _viewButtonOATlabelOAT.frame = CGRectMake( 0, yGapEnvi, 128, 23 ) ; labelDisplayOAT.frame = CGRectMake( 0, yGapEnvi+20, 128, 23 ) ;
        _viewButtonOATLabelPA.frame = CGRectMake( 0, yGapEnvi+20+20, 128, 23 ) ; labelDisplayPA.frame = CGRectMake( 0, yGapEnvi+20+20+20, 128, 23 ) ;
         _viewTrennerTop.hidden = NO;
    }
    
    
    if (flagIsLandscape == 1) {
        _scrollViewTopDisplayButton.frame = CGRectMake( -2, 54, 1031, 73 );
        viewTopDisplayButtons.frame = CGRectMake(  0,  0, 1031, 73 ) ;
    }else{
        _scrollViewTopDisplayButton.frame = CGRectMake( 645, 54, 150, 650 ) ;
        viewTopDisplayButtons.frame = CGRectMake(   0,  0, 150, 650 ) ;
    }
    
    //reihenfolge    
    //scrollViewTopDisplayButton 
    //viewLegButtons
        //darin
        //viewTopDisplayButtons   
        //button OAT PA
    //scrollViewUniversalButtons 
    //darin
    //viewUniversalButtons
    
    _scrollViewTopDisplayButton.backgroundColor = [UIColor clearColor];
     viewTopDisplayButtons.backgroundColor = [UIColor clearColor];
    _viewUniversalButtons.backgroundColor = [UIColor clearColor];
    
    
    for(UIView *subview in [_viewUniversalButtons subviews]) {
        [subview removeFromSuperview];
    }    
    float bGap = 0;
    float xEdgeLeft =  0;
    float xEdgeRight  = 0;
    float buttonWidth = 0;
    float xStartLeft = 0;
    float yCoord=0;
    float buttonHeight=0;
    
    // create buttons for each Performance item    
    if (flagIsLandscape == 1) {
        bGap = 2;
        xEdgeLeft =  8;  // next to triangle
        
        //buttonWidth =   ( (xEdgeRight - xEdgeLeft + (amountOfButtons) )    )    / amountOfButtons;
        buttonWidth =  119 ;
        if (_arrayName23.count > 40) {
            if ([[_arrayName23 objectAtIndex:42] floatValue] > 0) {
                buttonWidth = [[_arrayName23 objectAtIndex:42] floatValue];
            }
        }
       
        xEdgeRight  = (amountOfButtons * buttonWidth)   + ( amountOfButtons * bGap);
        //NSLog(@"buttonWidth %.0f", buttonWidth);
        xStartLeft = xEdgeLeft ;
        yCoord=6;
        buttonHeight=52;
        _scrollViewUniversalButtons.frame     = CGRectMake(  209, 0, 822, 73  );
        [_scrollViewUniversalButtons setScrollEnabled:YES];
        _viewUniversalButtons.frame     = CGRectMake(  0, 0, xEdgeRight + 209, 73  );
        //NSLog(@"xEdgeRight %.0f", xEdgeRight);
        [_scrollViewUniversalButtons setContentSize:CGSizeMake(_viewUniversalButtons.frame.size.width, 73)];
        
    }else{
        // this is just for scrolling to the button
        bGap = 2;
        xEdgeLeft =  8;
        xEdgeRight  = (amountOfButtons * 180)   + ( amountOfButtons * bGap);
        buttonWidth =   ( (xEdgeRight - xEdgeLeft + (amountOfButtons) )    )    / amountOfButtons;
        
        // if portrait
        xEdgeLeft =  0;  // next to triangle
        xEdgeRight  = 150;
        buttonWidth = 128;
        xStartLeft = xEdgeLeft ;
        yCoord=6;
        buttonHeight=65;
        _scrollViewUniversalButtons.frame     = CGRectMake(  -1, 130, 150, 500  );
        [_scrollViewUniversalButtons setScrollEnabled:YES];
        _viewUniversalButtons.frame     = CGRectMake(  0, 0, xEdgeRight, amountOfButtons * buttonHeight  );
        [_scrollViewUniversalButtons setContentSize:CGSizeMake(_viewUniversalButtons.frame.size.width , _viewUniversalButtons.frame.size.height)];
        _viewTrennerTop.hidden = NO;        
    }
    
    //the helicopters array contains all helicopter objects that came from the server
    float xPosButton = 0;
    for(int p=1; p<amountOfButtons+1; p++) {
        xPosButton = xPosButton + 1;
        UIButton *perfButton = [UIButton buttonWithType:UIButtonTypeCustom];
        if (flagIsLandscape == 1) {
            perfButton.frame     = CGRectMake(  ( xStartLeft - buttonWidth )  +  (xPosButton * (buttonWidth -bGap ))  , yCoord, buttonWidth, buttonHeight );
        }else{
            perfButton.frame     = CGRectMake(   xStartLeft  , (xPosButton-1) * buttonHeight, buttonWidth, buttonHeight );
        }
        [perfButton setTag:p];
        [perfButton addTarget:self action:@selector(actionPerfbuttons:) forControlEvents:UIControlEventTouchUpInside];
        
        // create labels Headline
        UILabel *label = [[UILabel alloc] init];
        label.tag = p+100;
        
        if (flagIsLandscape == 1) {
            label.frame     = CGRectMake(  ( xStartLeft - buttonWidth )  +  (xPosButton * (buttonWidth -bGap )) +5 , yCoord-12, buttonWidth - 10, buttonHeight );
             [label setFont:[UIFont systemFontOfSize:14]];
        }else{
            label.frame     = CGRectMake( xStartLeft  +5 , ((xPosButton-1) * buttonHeight) -12, buttonWidth - 10, buttonHeight );
             [label setFont:[UIFont systemFontOfSize:14]];
        }
        
        label.textColor = [UIColor colorWithRed:216.0/255.0f green:216.0/255.0f blue:216.0/255.0f alpha:1.0f];
        label.textAlignment = NSTextAlignmentCenter;
        label.shadowColor = [UIColor blackColor];
        label.shadowOffset = CGSizeMake(1.0, 1.0);
        label.adjustsFontSizeToFitWidth = YES;   // trick to shrink fonts            
        label.minimumScaleFactor = 0.3; 
        
        // create labels Values
        UILabel *label2 = [[UILabel alloc] init];
        label2.tag = p+200;
        
        if (flagIsLandscape == 1) {
            label2.frame     = CGRectMake(  ( xStartLeft - buttonWidth )  +  (xPosButton * (buttonWidth -bGap )) + 5  , yCoord+6, buttonWidth-10, buttonHeight );
        }else{
            label2.frame     = CGRectMake( xStartLeft +5 , ((xPosButton-1) * buttonHeight) +8, buttonWidth -10, buttonHeight );
        }
        
        
        [label2 setFont:[UIFont boldSystemFontOfSize:17]];
        label2.textColor = [UIColor whiteColor];
        label2.textAlignment = NSTextAlignmentCenter;
        label2.shadowColor = [UIColor blackColor];
        label2.shadowOffset = CGSizeMake(1.0, 1.0);
        label2.adjustsFontSizeToFitWidth = YES;   // trick to shrink fonts            
        label2.minimumScaleFactor = 0.3; 
        
        UIImage *bg = [UIImage imageNamed:@"bg.png"];
        UIImage *bb = [UIImage imageNamed:@"bb.png"];
        
        [perfButton setBackgroundImage:bg forState:UIControlStateNormal];
        [perfButton setBackgroundImage:bb forState:UIControlStateHighlighted];
        [perfButton setBackgroundImage:bb forState:UIControlStateSelected];        
        
        [_viewUniversalButtons addSubview:perfButton];
        [_viewUniversalButtons addSubview:label];
        [_viewUniversalButtons addSubview:label2];
        
       
        
    }
    
    //signalStripe
    UIView *signalStripe = [[UIView alloc] init];
    signalStripe.tag = 999;
    
    signalStripe.backgroundColor = [UIColor lightGrayColor];
    //buttonSignalStripe.frame     = CGRectMake(  ( xStartLeft - buttonWidth )  +  (xPosButton * (buttonWidth -bGap ))  , yCoord+50, buttonWidth, 5 );
    
    signalStripe.frame     = CGRectMake(  ( xStartLeft - buttonWidth )    , yCoord+50, buttonWidth, 5 );
    signalStripe.hidden = YES;
    [_viewUniversalButtons addSubview:signalStripe];

    
    
    if (amountofButtonsNeeded < 1) {
        _viewButtonOATPA.hidden = YES;
        _scrollViewUniversalButtons.hidden = YES;
        _triangleWhite.hidden = YES;
        _labelNoPerfCompAvail.hidden = NO;             
        [viewTopDisplayButtons bringSubviewToFront:_labelNoPerfCompAvail];
        if (flagIsLandscape == 1) {
            _labelNoPerfCompAvail.text = @"No performance computations available";
        }else{
            _labelNoPerfCompAvail.text = @"No perf.";
        }
        
    }else{
        _viewButtonOATPA.hidden = NO; 
        _scrollViewUniversalButtons.hidden = NO;
        _triangleWhite.hidden = NO;
        _labelNoPerfCompAvail.hidden = YES;
        
    }
    
       
    return;
    
    
}

- (void) addPerfBox {
    
    //NSLog(@"addPerfBox");
    
   NSMutableArray *tempArrayResultsAllMargins = [[NSMutableArray alloc] init];
    [tempArrayResultsAllMargins setArray:  [[[NSUserDefaults standardUserDefaults] objectForKey:@"resultsAllMargins"]  mutableCopy]];
    //NSLog(@"tempArrayResultsAllMargins %@", tempArrayResultsAllMargins);
    
   
    
    displayWindow = 0; [self displayWindows];
    //for(UIView *subview in [_viewUniversalButtons subviews]) { [subview removeFromSuperview]; }
    [_viewUniversalButtons.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; 
    
    float bGap = 0;
    float xEdgeLeft =  0;
    float xEdgeRight  = 0;
    float buttonWidth = 0;
    float xStartLeft = 0;
    float yCoord=0;
    float buttonHeight=0;
    float lineCounter = 0;
    float buttonCounter = 0;
    float buttonPerRow = 3;
    // create buttons for each Performance item
    
    if (flagIsLandscape == 1) {
       
        float xMove = 0;
        if (_segmentFlightLegMode.selectedSegmentIndex == 0) {
            xMove = 0;
        }else{
            int numberOfLegsThisFlight = [[flightSettingsDictionary  objectForKey:@"numberOfLegsThisFlight"] floatValue];
            xMove = 4 + (numberOfLegsThisFlight * 73);
        }
        _viewButtonOATPA.frame = CGRectMake( -1 + xMove, 6, 186, 52 );  buttonDisplayEnvironment.frame = CGRectMake( 1 , 0, 182, 52 );
        _viewButtonOATlabelOAT.frame = CGRectMake( 2, 1, 90, 23 ); labelDisplayOAT.frame = CGRectMake( 2, 22, 92, 23 );
        _viewButtonOATLabelPA.frame = CGRectMake( 82, 1, 90, 23 ); labelDisplayPA.frame = CGRectMake( 75, 22, 92, 23 );
        _triangleWhite.frame = CGRectMake( 188 + xMove, 13, 19, 38 );
    

        ///viewTopDisplayButtons  -- _scrollViewUniversalButtons --  _viewUniversalButtons
        viewTopDisplayButtons.backgroundColor = [UIColor clearColor]; 
  
        _scrollViewTopDisplayButton.frame = CGRectMake( -2, 54, 648, 650 );
        viewTopDisplayButtons.frame = CGRectMake(0, 0, 648, 650 );
        _scrollViewUniversalButtons.frame     = CGRectMake(  0, 60, viewTopDisplayButtons.frame.size.width, viewTopDisplayButtons.frame.size.height  );
        
        
        [viewOne bringSubviewToFront: _scrollViewTopDisplayButton];       
        [viewMain bringSubviewToFront:viewEnvironment]; viewEnvironment.hidden =NO;
        
        bGap = 2;
        xEdgeLeft =  0;  // next to triangle
        xEdgeRight  = (amountOfButtons * 180)   + ( amountOfButtons * bGap);
        buttonWidth =   ( (xEdgeRight - xEdgeLeft + (amountOfButtons) )    )    / amountOfButtons;
        buttonWidth = viewTopDisplayButtons.frame.size.width / buttonPerRow;
        xStartLeft = xEdgeLeft ;
        buttonHeight=100;   
         
        _scrollViewUniversalButtons.backgroundColor = [UIColor blackColor]; 
        _viewUniversalButtons.frame     = CGRectMake(  0, -77, 265, 805  );        
        
        [_scrollViewUniversalButtons setScrollEnabled:YES];        
        [_scrollViewUniversalButtons setContentSize:CGSizeMake(_viewUniversalButtons.frame.size.width, (amountOfButtons/3) * buttonHeight + 100)];          
        [_scrollViewUniversalButtons scrollRectToVisible:CGRectMake( 1,1,1,1 ) animated:NO];   
        //[viewOne bringSubviewToFront:_scrollViewUniversalButtons];
        
    }else{
              
         float xMove = 0;
         if (_segmentFlightLegMode.selectedSegmentIndex == 0) {
             xMove = 0;
         }else{
             int numberOfLegsThisFlight = [[flightSettingsDictionary  objectForKey:@"numberOfLegsThisFlight"] floatValue];
             xMove = 4 + (numberOfLegsThisFlight * 73);
         }
         _viewButtonOATPA.frame = CGRectMake( -1 + xMove, 6, 186, 52 );  buttonDisplayEnvironment.frame = CGRectMake( 1 , 0, 182, 52 );
         _viewButtonOATlabelOAT.frame = CGRectMake( 2, 1, 90, 23 ); labelDisplayOAT.frame = CGRectMake( 2, 22, 92, 23 );
         _viewButtonOATLabelPA.frame = CGRectMake( 82, 1, 90, 23 ); labelDisplayPA.frame = CGRectMake( 75, 22, 92, 23 );
         _triangleWhite.frame = CGRectMake( 188 + xMove, 13, 36, 38 );

         ///viewTopDisplayButtons  -- _scrollViewUniversalButtons --  _viewUniversalButtons
         viewTopDisplayButtons.backgroundColor = [UIColor blackColor]; 
         _scrollViewTopDisplayButton.frame = CGRectMake( -2, 54, 648, 570 );
         viewTopDisplayButtons.frame = CGRectMake( 0, 0, 648, 570 );
         _scrollViewUniversalButtons.frame     = CGRectMake(  0, 60, viewTopDisplayButtons.frame.size.width, viewTopDisplayButtons.frame.size.height  );
         
         
         [viewOne bringSubviewToFront: _scrollViewTopDisplayButton];       
         [viewMain bringSubviewToFront:viewEnvironment]; viewEnvironment.hidden =NO;
         
         bGap = 2;
         xEdgeLeft =  0;  // next to triangle
         xEdgeRight  = (amountOfButtons * 180)   + ( amountOfButtons * bGap);
         buttonWidth =   ( (xEdgeRight - xEdgeLeft + (amountOfButtons) )    )    / amountOfButtons;
         buttonWidth = viewTopDisplayButtons.frame.size.width / buttonPerRow;
         xStartLeft = xEdgeLeft ;
         buttonHeight=100;       
          
        
         _scrollViewUniversalButtons.backgroundColor = [UIColor blackColor];                
         _viewUniversalButtons.frame     = CGRectMake(  0, -77, 265, 805  );        
         
         [_scrollViewUniversalButtons setScrollEnabled:YES];        
         [_scrollViewUniversalButtons setContentSize:CGSizeMake(_viewUniversalButtons.frame.size.width, (amountOfButtons/3) * buttonHeight + 100)];          
         [_scrollViewUniversalButtons scrollRectToVisible:CGRectMake( 1,1,1,1 ) animated:NO];   
         //[viewOne bringSubviewToFront:_scrollViewUniversalButtons];
        
    }
    
    UILabel *label = [[UILabel alloc] init];           
           label.frame     = CGRectMake( 0 , 76, 650, 25 );
           [label setFont:[UIFont systemFontOfSize:14]];          
           
           label.textColor = [UIColor blackColor];
           label.textAlignment = NSTextAlignmentCenter; 
    label.backgroundColor = [UIColor orangeColor];
    [label setText:@"Note: Check CG to verify available loads!"];
            
    [_viewUniversalButtons addSubview:label];
    
    for(int p=1; p<amountOfButtons+1; p++) {
      
        buttonCounter = buttonCounter + 1;
        if (buttonCounter == buttonPerRow + 1) {
            buttonCounter = 1;
            lineCounter = lineCounter +1;
        }
        
        if (flagIsLandscape == 1) {
           yCoord= buttonHeight * lineCounter + 75 + 25;
        }else{
           yCoord= buttonHeight * lineCounter + 75 + 25;
        }
        
        //NSLog(@"lineCounter %.0f", lineCounter);
        //NSLog(@"yCoord %.0f", yCoord);
        
       
        
        UIButton *perfButton = [UIButton buttonWithType:UIButtonTypeCustom];        
        perfButton.frame     = CGRectMake( (buttonCounter * buttonWidth) -  buttonWidth , yCoord, buttonWidth, buttonHeight );
        
        [perfButton setTag:p];
        [perfButton addTarget:self action:@selector(actionPerfbuttons:) forControlEvents:UIControlEventTouchUpInside];
        // create labels Headline
        UILabel *label = [[UILabel alloc] init];
        label.tag = p+100;
        label.frame     = CGRectMake( (buttonCounter * buttonWidth) -  buttonWidth , yCoord +7, buttonWidth, 25 );
        [label setFont:[UIFont systemFontOfSize:16]];
        
        
        label.textColor = [UIColor colorWithRed:216.0/255.0f green:216.0/255.0f blue:216.0/255.0f alpha:1.0f];
        label.textAlignment = NSTextAlignmentCenter;
        label.shadowColor = [UIColor blackColor];
        label.shadowOffset = CGSizeMake(1.0, 1.0);
        // create labels Values
        UILabel *label2 = [[UILabel alloc] init];
        label2.tag = p+200;
        label2.frame     = CGRectMake( (buttonCounter * buttonWidth) -  buttonWidth , yCoord +27, buttonWidth, 25 );
       
        [label2 setFont:[UIFont boldSystemFontOfSize:17]];
        label2.textColor = [UIColor whiteColor];
        label2.textAlignment = NSTextAlignmentCenter;
        label2.shadowColor = [UIColor blackColor];
        label2.shadowOffset = CGSizeMake(1.0, 1.0);
        UIImage *bg = [UIImage imageNamed:@"bg.png"];
        UIImage *bb = [UIImage imageNamed:@"bb.png"];
        [perfButton setBackgroundImage:bg forState:UIControlStateNormal];
        [perfButton setBackgroundImage:bb forState:UIControlStateHighlighted];
        [perfButton setBackgroundImage:bb forState:UIControlStateSelected];
        [_viewUniversalButtons addSubview:perfButton];
        [_viewUniversalButtons addSubview:label];
        [_viewUniversalButtons addSubview:label2];
        

        
        float marginWeight = [[tempArrayResultsAllMargins objectAtIndex:p-1] floatValue];
        
        //NSLog(@"tempArrayResultsAllMargins %@", tempArrayResultsAllMargins);
        
        
        if (marginWeight != -9999) { 
            
        
            float maxLineWidth = buttonWidth * 0.8;              
            //float greenLineWidth = (buttonWidth * 0.8) * (marginPercent/100);              
            UIBezierPath *path = [UIBezierPath bezierPath];
            [path moveToPoint:CGPointMake( (buttonCounter * buttonWidth) -  buttonWidth + (buttonWidth * 0.1), yCoord + 66 )];
            [path addLineToPoint:CGPointMake( (buttonCounter * buttonWidth) -  buttonWidth + (buttonWidth * 0.1) + maxLineWidth , yCoord + 66  )  ];
            CAShapeLayer *shapeLayer = [CAShapeLayer layer];
            shapeLayer.path = [path CGPath];
            shapeLayer.strokeColor = [[UIColor orangeColor] CGColor];
            shapeLayer.lineWidth = 20;
            shapeLayer.fillColor = [[UIColor clearColor] CGColor];       
            [_viewUniversalButtons.layer addSublayer:shapeLayer];
                 
            // draw margin line
            path = [UIBezierPath bezierPath];
            [path moveToPoint:CGPointMake( (buttonCounter * buttonWidth) -  buttonWidth + (buttonWidth * 0.1), yCoord + 66 )];
            [path addLineToPoint:CGPointMake( (buttonCounter * buttonWidth) -  buttonWidth + (buttonWidth * 0.1) + maxLineWidth , yCoord + 66  )  ];
            shapeLayer = [CAShapeLayer layer];
            shapeLayer.path = [path CGPath];
            
            
            if (marginWeight <0 ) {
                shapeLayer.strokeColor = [[UIColor orangeColor] CGColor];
            }else if (marginWeight <40 ) {
                 shapeLayer.strokeColor = [[UIColor yellowColor] CGColor];
            }else{
                shapeLayer.strokeColor = [[UIColor greenColor] CGColor];
                
            }
            shapeLayer.lineWidth = 20;
            shapeLayer.fillColor = [[UIColor clearColor] CGColor];       
            [_viewUniversalButtons.layer addSublayer:shapeLayer];
            
            UILabel *label3 = [[UILabel alloc] init];
            label3.frame     = CGRectMake( (buttonCounter * buttonWidth) -  buttonWidth , yCoord + 55, buttonWidth, 21 );
            [label3 setFont:[UIFont systemFontOfSize:15]];
            label3.textColor = [UIColor blackColor];
            label3.textAlignment = NSTextAlignmentCenter;       
            label3.tag = p+2000;
            [label3 setText:@"-"]; // weight margin
            [_viewUniversalButtons addSubview:label3];
        
            
        }else{
         
            float maxLineWidth = buttonWidth * 0.8;        
            // draw margin line
            UIBezierPath *path = [UIBezierPath bezierPath];
            [path moveToPoint:CGPointMake( (buttonCounter * buttonWidth) -  buttonWidth + (buttonWidth * 0.1), yCoord + 66 )];
            [path addLineToPoint:CGPointMake( (buttonCounter * buttonWidth) -  buttonWidth + (buttonWidth * 0.1) + maxLineWidth , yCoord + 66  )  ];
            CAShapeLayer *shapeLayer = [CAShapeLayer layer];
            shapeLayer.path = [path CGPath];
            shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];
            shapeLayer.lineWidth = 20;
            shapeLayer.fillColor = [[UIColor clearColor] CGColor];       
            [_viewUniversalButtons.layer addSublayer:shapeLayer];           
            
            UILabel *label3 = [[UILabel alloc] init];
            label3.frame     = CGRectMake( (buttonCounter * buttonWidth) -  buttonWidth , yCoord + 55, buttonWidth, 21 );
            [label3 setFont:[UIFont systemFontOfSize:15]];
            label3.textColor = [UIColor blackColor];
            label3.textAlignment = NSTextAlignmentCenter;       
            label3.tag = p+3000;
            [label3 setText:@"N/A"]; // weight margin
            [_viewUniversalButtons addSubview:label3];
          
        }

        
    }
    

    
    return;
    
}



- (IBAction)actionTrianglePerfButtons:(id)sender {
    
    if (_segmentFlightLegMode.selectedSegmentIndex == 1) {
        return;
    }
    
    if (flagPerfBoxOn == 0) {
        flagPerfBoxOn = 1;
         //NSLog(@"actionTrianglePerfButtons addPerfBox ");
        [self addPerfBox];
        [self displayWindows];
       
    }else{
        flagPerfBoxOn = 0;
        [self addPerformanceButtons];
        [self displayWindows];
    }
    [self MainRoutine];
}








- (IBAction)buttonActionChangeServer:(id)sender {
    
    if (_viewSelectServer.hidden == YES) {
        _viewSelectServer.hidden = NO; [viewSetup bringSubviewToFront:_viewSelectServer];
    }else{
        
      _viewSelectServer.hidden = YES;
    }
    
    
}



- (IBAction)buttonActionSelectServer:(id)sender {
    
    UIButton *btn = (UIButton*)sender;
    
    if (btn.tag == 1) {
        
        // set Standard Server
        
        _labelServer.text =@"Standard Server";
        
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        
        [defaults  setObject: _labelServer.text                     forKey:@"_labelServer"];
        
        
        serverpath      = serverpath_standard;
        serverpath_new  = serverpath_new_standard;
        serverhost      = serverhost_standard;
        
        [self MainRoutine];
        
        
    }
    
    
    if (btn.tag == 2) {
        
        // set Alternate Server
        
        _labelServer.text =@"Alternate Server";
        
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        
        [defaults  setObject: _labelServer.text                     forKey:@"_labelServer"];
        
        serverpath      = serverpath_alternate;
        serverpath_new  = serverpath_alternate;
        serverhost      = serverhost_alternate;
        
        [self MainRoutine];
        
        
        
    }
    
    
    
    
    if (btn.tag == 3) {
        
     
        _viewSelectServer.hidden = YES;
        
        [self MainRoutine];
        
    }
    
    
    
}







- (void) createConfigViewItemList {
    
    
    
    
}

- (IBAction)closeKeyboardEditStations:(id)sender {
    
    
     [self.view endEditing:TRUE];
    
    
    float enterValue = [_inputFuelOnBoard.text floatValue];
    
    
    if ([fuelEnterMode isEqualToString:@"mass"]) {
        
        if (enterValue > tankCapacityVolume * [_inputSpecificFuelMassPerVolume.text floatValue] ) {
            enterValue = tankCapacityVolume * [_inputSpecificFuelMassPerVolume.text floatValue];
        }
        
        _sliderFuelMain1.value =  enterValue / [_inputSpecificFuelMassPerVolume.text floatValue];
        
        
    }else{
        
        if (enterValue > tankCapacityVolume) {
            enterValue = tankCapacityVolume;
        }
        
        _sliderFuelMain1.value =  enterValue;
        
    }
    
    
    [self MainRoutine];
    
    [self MainRoutine];
    
    
    
   
    
    
}



- (void)actionItemInOut:(UIButton*)sender {



    //UIButton *perfButton = (UIButton *)sender;



    float itemNr = sender.tag;
    
    //NSLog (@"itemNr %@ ", [ [NSString alloc] initWithFormat:@"%.0f ", itemNr]);
    
    
    if  ([[_arrayName8 objectAtIndex: itemNr-100 ] doubleValue] >= 1) {
        
        
         [_arrayName8 replaceObjectAtIndex:itemNr-100 withObject: @"0"  ];
        
        [self createListoItemsSlidersAndInterior];
        
        [self createConfigViewItemList];
        
        
        
        
    }else{
        
        [_arrayName8 replaceObjectAtIndex:itemNr-100 withObject: @"1"  ];
        
        [self createListoItemsSlidersAndInterior];
        
        [self createConfigViewItemList];
        
        
        
        
    }

    
    
    


    //[_arrayName5 replaceObjectAtIndex:tag-1600 withObject: [ [NSString alloc] initWithFormat:@"%.1f", LatArm  ] ];


}



- (void)actionConnectorOnOff:(UIButton*)sender {
    
    
    
    //UIButton *perfButton = (UIButton *)sender;
    
    
    
    float itemNr = sender.tag;
    
    //NSLog (@"itemNr %@ ", [ [NSString alloc] initWithFormat:@"%.0f ", itemNr]);
    
    
    if  ([[_arrayName16 objectAtIndex: itemNr-0 ] doubleValue] >= 1) {
        
        
        [_arrayName16 replaceObjectAtIndex:itemNr-0 withObject: @"0"  ];
        
        [self createListoItemsSlidersAndInterior];
        
        [self createConfigViewItemList];
        
        
        
        
    }else{
        
        [_arrayName16 replaceObjectAtIndex:itemNr-0 withObject: @"1"  ];
        
        [self createListoItemsSlidersAndInterior];
        
        [self createConfigViewItemList];
        
        
        
        
    }
    
    
    
    
    
    
    //[_arrayName5 replaceObjectAtIndex:tag-1600 withObject: [ [NSString alloc] initWithFormat:@"%.1f", LatArm  ] ];
    
    
}





// **************************************************************************************************************************************************************************
// *************************************************************************************************************************************************************************
// *************************************************************************************************************************************************************************
// *************************************************************************************************************************************************************************


- (void) makeConfigButtons {
    
    NSMutableArray *arrayConfigButtonsRegistration   = [[NSMutableArray alloc] init];
    
    for(UIView *subview in [_viewConfigButtons subviews]) {
        [subview removeFromSuperview];
    }
    // load array with configurations
    [arrayConfigurations setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"arrayConfigurations%@", AC_Type] ] mutableCopy]];
    [arrayConfigButtons setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"arrayConfigButtons%@", AC_Type] ] mutableCopy]];
    [arrayConfigButtonsRegistration setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"arrayConfigButtonsRegistration%@", AC_Type] ] mutableCopy]];
     //NSLog(@"5 kill");
    //NSLog (@"makeConfigButtons  %@" , arrayConfigurations );
    
    
    int buttonTag = 1;
    for (int i = 1; i < arrayConfigButtons.count  ; i++) {
        //NSLog (@"buttonTag  %d" , buttonTag );
        // check if the configuration is for the selected ACregistration
        if (![[arrayConfigButtonsRegistration objectAtIndex:i] isEqualToString:vFlightRegistration.text]) {
            //NSLog (@"continue at buttonTag  %d" , buttonTag );
            if ([[arrayConfigButtonsRegistration objectAtIndex:i] isEqualToString:@"noReg"]) {
            }else{
                continue;
            }
        }
      
        
        // make button
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(15, 5 + ((buttonTag-1) * 60) , 340, 57);
        
        [btn addTarget:self
                action:@selector(actionSetConfiguration:)
         forControlEvents:UIControlEventTouchUpInside];        
        
        // name the button
        btn.tag = i ;
        btn.backgroundColor = [UIColor clearColor];
        btn.hidden = NO;
        [btn  setBackgroundImage:[UIImage imageNamed: @"button generic dark.png"] forState:UIControlStateNormal];        
        
        NSString *configNameSaved = [arrayConfigurations objectAtIndex: i  ] ; // get actual config name
        [btn setTitle:configNameSaved forState:UIControlStateNormal];
        int savedConfigNumber = [[arrayConfigButtons objectAtIndex: i  ] doubleValue]; // get actual confi number saved
        //NSLog (@"savedConfigNumber  %d" , savedConfigNumber );
        //NSLog(@"tag title   %d  - %@" , i ,configNameSaved );
        if (configuration == savedConfigNumber) {
            [btn  setBackgroundImage:[UIImage imageNamed: @"button generic blue.png"] forState:UIControlStateNormal];
        }
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];        
        [_viewConfigButtons addSubview:btn];        
        buttonTag = buttonTag +1;
    }
    
 
    _viewConfigButtons.frame = CGRectMake(_viewConfigButtons.frame.origin.x, 80, _viewConfigButtons.frame.size.width, (buttonTag - 1) * 63);
    _viewSelectOptions.frame = CGRectMake(_viewSelectOptions.frame.origin.x, _viewConfigButtons.frame.origin.y + _viewConfigButtons.frame.size.height +50, _viewSelectOptions.frame.size.width, _viewSelectOptions.frame.size.height);
    
    
    float scViewHeight =  _viewSelectOptions.frame.origin.y + (numberOfSwitches * 50) + 200 ;
    //NSLog( @"scViewHeight %.0f ",scViewHeight );
    [_scrollViewConfigurations setContentSize:CGSizeMake(377,  scViewHeight)];
    
    
    return;
    
}

- (void) actionSetConfiguration :(UIButton*)sender {
    
    //NSLog(@"actionSetConfiguration");
    
   
    
    arrayCustomStations = [[NSMutableArray alloc] init]; 
    NSString *internalFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];    
    arrayCustomStations = [[[NSUserDefaults standardUserDefaults] objectForKey:[[NSString alloc] initWithFormat:@"%@%@", internalFlightID, @"arrayCustomStations" ]] mutableCopy];  
    //NSLog(@"arrayCustomStations.count %lu", arrayCustomStations.count);
    
    if (arrayCustomStations.count >= 1) {
        
        activeConfigButton = sender.tag;    
        alertFlag = 2000;
        
        UIAlertView *alert = [[UIAlertView alloc]
                              
                              initWithTitle:@"Reset Custom Stations?"                              
                              message:@"You have created custom stations for this configuration. All custom stations will be deleted when you re-load or change the configuration. "
                              delegate:self                              
                              cancelButtonTitle:@"CANCEL"                              
                              otherButtonTitles:@"RESET STATIONS", nil];        
        [alert show];
        
    }else{
        
        flagUsingAlternateEquipment = 0;    
        flagLoadConfigDataForButton= 1;    
        //NSLog(@"old configuration  %d" , configuration);    
        activeConfigButton = sender.tag;    
        configuration = activeConfigButton;    
        [self setConfiguration];
        [self retainCrewNames];    
        [self searchbutSelHeli];   
        [self loadDefaultEquipmentArrays]; 
        [self createSpecialEquipListItems];
        [self makeConfigButtons];
        [self MainRoutine];  
        
    }
    
    if (flagReopenFlightSettings == 1) {
        _viewLegData.hidden = NO;
    }
    
    if (flagSpecialPHIFlightSettingPage == 1) {
        [self SaveValues];
    }
     
}





- (void) setDefaultsForConfig {
    
    // do this only when load array listo to create a new config
    flagSettingDefaults = 1;
    //NSLog(@"setDefaultsForConfig _arrayName21 %@", _arrayName21);
    
    //NSLog(@"setDefaultsForConfig ------------");
    
    flagOverwriteOptionsDefault = 1;
    
    ///NSLog(@"previousOriginalWeightUnits1 %@", previousOriginalWeightUnits);
    //NSLog(@"[_arrayName21 objectAtIndex:5] %@", [_arrayName21 objectAtIndex:5]); // excel Weight Units
    //NSLog(@"[_arrayName21 objectAtIndex:15] %@", [_arrayName21 objectAtIndex:15]); //Fuel Units
   
    //NSLog(@"specialdata2 %@", specialdata2);
    
   
      
    
    
    int flagLoadUnits = 0;    
    if (![previousOriginalWeightUnits isEqualToString: [_arrayName21 objectAtIndex:5]]) {
        flagLoadUnits = 1;
    }
    if (![previousOriginalFuelUnits isEqualToString: [_arrayName21 objectAtIndex:15]]) {
        flagLoadUnits = 1;
    }
   
    
    NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"]; 
    if (dedicatedCustomerData.length < 2) {
        dedicatedCustomerData = @"";
    }
    if ([dedicatedCustomerData rangeOfString:@"weight"].location != NSNotFound  ) {
        //NSLog(@"Customer (UHI!) wants weight instead of mass");
        _labelMassOnCGValues.text = @"Weight";
    }else{
        _labelMassOnCGValues.text = @"Mass";
    } 
    
   
    [tempArraySeatWgt removeAllObjects];
    [tempArraySeatName removeAllObjects];
    
   
    _segmentFlightLegMode.selectedSegmentIndex = 0;
    if ( [[_arrayName21 objectAtIndex:49] isEqualToString:@"LegMode"]) {
        _segmentFlightLegMode.selectedSegmentIndex = 1;
    }
   
    
    if ([vFlightID floatValue] <= 1 || flagLoadUnits == 1) {
        //NSLog(@"1 meep"); 
        
        // fuel defaults
        fuelUnits = [_arrayName21 objectAtIndex:15 ];
        tankCapacityVolume = [[_arrayName21 objectAtIndex: 17 ] floatValue];
        
        //NSLog(@"1 meep tankCapacityVolume %.2f", tankCapacityVolume);         
        _sliderFuelMain1.maximumValue = tankCapacityVolume;
        _sliderFuelLanding.maximumValue = tankCapacityVolume - (tankCapacityVolume * 0.05);        
        inputFuelFlowOverride.text = [_arrayName21 objectAtIndex: 27 ];
        
        unitsWeight.text = [_arrayName21 objectAtIndex: 5  ];
        selectedUnitForItems = unitsWeight.text;
        selectedUnitForFuel = unitsWeight.text;
        _inputQuickLoadPreset.text = [_arrayName21 objectAtIndex: 33 ];
        
        if ([fuelUnits isEqualToString:@"lbs"]) {
            _inputSpecificFuelMassPerVolume.text = [_arrayName21 objectAtIndex:20 ] ; // lbs/gal             
        }else{
            _inputSpecificFuelMassPerVolume.text = [_arrayName21 objectAtIndex:22 ] ; // kg/ltr           
        }
        
        if ([[_arrayName21 objectAtIndex:24] isEqualToString:@"volume"] ) {
            _segmentFuelVolumeOrMass.selectedSegmentIndex = 0;
            fuelEnterMode = @"volume";   
          
        }else{
            _segmentFuelVolumeOrMass.selectedSegmentIndex = 1;
            fuelEnterMode = @"mass";  
        }
        
        //NSLog(@"selectedUnitForItems %@", selectedUnitForItems); 
        
    }else{
        //NSLog(@"2 meep");
         inputFuelFlowOverride.text = [NSString stringWithFormat:@"%.1f", [[_arrayName21 objectAtIndex: 27 ]floatValue]  ]; 
        
        if ([[_arrayName21 objectAtIndex:24] isEqualToString:@"volume"] && [fuelEnterMode isEqualToString:@"mass"]) {            
            //NSLog(@"convert vol to mass");            
            inputFuelFlowOverride.text = [NSString stringWithFormat:@"%.2f", [[_arrayName21 objectAtIndex: 27 ]floatValue] * [_inputSpecificFuelMassPerVolume.text floatValue] ]; 
        }        
        if ([[_arrayName21 objectAtIndex:24] isEqualToString:@"mass"] && [fuelEnterMode isEqualToString:@"volume"]) {            
            //NSLog(@"convert mass to vol");
             inputFuelFlowOverride.text = [NSString stringWithFormat:@"%.2f", [[_arrayName21 objectAtIndex: 27 ]floatValue] / [_inputSpecificFuelMassPerVolume.text floatValue] ]; 
        }
        
    }
    
    
    
    
    
    
    if (_vFuelPresetField.text.length > 0) {      
        float fuelPresetVolume = 0;
        
        fuelPresetVolume = [_vFuelPresetField.text floatValue];
        
         if ([[_arrayName25 objectAtIndex:31 ] rangeOfString:@"kg"].location != NSNotFound || [[_arrayName25 objectAtIndex:31 ] rangeOfString:@"lbs"].location != NSNotFound  ) {
             //we need to convert kg to liter
             fuelPresetVolume = [_vFuelPresetField.text floatValue] / [_inputSpecificFuelMassPerVolume.text floatValue];
         }        
        //NSLog(@"setting fuelPresetVolume %.0f", fuelPresetVolume);
        //if subtract supply fuel
        if ([[_arrayName25 objectAtIndex:21 ] isEqualToString:@"yes"]) {
             //NSLog(@"adding supply fuel volume  %.0f", [[_arrayName25 objectAtIndex:19 ] floatValue] );
            fuelPresetVolume = fuelPresetVolume +  [[_arrayName25 objectAtIndex:19 ] floatValue];
        }        
        //NSLog(@"final fuelPresetVolume %.0f", fuelPresetVolume);
        
        _sliderFuelMain1.value = fuelPresetVolume;
        
        
        
    }else{       
        _sliderFuelMain1.value = [[_arrayName21 objectAtIndex:29 ] floatValue]; 
        
        //NSLog(@"_arrayName21 %@", _arrayName21);
        //NSLog(@"setting _sliderFuelMain1.value %.0f", _sliderFuelMain1.value);
    }
    
    
    _sliderFuelLanding.value = [[_arrayName21 objectAtIndex:31 ] floatValue];
    linePilot = [[_arrayName23 objectAtIndex: 27 ] intValue];
    
    _segmentPlanMode.selectedSegmentIndex = 1;
    
    if ([[_arrayName21 objectAtIndex:41 ] isEqualToString:@"off"]) {
        _segmentSwapMode.selectedSegmentIndex = 0;
    }else{
        _segmentSwapMode.selectedSegmentIndex = 1;
    }
    
   
    
    if ([[_arrayName21 objectAtIndex:43 ] isEqualToString:@"q"]) {
        _segmentSeatLoadOptions.selectedSegmentIndex = 0;
    }else{    
        _segmentSeatLoadOptions.selectedSegmentIndex = 1;
    }
    if ([dedicatedCustomerData rangeOfString:@"openCrewListOnSeatTap"].location != NSNotFound  ) {        
        _segmentSeatLoadOptions.selectedSegmentIndex = 1;          
        
    }
    
    
    if ([[_arrayName21 objectAtIndex:45 ] isEqualToString:@"ID"]) {
        _segmentNamesOnSeats.selectedSegmentIndex = 0;
    }
    if ([[_arrayName21 objectAtIndex:45 ] isEqualToString:@"WID"]) {
        _segmentNamesOnSeats.selectedSegmentIndex = 1;
    }
    if ([[_arrayName21 objectAtIndex:45 ] isEqualToString:@"WN"]) {
        _segmentNamesOnSeats.selectedSegmentIndex = 2;
    }
    
    if ([[_arrayName23 objectAtIndex:34 ] isEqualToString:@"off"]) {
        _segmentCGAutoCheck.selectedSegmentIndex = 0;
    }else{
        _segmentCGAutoCheck.selectedSegmentIndex = 1;
    }
    
    //NSLog(@"resetting custom station");
    NSString *internalFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];   
    arrayCustomStations = [[NSMutableArray alloc] init]; 
    [arrayCustomStations removeAllObjects];
    [[NSUserDefaults standardUserDefaults]  setObject: arrayCustomStations  forKey:[ [NSString alloc] initWithFormat:@"%@%@", internalFlightID, @"arrayCustomStations" ]];
    
 
    
}








- (void) loadFuelTankSettings {
    
    //NSLog(@"loadFuelTankSettings ");    
    _sliderFuelMain1.value = [[legSettingsDictionary objectForKey: @"_sliderFuelMain1"] floatValue];
    _sliderFuelLanding.value = [[legSettingsDictionary objectForKey: @"_sliderFuelLanding"] floatValue];
    //NSLog(@"loading _sliderFuelMain1.value %.0f", [[legSettingsDictionary objectForKey: @"_sliderFuelMain1"] floatValue]);
    fuelUnits = [_arrayName21 objectAtIndex:15 ];
    tankCapacityVolume = [[_arrayName21 objectAtIndex:17 ] floatValue];
    _sliderFuelMain1.maximumValue = tankCapacityVolume;
    _sliderFuelLanding.maximumValue = tankCapacityVolume - (tankCapacityVolume * 0.05);
   //NSLog(@"loadFuelTankSettings tankCapacityVolume %.f", tankCapacityVolume); 
}

- (void) setOptionalButtons {
    
    //NSLog(@"setOptionalButtons");
    
    
    if ([[_arrayName25 objectAtIndex:39] isEqualToString:@"ISA"]) {
        OATinput =1;  
        viewSliderISA.hidden = NO;
        [self iEnviCalcALL];
    }
    
    if ([[_arrayName25 objectAtIndex:39 ] isEqualToString:@"OAT"]) {
        OATinput =0;
        viewSliderISA.hidden = YES;
        [self iEnviCalcALL];
    }
    
    if ([[_arrayName23 objectAtIndex:15 ] isEqualToString:@"yes"] ) {
        _optionalButtonExportLoadManifestAsPDF.hidden = NO;
    }else{
        _optionalButtonExportLoadManifestAsPDF.hidden = YES;
        
    }
    
    if ( [[_arrayName23 objectAtIndex:17 ] isEqualToString:@"yes"]) {
        _optionalButtonExportSummaryAsPDF.hidden = NO;
    }else{
        _optionalButtonExportSummaryAsPDF.hidden = YES;
        
    }

    
    // risk assessment
    if ([[_arrayName25 objectAtIndex:7] isEqualToString:@"yes"] ) {
        _displayButtonRiskAssessment.hidden = NO;
        _displayButtonRiskAssessment.frame = CGRectMake(504, -1, 65, 52);         
        
    }else if ([[_arrayName25 objectAtIndex:7] isEqualToString:@"OCC"] ) {
        _displayButtonRiskAssessment.hidden = NO;
        _displayButtonRiskAssessment.frame = CGRectMake(504, -1, 65, 52);         
        
    }else if ([[_arrayName25 objectAtIndex:7] floatValue] > 10 ) {
        
        _displayButtonRiskAssessment.hidden = NO;
        _displayButtonRiskAssessment.frame = CGRectMake([[_arrayName25 objectAtIndex:7] floatValue], -1, 65, 52);    
            
        }else{            
            _displayButtonRiskAssessment.hidden = YES;
   }
      
    
    
    
    if ( [[_arrayName25 objectAtIndex:9] isEqualToString:@"yes"] ) {
        _displayButtonDocumentViewer.hidden = NO;
        _displayButtonDocumentViewer.frame = CGRectMake(504, -1, 65, 52); 
        
        }else if ([[_arrayName25 objectAtIndex:9] floatValue] > 10 ) {
             
             _displayButtonDocumentViewer.hidden = NO;
             _displayButtonDocumentViewer.frame = CGRectMake([[_arrayName25 objectAtIndex:9] floatValue], -1, 65, 52);    
                 
             }else{            
                 _displayButtonDocumentViewer.hidden = YES;
        }
    
    
    
    // this is the detailed station setup 'Setup Station Data'
    _buttonShowInteriorConfiguratorPage.hidden = YES;
    if ([[_arrayName25 objectAtIndex:11] isEqualToString:@"yes"]  ) {
         _buttonShowInteriorConfiguratorPage.hidden = NO;
        
    }
    
    
    _optionalButtonEditConfigurations.hidden = YES;
    if ( [[_arrayName23 objectAtIndex:19] isEqualToString:@"yes"] ) {
        _optionalButtonEditConfigurations.hidden = NO;
        
    }
    
    _buttonOpenCustomStations.hidden = YES;
    NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"]; 
    //NSLog (@"customerFolderName %@", customerFolderName);

    if ([customerFolderName isEqualToString:@"noAccount"] || [customerFolderName isEqualToString:@"Tester"]) {         
        _buttonOpenCustomStations.hidden = NO;
        _optionalButtonEditConfigurations.hidden = NO;
    }
    
    NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
    if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
    //NSLog(@"startup fetchAvailableProducts  userExtraCheck %@", userExtraCheck);       
    
    if ([userExtraCheck rangeOfString:@"allowCustomStations"].location != NSNotFound  ) {  
        _buttonOpenCustomStations.hidden = NO;
        _optionalButtonEditConfigurations.hidden = NO;
    
    }
    
     [_optionalButtonEditConfigurations setTitle:@"Edit Configuration"  forState:UIControlStateNormal];  
    
    if ([userExtraCheck rangeOfString:@"allowCustomStationsButNotEditConfig"].location != NSNotFound  ) {  
        _buttonOpenCustomStations.hidden = YES;
        _optionalButtonEditConfigurations.hidden = NO;        
        [_optionalButtonEditConfigurations setTitle:@"Custom Stations"  forState:UIControlStateNormal];  
        
    }
    
    
    
    //allowCustomStations extra 7
    if ( [[_arrayName25 objectAtIndex:47] isEqualToString:@"yes"] ) {
        _buttonOpenCustomStations.hidden = NO;
        
    }
    
   
    
    
    _viewFuelUnitButtons.hidden = NO;
    if ( [[_arrayName21 objectAtIndex:25] isEqualToString:@"no"] ) {
        _viewFuelUnitButtons.hidden = YES;
        //NSLog(@"hide unit button!!!");
    }
    
    
   

    // allow to select various equipment lists
    
    _viewPHIEquipmentListSelection.hidden = YES;
    
    if ( [[_arrayName23 objectAtIndex:32] isEqualToString:@"yes"]) {        
        if (flagSpecialPHIFlightSettingPage == 1) {
            _viewSelectEquipmentFromOtherConfigs.hidden = YES;
            _viewPHIEquipmentListSelection.hidden = NO;       
        }else{            
            _viewSelectEquipmentFromOtherConfigs.hidden = NO;
        }        
    }else{
        _viewSelectEquipmentFromOtherConfigs.hidden = YES;
      
    }
    
    
    NSArray *componentItems = [[NSArray alloc] init];
    componentItems  = [[_arrayName25 objectAtIndex:17] componentsSeparatedByString:@"_"];
    //NSLog(@"componentItems %@", componentItems);
    //NSLog(@"1 _vFlightTypeField.text -%@-", _vFlightTypeField.text);
    
    
    if (componentItems.count > 1) {
        _vFlightTypeField.items   = componentItems;
        if ([_vFlightTypeField.text isEqualToString:@""]) {
            _vFlightTypeField.text = [componentItems objectAtIndex:0];
        }
    }else{        
        _vFlightTypeField.items   =  @[ @"VFR Day", @"VFR Night", @"IFR"];
        if ([_vFlightTypeField.text isEqualToString:@""]) {
            _vFlightTypeField.text = @"VFR Day";
        }
    }
    
    
    
    
    
  //NSLog(@"2 _vFlightTypeField.text %@", _vFlightTypeField.text);
    componentItems  = [[_arrayName25 objectAtIndex:31] componentsSeparatedByString:@"_"];    
    if (componentItems.count > 1) {
        _vFuelPresetField.items   = componentItems;
    }else{        
        _vFuelPresetField.items   =  [_arrayName21 objectAtIndex:29];
    }
    
    
  
    
    if ([_vFuelPresetField.text isEqualToString:@""]) {
        _vFuelPresetField.text = [componentItems objectAtIndex:0];
    }
    

    if ([customerFolderName isEqualToString:@"noAccount"] ) { 
        _switchAutoLandingFuel.on = NO;
    } 
    
    if ([[_arrayName25 objectAtIndex:33] isEqualToString:@"on"]) {
        _switchAutoLandingFuel.on = YES;       
    }
    if ([[_arrayName25 objectAtIndex:33] isEqualToString:@"off"] || [[_arrayName25 objectAtIndex:33] isEqualToString:@""]) {
        _switchAutoLandingFuel.on = NO;       
    }
   
    
    
}

- (void) setItemsFlightLegData  {
    
    //NSLog(@"setItemsFlightLegData _arrayName1 %@", _arrayName1);
    
    
    
    //Flight Data Elements
    
    for(UIView *subview in [_viewCustomFlightDataElements subviews]) {
        [subview removeFromSuperview];
    }
    
    itemsGuidance = [[NSArray alloc] init];
    NSArray *componentItems = [[NSArray alloc] init];
    //NSLog(@"_arrayName1  %@", _arrayName1 );
    int flagThisIsNewVersion = 0;
    
    NSArray *itemsOnOff = [[NSArray alloc] init];
    NSArray *itemsCellHeight = [[NSArray alloc] init];
    NSArray *itemsPreset = [[NSArray alloc] init];
    NSArray *itemsHeadline = [[NSArray alloc] init];
    NSArray *itemsTextOrNumberfield = [[NSArray alloc] init];
    NSArray *itemsYpos = [[NSArray alloc] init];
    
    NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];    
    if ([customerFolderName isEqualToString:@"Tester"]   ) { 
        [_arrayName23 replaceObjectAtIndex:40 withObject:@"standard"];        
    }
  
    if ([[_arrayName23 objectAtIndex:40] isEqualToString:@"standard"] || [[_arrayName23 objectAtIndex:40] isEqualToString:@""] || [[_arrayName23 objectAtIndex:40] isEqualToString:@"Standard"]  ) {
        //NSLog(@"using standard component items");
        NSString *standardElements = @"1_0_0_0_0_0_0_1_1_0_1_1_0_0_0_0x60_60_60_60_60_60_60_60_60_90_60_60_60_60_60_60x1_1_0_0_0_0_1_1_1_0_0_0_0_0_0_0";        
        componentItems  = [standardElements componentsSeparatedByString:@"x"]; 
        itemsOnOff = [[componentItems objectAtIndex:0] componentsSeparatedByString:@"_"];   
        itemsCellHeight = [[componentItems objectAtIndex:1] componentsSeparatedByString:@"_"];
        itemsGuidance  = [[componentItems objectAtIndex:2] componentsSeparatedByString:@"_"];    
        
    }else{  
        
       if ([[_arrayName23 objectAtIndex:40] rangeOfString:@"newVersion"].location != NSNotFound ) {
           //NSLog(@"using newVersion");
           flagThisIsNewVersion = 1;
           componentItems  = [[_arrayName23 objectAtIndex:40] componentsSeparatedByString:@";"];
           itemsOnOff = [[componentItems objectAtIndex:1] componentsSeparatedByString:@"_"];   
           itemsYpos = [[componentItems objectAtIndex:2] componentsSeparatedByString:@"_"];
           itemsGuidance  = [[componentItems objectAtIndex:3] componentsSeparatedByString:@"_"];           
           
           itemsPreset = [[componentItems objectAtIndex:4] componentsSeparatedByString:@"_"];
           itemsHeadline = [[componentItems objectAtIndex:5] componentsSeparatedByString:@"_"];
           itemsTextOrNumberfield = [[componentItems objectAtIndex:6] componentsSeparatedByString:@"_"];
                     
           
       }else{   
           //NSLog(@"using older Version");
           componentItems  = [[_arrayName23 objectAtIndex:40] componentsSeparatedByString:@"x"];   
           itemsOnOff = [[componentItems objectAtIndex:0] componentsSeparatedByString:@"_"];   
           itemsCellHeight = [[componentItems objectAtIndex:1] componentsSeparatedByString:@"_"];
           itemsGuidance  = [[componentItems objectAtIndex:2] componentsSeparatedByString:@"_"];           
       }
       
    }
    
    //NSLog(@"componentItems %@", componentItems);   
    //NSLog(@"componentItems.count %lu", componentItems.count);
    //NSLog(@"componentItems %@", componentItems);
    
    float yPosFrame = 50;
   
    if (flagThisIsNewVersion == 1) {        
        _viewCustomFlightDataElements.frame = CGRectMake(0, 0, _viewLegDataItems.frame.size.width, _viewLegDataItems.frame.size.height);      
        
        float highestYPos = 0;
        // achtung !! wenn du ein item einfügst dann alle von 17 auf 18 setzten usw suche: arrayCustomFlightDataElements
        for (int i = 0; i<17; i++) { 
            //NSLog(@"itemsHeadline %d %@", i, [itemsHeadline objectAtIndex: i]);            
            UIView *viewElement = (UIButton*)[_viewLegDataItems viewWithTag: 10000 + i ];        
            if ([[itemsOnOff objectAtIndex:i] floatValue] > 0) {
                if (i==0) {
                    _labelFlightIDOnSettings.text = [itemsHeadline objectAtIndex: i]; 
                }  
                if (i==10) {
                    _labelFlightTypeOnSettings.text = [itemsHeadline objectAtIndex: i]; 
                }
                if (flagJustResettedFlightSettings == 1) {
                    flagJustResettedFlightSettings = 0;
                    //NSLog(@"doing presets itemsPreset ");
                    //do presets
                                   if (i==0  ) {
                                       _vFlightIDName.text = [itemsPreset objectAtIndex: i]; 
                                   } 
                                   if (i==7 ) {
                                       vFlightDeparture.text = [itemsPreset objectAtIndex: i]; 
                                   }
                                   
                                   if (i==11 ) {
                                       _vFlightRemarks.text = [itemsPreset objectAtIndex: i]; 
                                   }
                }
               
                if (i==13) {
                    _vHeadlineRIN.hidden = YES;
                    _vHeadlineEngine2.hidden = YES;
                    _vEngineStarts2.hidden = YES;
                    _vRIN.hidden = YES;
                    
                    if ( [[itemsOnOff objectAtIndex:i] floatValue] == 2) {
                        _vHeadlineEngine2.hidden = NO;
                        _vEngineStarts2.hidden = NO;
                    }                    
                    if ( [[itemsOnOff objectAtIndex:i] floatValue] == 3) {
                        _vHeadlineRIN.hidden = NO;
                        _vRIN.hidden = NO;                       
                    }
                    if ( [[itemsOnOff objectAtIndex:i] floatValue] == 4) {
                        _vHeadlineEngine2.hidden = NO;
                        _vEngineStarts2.hidden = NO;
                        _vHeadlineRIN.hidden = NO;
                        _vRIN.hidden = NO;
                    }  
                }
                viewElement.hidden = NO; 
                yPosFrame = [[itemsYpos objectAtIndex: i]floatValue];
                if (yPosFrame > highestYPos) {
                    highestYPos = yPosFrame;
                }
                viewElement.center = CGPointMake( viewElement.center.x ,  yPosFrame + 50);                
                
            }else{
                viewElement.hidden = YES;
            }
        }    
        // now create custom elements       
       for (int i = 17; i<itemsOnOff.count; i++) { 
        
           if ([[itemsOnOff objectAtIndex:i] isEqualToString:@"1"]) {
               yPosFrame = [[itemsYpos objectAtIndex: i]floatValue];  
               if (yPosFrame > highestYPos) {
                   highestYPos = yPosFrame;
               }
               UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(23, yPosFrame + 21, 220 , 22) ];
               label.font = [UIFont systemFontOfSize:15];
               label.textAlignment = NSTextAlignmentLeft;
               label.textColor = [UIColor whiteColor];              
               [label  setText: [itemsHeadline objectAtIndex:i] ];
               [_viewCustomFlightDataElements addSubview:label];  
               UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(19 , yPosFrame + 45, 256, 31)];
               textField.borderStyle = UITextBorderStyleRoundedRect;             
               textField.font = [UIFont boldSystemFontOfSize:15];               
               textField.textAlignment = NSTextAlignmentLeft;           
               textField.backgroundColor = [UIColor lightGrayColor];
               textField.textColor = [UIColor blackColor];              
               textField.autocorrectionType = UITextAutocorrectionTypeNo;
               [textField addTarget:self
                             action:@selector(closeKeyboardLegData:)
                   forControlEvents:UIControlEventEditingDidEndOnExit];              
     
               //NSLog(@"i %d ", i);               
               //NSLog(@"itemsTextOrNumberfield %@", itemsPreset);
               
               
                //NSLog(@"arrayCustomFlightDataElements %@ ", arrayCustomFlightDataElements);
                //NSLog(@"arrayCustomFlightDataElements.count %lu ", arrayCustomFlightDataElements.count);
               
               
               if (arrayCustomFlightDataElements.count > 0) { 
                   if ([[arrayCustomFlightDataElements objectAtIndex:i-17] isEqualToString:@""]) {                      
                        [textField  setText: [itemsPreset objectAtIndex:i]];                      
                       //NSLog(@"setting preset %@", [itemsPreset objectAtIndex:i] );           
                   }else{                   
                        [textField  setText: [arrayCustomFlightDataElements objectAtIndex:i-17] ];
                       //NSLog(@"setting loaded %@", [arrayCustomFlightDataElements objectAtIndex:i-16] );     
                   }
               }
              
               textField.tag = i;              
               [textField addTarget:self action:@selector(moveScrollViewItemsFlightLegData:)  forControlEvents:UIControlEventEditingDidBegin];               
               if ([[itemsTextOrNumberfield objectAtIndex:i] isEqualToString:@"text"]) {                 
                   [textField setKeyboardType:UIKeyboardTypeDefault];
               }else{                  
                   [textField setKeyboardType:UIKeyboardTypeNumberPad];                   
               }               
               [_viewCustomFlightDataElements addSubview: textField];               
           }
       }        
        [_scrollViewLegData setContentSize:CGSizeMake(_viewLegData.frame.size.width, highestYPos + 600)];
        
    }else{
        //older Versions
        for (int i = 0; i<itemsOnOff.count; i++) {        
            UIView *viewElement = (UIButton*)[_viewLegDataItems viewWithTag: 10000 + i ]; 
            //NSLog(@"[itemsOnOff objectAtIndex:i] %@", [itemsOnOff objectAtIndex:i]);
            if ([[itemsOnOff objectAtIndex:i] isEqualToString:@"1"]) {
                viewElement.hidden = NO; 
                float CellHeight = [[itemsCellHeight objectAtIndex: i]floatValue];
                viewElement.center = CGPointMake( viewElement.center.x ,  yPosFrame);
                yPosFrame = yPosFrame + CellHeight/2;
                if (i < itemsOnOff.count - 1) {
                    float CellHeight = [[itemsCellHeight objectAtIndex: i+1]floatValue];
                    yPosFrame = yPosFrame + CellHeight/2;
                }
            }else{
                viewElement.hidden = YES;
            }
        }    
         [_scrollViewLegData setContentSize:CGSizeMake(_viewLegData.frame.size.width, yPosFrame + 600)];
    }
    
   
   
    
    
    
    
    
}

- (void) loadACimages {
    
    ACimagesDictionary = [[NSMutableDictionary alloc] init];
    ACimagesDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"ACimagesDictionary"] mutableCopy];    
    //NSLog(@"loadACimages AC_Type -%@-", AC_Type);   
    
    
    NSString *imageToLoad = [NSString stringWithFormat:@"image_%@_topViewOK", AC_Type ];
    //NSLog(@"loading imageToLoad %@", imageToLoad); 
    
    
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
     NSString *documentsDirectory = [paths objectAtIndex:0];
    
    //NSString *imageToLoad = [NSString stringWithFormat:@"%@_topViewOK.png", AC_Type ];
    
    if (![previousACImageToLoad isEqualToString:imageToLoad]) {
        //ACtopImage = [UIImage imageWithData:imageToLoad ];        
        //ACtopImage = [UIImage imageNamed:imageToLoad];                
        //UIImage * result = [UIImage imageWithContentsOfFile:imageToLoad];
        //ACtopImage = result;  
        
        
        NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:imageToLoad];
        UIImage *imageLoaded = [UIImage imageWithContentsOfFile:getImagePath];
        ACtopImage = imageLoaded;
        
        
        
        UIColor *color = [UIColor redColor];
        UIImage *image = ACtopImage;// Image to mask with
        UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [color setFill];
        CGContextTranslateCTM(context, 0, image.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextClipToMask(context, CGRectMake(0, 0, image.size.width, image.size.height), [image CGImage]);
        CGContextFillRect(context, CGRectMake(0, 0, image.size.width, image.size.height));    
        ACtop_WarningImage = UIGraphicsGetImageFromCurrentImageContext();    
        UIGraphicsEndImageContext();
        previousACTopViewState = -1;
    }
    
    
    previousACImageToLoad = imageToLoad;
    
    // set logoManifest
    imageToLoad = [NSString stringWithFormat:@"image_%@_logoManifest.png", AC_Type ];    
    
    //NSLog(@"imageToLoad -%@-", imageToLoad); 
        
    if ([previousImageToLoad isEqualToString:imageToLoad]) {
        return;
    }
    
    if ([[ACimagesDictionary objectForKey: imageToLoad]length]<1) {
        //NSLog(@"NOOOOOOO image is there");     
        UIImage *maniImage = [UIImage imageNamed: @"Gyronimo_logoManifest.png" ];
        [_logoManifest setImage:maniImage ];   
       
        if (_segmentFlightLegMode.selectedSegmentIndex != 0) {
            [_logoSummary setImage:maniImage ];
        }
               
    }else{
        //NSLog(@"image is there %@", imageToLoad);
        _logoManifest.frame = CGRectMake(0, 0, _logoManifest.frame.size.width * 2, _logoManifest.frame.size.height * 2);        
        _logoManifest.image = nil ;        
        [_logoManifest setImage: [UIImage imageWithData:[ACimagesDictionary objectForKey: imageToLoad] ]  ]; 
        CGRect rect = [_logoManifest bounds];
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [_logoManifest.layer renderInContext:context];
        UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
        _logoManifest.image = nil ; 
        UIGraphicsEndImageContext();      
        _logoManifest.image = img;       
        _logoManifest.frame = CGRectMake(0, 0, _logoManifest.frame.size.width / 2, _logoManifest.frame.size.height / 2);
        
         if (_segmentFlightLegMode.selectedSegmentIndex != 0) {   
        _logoSummary.image = nil ;        
        [_logoSummary setImage: [UIImage imageWithData:[ACimagesDictionary objectForKey: imageToLoad] ]  ];
         }
        
       
    }
    previousImageToLoad = imageToLoad;
       
}

- (void) loadFuelArrays {
    
    //NSLog(@"loadFuelArrays AC_Type %@", AC_Type);
    arrayFuelVolumeLONG = [[NSMutableArray alloc] init];
    arrayFuelMomentLONG = [[NSMutableArray alloc] init];    
    arrayFuelVolumeLAT = [[NSMutableArray alloc] init];
    arrayFuelMomentLAT = [[NSMutableArray alloc] init];    
    fuelInterpolationDictionary = [[NSMutableDictionary alloc] init];    
    arrayKey = [ [NSString alloc] initWithFormat:@"%@%@", AC_Type,  @"_FuelInterpolation" ];
    fuelInterpolationDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
    //NSLog(@"fuelInterpolationDictionary AC_Type %@  ", AC_Type);    
    arrayFuelVolumeLONG = [fuelInterpolationDictionary objectForKey:@"arrayFuelVolumeLONG"];
    arrayFuelMomentLONG = [fuelInterpolationDictionary objectForKey:@"arrayFuelMomentLONG"];    
    arrayFuelVolumeLAT = [fuelInterpolationDictionary objectForKey:@"arrayFuelVolumeLAT"];
    arrayFuelMomentLAT = [fuelInterpolationDictionary objectForKey:@"arrayFuelMomentLAT"];
        
    //NSLog(@"loaded arrayFuelVolumeLONG %@", arrayFuelVolumeLONG);
    //NSLog(@"arrayFuelMomentLONG %@", arrayFuelMomentLONG);
    //NSLog(@"arrayFuelMomentLAT %@", arrayFuelMomentLAT);
    
    
    addToStartIDforVariableTanks = 0;
    flagWeHaveVariableTanks = 0;
    useTankNumberInArray = 0;

    for (int i = 0; i < _arrayName18.count-1  ; i++) {
        
        if ([[_arrayName18 objectAtIndex: i ] rangeOfString:@"forceFuelTank"].location != NSNotFound ) {
            flagWeHaveVariableTanks = 1;
            useTankNumberInArray = [[_arrayName18 objectAtIndex:i]floatValue];  
            if (flagWeHaveVariableTanks == 1) { 
                              NSMutableArray *trenner = [[NSMutableArray alloc] init];
                               [trenner addObject: @"0"];
                               [trenner addObject: @"0"];
                              for (int i = 0; i<arrayFuelVolumeLONG.count-1; i++) {
                                  if ([[arrayFuelMomentLONG objectAtIndex:i] isEqualToString:@"|"]) {
                                      [trenner addObject: [[NSString alloc] initWithFormat:@"%d ", i]];
                                      //NSLog(@"trenner %d", i);
                                  }
                              }
                       addToStartIDforVariableTanks =[[trenner objectAtIndex:useTankNumberInArray] intValue]; 
                     
                   }
        }
    }
    
     NSLog(@"addToStartIDforVariableTanks %d", addToStartIDforVariableTanks);
    
}


- (void) setFuelTankSettings {
    
    //NSLog(@"setFuelTankSettings");
   
    fuelUnits = [_arrayName21 objectAtIndex:15 ];   
       
     tankCapacityVolume = [[_arrayName21 objectAtIndex: 17 ] floatValue];
     _sliderFuelMain1.maximumValue = tankCapacityVolume;
     _sliderFuelLanding.maximumValue = tankCapacityVolume - (tankCapacityVolume * 0.05);

    
    
    
    if (_sliderFuelMain1.value >  tankCapacityVolume) {
        _sliderFuelMain1.value =  tankCapacityVolume;
    }    
    
   //NSLog(@"setFuelTankSettings to tankCapacityVolume %.0f", tankCapacityVolume);
    
}




- (void) setCGwindows {
    
  //NSLog(@"setCGwindows ");
    
    // set lateral cg envelope or not
    if (flagIsLandscape == 1) {
        
        if ([[_arrayName21 objectAtIndex:13] isEqualToString:@"noLat"]) {
            //NSLog(@"noLat");
            _viewCGLatManifest.hidden = YES;
            // long only
            _viewCGlat.hidden = YES;
            _viewCGLong.frame  = CGRectMake( 646, 140, 374, 450 );
            _viewMeasureCGenvelope.frame  = CGRectMake( 50, 14, 309, 430 );            
            _viewCGenvelopeFrame.frame  = CGRectMake( 0, 0, _viewCGLong.frame.size.width, _viewCGLong.frame.size.height );            
            _viewFuelPathCG.frame  = CGRectMake( 0, 0, _viewCGLong.frame.size.width, _viewCGLong.frame.size.height );
            _viewFuelPathCGLat.frame  = CGRectMake( 0, 0, _viewCGlat.frame.size.width, _viewCGlat.frame.size.height );
            _viewCGValues.frame  = CGRectMake( 650, 620, 377, 74 );
            
            _viewCGLongManifest.frame  = CGRectMake( 0, 5, 321, 450 );
            _viewMeasureCGenvelope2.frame  = CGRectMake( 40, 24, 263, 380 );   
            _viewCGenvelopeFrame2.frame  = CGRectMake( 0, 0, _viewCGLongManifest.frame.size.width, _viewCGLongManifest.frame.size.height );  
            
        }else{
            
            _viewCGLatManifest.hidden = NO;
            
            // draw  both long and lat
            _viewCGlat.hidden = NO;            
            
                       
            if (flagShowCGEnvelopeValues == 1){
                               
                 _viewCGLong.frame  = CGRectMake( 0, 125, 1200, 1200  );
                 _viewMeasureCGenvelope.frame  = CGRectMake( 70, 30, 400, 540 );                
                 _viewTrennerTop.hidden = YES;                
                 _viewCGlat.frame  = CGRectMake( 510, 127, 1200, 1200 );
                 _viewMeasureCGenvelope_LAT.frame  = CGRectMake( 50, 30, 400, 540 );                
                 [viewMain bringSubviewToFront: _viewCGlat];
                
            }else{
                
                _viewCGLong.frame  = CGRectMake( 646, 140, 374, 282 );
                _viewMeasureCGenvelope.frame  = CGRectMake( 50, 14, 309, 255 );
                _viewCGlat.frame  = CGRectMake( 646, 505, 374, 282 );
                _viewMeasureCGenvelope_LAT.frame  = CGRectMake( 50, 14, 309, 165 );
                _viewTrennerTop.hidden = NO;               
                
            }
            
            
            _viewCGenvelopeFrame.frame  = CGRectMake( 0, 0, _viewCGLong.frame.size.width, _viewCGLong.frame.size.height );
            _viewCGenvelopeFrame_LAT.frame  = CGRectMake( 0, 0, _viewCGlat.frame.size.width, _viewCGlat.frame.size.height );
            _viewFuelPathCG.frame  = CGRectMake( 0, 0, _viewCGLong.frame.size.width, _viewCGLong.frame.size.height );
            _viewFuelPathCGLat.frame  = CGRectMake( 0, 0, _viewCGlat.frame.size.width, _viewCGlat.frame.size.height );
            _viewCGValues.frame  = CGRectMake( 650, 420, 377, 74 );
            
            _viewCGLongManifest.frame  = CGRectMake( 0, 5, 321, 250 );
            _viewMeasureCGenvelope2.frame  = CGRectMake( 40, 14, 263, 201 );   
            _viewCGenvelopeFrame2.frame  = CGRectMake( 0, 0, _viewCGLongManifest.frame.size.width, _viewCGLongManifest.frame.size.height );  
        }
        
    }else{
        
        
        if (flagShowCGEnvelopeValues == 1){
                                  
                    _viewCGLong.frame  = CGRectMake( 0, 60, 1200, 1200 );
                    _viewMeasureCGenvelope.frame  = CGRectMake( 100, 30, 400, 400 );            
                    _viewCGlat.frame  = CGRectMake( 0, 510, 1200, 1200 );
                    _viewMeasureCGenvelope_LAT.frame  = CGRectMake( 100, 30, 400, 400 );
                    [viewMain bringSubviewToFront: _viewCGlat];
                   
               }else{                   
                   _viewCGLong.frame  = CGRectMake( 1, 712, 374, 289 );
                   _viewMeasureCGenvelope.frame  = CGRectMake( 50, 17, 309, 255 );
                   _viewCGlat.frame  = CGRectMake( 390, 790, 374, 289 );
                   _viewMeasureCGenvelope_LAT.frame  = CGRectMake( 50, 14, 309, 135 );             
                   
               }
        
        
       
        _viewCGenvelopeFrame.frame  = CGRectMake( 0, 0, _viewCGLong.frame.size.width, _viewCGLong.frame.size.height );
        _viewCGenvelopeFrame_LAT.frame  = CGRectMake( 0, 0, _viewCGlat.frame.size.width, _viewCGlat.frame.size.height );
        _viewFuelPathCG.frame  = CGRectMake( 0, 0, _viewCGLong.frame.size.width, _viewCGLong.frame.size.height );
        _viewFuelPathCGLat.frame  = CGRectMake( 0, 0, _viewCGlat.frame.size.width, _viewCGlat.frame.size.height );
        _viewCGValues.frame  = CGRectMake( 400, 710, 377, 74   );
        
        
        
       
        
        
        
        
        
        
        if ( [[_arrayName21 objectAtIndex:13] isEqualToString:@"noLat"]) {
            _viewCGlat.hidden = YES;
            _viewCGLatManifest.hidden = YES;
            
            _viewCGLongManifest.frame  = CGRectMake( 0, 5, 321, 450 );
            _viewMeasureCGenvelope2.frame  = CGRectMake( 40, 24, 263, 380 );   
            _viewCGenvelopeFrame2.frame  = CGRectMake( 0, 0, _viewCGLongManifest.frame.size.width, _viewCGLongManifest.frame.size.height ); 
            
        }else{
            _viewCGlat.hidden = NO;
            _viewCGLatManifest.hidden = NO;
            
            _viewCGLongManifest.frame  = CGRectMake( 0, 5, 321, 250 );
            _viewMeasureCGenvelope2.frame  = CGRectMake( 40, 14, 263, 201 );   
            _viewCGenvelopeFrame2.frame  = CGRectMake( 0, 0, _viewCGLongManifest.frame.size.width, _viewCGLongManifest.frame.size.height );  
            
            
        }
        
    }

    
}

- (void) createSelectorButtons {
    
    //NSLog(@"createSelectorButtons");    
    for(UIView *subview in [_viewSelectorButtons subviews]) {
        [subview removeFromSuperview];
    }    
    //get amount of buttons
    float numberOfSelectorButtons =0;
    NSString *buttonString = [_arrayName25 objectAtIndex:13]; 
    if (buttonString.length < 1) {        
        buttonString = @"Configuration_Flight Settings_Equipment_Crew List_Fuel";    
    }    
    NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];
    if ([customerFolderName isEqualToString:@"noAccount"] ) { 
        buttonString = @"Configuration_Flight Settings_Fuel";            
    } 
    
    if (flagSpecialPHIFlightSettingPage == 1) {
         buttonString = @"Toggle Flight Settings / Station Input"; 
    }
   
    
    NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"_"];
    NSArray *components = [buttonString componentsSeparatedByCharactersInSet:charSet];
    //NSLog(@"components %@", components);    
    numberOfSelectorButtons = components.count;    
    float buttonWidth = 650 / numberOfSelectorButtons;
    float buttonHeight = _viewSelectorButtons.frame.size.height;
    
    for (int i = 0; i < numberOfSelectorButtons  ; i++) {
        buttonView =[[UIView alloc] initWithFrame:CGRectMake(i * buttonWidth - 3, 0, buttonWidth , buttonHeight) ];
        buttonView.backgroundColor = [UIColor lightGrayColor];
        [_viewSelectorButtons addSubview:buttonView];                
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0 ,  0, buttonWidth, buttonHeight);        
        if ([[components objectAtIndex: i  ] rangeOfString:@"Flight Settings"].location != NSNotFound ) {
            
            [btn addTarget:self
                    action:@selector(actionShowFlightSettings:)
          forControlEvents:UIControlEventTouchUpInside];
            btn.tag = 222;    
        }        
        if ([[components objectAtIndex: i  ] rangeOfString:@"Configuration"].location != NSNotFound  || [[components objectAtIndex: i  ] rangeOfString:@"Role Fits"].location != NSNotFound) {
           
            [btn addTarget:self
                    action:@selector(buttonActionConfigurations:)
          forControlEvents:UIControlEventTouchUpInside];
        }        
        if ([[components objectAtIndex:i] isEqualToString:@"Equipment"] || [[components objectAtIndex:i] isEqualToString:@"Equip"] || [[components objectAtIndex:i] isEqualToString:@"Special Equipment"]) {
            [btn addTarget:self
                    action:@selector(actionShowEquiplistView:)
          forControlEvents:UIControlEventTouchUpInside];
        }        
        if ([[components objectAtIndex:i] isEqualToString:@"Crew List"] || [[components objectAtIndex:i] isEqualToString:@"Crew"]) {
           
            [btn addTarget:self
                    action:@selector(actionShowPilotList:)
          forControlEvents:UIControlEventTouchUpInside];
        }        
        if ([[components objectAtIndex:i] isEqualToString:@"Fuel"] ) {
            [btn addTarget:self
                    action:@selector(actionSetFuel:)
          forControlEvents:UIControlEventTouchUpInside];
            btn.tag = 111;
        }        
        [btn  setBackgroundImage:[UIImage imageNamed: @"button blue top184x52" ] forState:UIControlStateNormal];       
        [buttonView addSubview:btn];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, buttonWidth , buttonHeight) ];
        label.font = [UIFont boldSystemFontOfSize:15];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
         [label  setText: [components objectAtIndex:i] ];
        [buttonView addSubview:label];        
        if ([[components objectAtIndex:i] isEqualToString:@"Fuel"]) {
            UIImageView *image =[[UIImageView alloc] initWithFrame:CGRectMake((buttonWidth/2)-48, 5, 30 , 30) ];
            image.image=[UIImage imageNamed:@"Fuel Symbol.png"];
            [buttonView addSubview:image];
        }
    }  
   
   
}



- (void) setCrosses {
    
    if ([[_arrayName24 objectAtIndex:15] isEqualToString:@"triangles"]) {
        
        UIImage *cgImage = [UIImage imageNamed: @"pointCGTO.png" ];
        [crossTOW setImage:cgImage ];        
        cgImage = [UIImage imageNamed: @"pointCGLD.png" ];
        [crossLDW setImage:cgImage ];        
        cgImage = [UIImage imageNamed: @"pointCGZF.png" ];
        [crossZFW setImage:cgImage ]; 
        cgImage = [UIImage imageNamed: @"pointCGTO.png" ];
        [crossLatTOW setImage:cgImage ];
        cgImage = [UIImage imageNamed: @"pointCGLD.png" ];
        [_crossLatLDW setImage:cgImage ];
        cgImage = [UIImage imageNamed: @"pointCGZF.png" ];
        [_crossLatZFW setImage:cgImage ];
        
        cgImage = [UIImage imageNamed: @"pointCGTOblack.png" ];
        [_crossMailTow setImage:cgImage ];        
        cgImage = [UIImage imageNamed: @"pointCGLDblack.png" ];
        [_crossMailLDW setImage:cgImage ];        
        cgImage = [UIImage imageNamed: @"pointCGZFblack.png" ];
        [_crossMailZFW setImage:cgImage ]; 
        cgImage = [UIImage imageNamed: @"pointCGTOblack.png" ];
        [_crossMailLAT setImage:cgImage ];
        cgImage = [UIImage imageNamed: @"pointCGTOblack.png" ];
        [_crossMailLATLDW setImage:cgImage ];
        cgImage = [UIImage imageNamed: @"pointCGLDblack.png" ];
        [_crossMailLATZFW setImage:cgImage ];
        
       
        
        
    }else{
        
        
        
        UIImage *cgImage = [UIImage imageNamed: @"cgCrossTO.png" ];
        
        if ( ![[_arrayName21 objectAtIndex:47] isEqualToString:@"Yellow"]) {
            cgImage = [UIImage imageNamed: @"cgCrossTOwhite.png" ];
        }        
        [crossTOW setImage:cgImage ];        
        cgImage = [UIImage imageNamed: @"cgCrossLD.png" ];
        [crossLDW setImage:cgImage ];        
        cgImage = [UIImage imageNamed: @"cgCrossZF.png" ];
        [crossZFW setImage:cgImage ]; 
        cgImage = [UIImage imageNamed: @"cgCrossTO.png" ];
        if ( ![[_arrayName21 objectAtIndex:47] isEqualToString:@"Yellow"]) {
            cgImage = [UIImage imageNamed: @"cgCrossTOwhite.png" ];
        } 
        [crossLatTOW setImage:cgImage ];
        cgImage = [UIImage imageNamed: @"cgCrossLD.png" ];
        [_crossLatLDW setImage:cgImage ];
        cgImage = [UIImage imageNamed: @"cgCrossZF.png" ];
        [_crossLatZFW setImage:cgImage ];
        
        cgImage = [UIImage imageNamed: @"cgCrossTOblack.png" ];
        [_crossMailTow setImage:cgImage ];        
        cgImage = [UIImage imageNamed: @"cgCrossLDblack.png" ];
        [_crossMailLDW setImage:cgImage ];        
        cgImage = [UIImage imageNamed: @"cgCrossZFblack.png" ];
        [_crossMailZFW setImage:cgImage ]; 
        cgImage = [UIImage imageNamed: @"cgCrossTOblack.png" ];
        [_crossMailLAT setImage:cgImage ];
        cgImage = [UIImage imageNamed: @"cgCrossLDblack.png" ];
        [_crossMailLATLDW setImage:cgImage ];
        cgImage = [UIImage imageNamed: @"cgCrossZFblack.png" ];
        [_crossMailLATZFW setImage:cgImage ];
        
        
    }
    
}

- (void) setBasicsForConfiguration {
    
    //NSLog(@"setBasicsForConfiguration ---- ");
    
    int flagLoadUnits = 0;
    
    //NSLog(@"1 previousOriginalWeightUnits %@", previousOriginalWeightUnits);
    
    //NSLog(@"_arrayName1 %@", _arrayName1);
    
    flagWeHavePenaltyData = 0;
    arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@_%@_%@_%@", ACCategory, ACmanufacturer, AC_Type, ACVariant, @"penaltyData" ];
    NSString *penaltyData = [[NSUserDefaults standardUserDefaults] objectForKey:arrayKey]; 
    if (penaltyData.length > 3) {
        //NSLog(@"penaltyData %@", penaltyData);
        flagWeHavePenaltyData = 1;
    }
    
    if (![previousOriginalWeightUnits isEqualToString: [_arrayName21 objectAtIndex:5] ]) {
        flagLoadUnits = 1;
        previousOriginalWeightUnits = [_arrayName21 objectAtIndex:5];
    }
    if (![previousOriginalFuelUnits isEqualToString: [_arrayName21 objectAtIndex:15] ]) {
        flagLoadUnits = 1;
        previousOriginalFuelUnits = [_arrayName21 objectAtIndex:15];
    }
    
    _viewHVdata.hidden = YES;
  
    calculatePerformanceClass_.cruiseInputFuelFlow.text = @"xxx";
    resultCruiseFuelBurn = 0;
    
    [self setCrosses];
    
    NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];    
    if ([customerFolderName isEqualToString:@"noAccount"] ) { 
        _viewGenericACaccess.hidden = NO; 
        _buttonImportPerfData.hidden = YES;
        _buttonImportConfigData.hidden = YES;
    }else{
        _buttonImportPerfData.hidden = NO;
        _buttonImportConfigData.hidden = NO;        
               
        NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
        if ([userExtraCheck rangeOfString:@"allowGeneric"].location != NSNotFound  ) {         
            _viewGenericACaccess.hidden = NO; 
        }else{           
             _viewGenericACaccess.hidden = YES; 
        }
    }
    
    
    if (_viewGenericACaccess.hidden == YES) {
        _buttonImportPerfData.frame = CGRectMake(390, 305, 210, 50);
        _buttonImportConfigData.frame = CGRectMake(390, 360, 210, 50);
    }else{
        
        _buttonImportPerfData.frame = CGRectMake(390, 471, 210, 50);
        _buttonImportConfigData.frame = CGRectMake(390, 523, 210, 50);
    }
    
    // will be called anytime we load a flight    
    [self supportedInterfaceOrientations]; 
    _viewRobinsonFuelPanel.hidden = YES;   
    
    // show/hide config and equipment weight label on heli top view
    if ( [[_arrayName22 objectAtIndex:43] isEqualToString:@"yes"] ) {
        _labelConfigurationName2.hidden = NO;
        _labelSEtotalWeight2.hidden = NO;
    }else{
        _labelConfigurationName2.hidden = YES;
        _labelSEtotalWeight2.hidden = YES;
    }
    
    if ( [[_arrayName25 objectAtIndex:43] isEqualToString:@"US"] ) {
       unitsAltimeter = @"US";
    }else{
        unitsAltimeter = @"EU";
    }
    
    restrictingHoistWeight = 99999;
    
    unitsWeight.text = [_arrayName21 objectAtIndex: 5  ];
    fuelUnits = [_arrayName21 objectAtIndex:15 ];
    //NSLog(@"setting unitsWeight.text to %@", unitsWeight.text);    
    //NSLog(@"fuelUnits %@", fuelUnits);    
    //NSLog(@"selectedUnitForItems %@", selectedUnitForItems);    
    
    [self searchbutSelHeli];   
 
    if ([vFlightID floatValue] < 1 || flagLoadUnits == 1) {
        //NSLog(@"2 meep");   
       
        //NSLog(@"0 _inputQuickLoadPreset.text %@", _inputQuickLoadPreset.text);
        //NSLog(@"vFlightID %@", vFlightID);
        
        selectedUnitForItems = unitsWeight.text;
        selectedUnitForFuel = unitsWeight.text;
        _inputQuickLoadPreset.text = [_arrayName21 objectAtIndex: 33 ];
        
        if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"forceUnitLBS"].location != NSNotFound ) {
            _inputQuickLoadPreset.text = [ [NSString alloc] initWithFormat:@"%.0f", [[_arrayName21 objectAtIndex: 33 ]floatValue] * 2.2046 ];        
            float toRound =  [_inputQuickLoadPreset.text floatValue] ;        
            int dummy = toRound / 10;        
            toRound =  (dummy * 10)+10;
            _inputQuickLoadPreset.text = [ [NSString alloc] initWithFormat:@"%.0f",toRound ];
            
            _segmentUnitsForItems.selectedSegmentIndex = 1;
            _segmentUnitsForFuel.selectedSegmentIndex = 1;
            selectedUnitForItems = @"lbs";
            selectedUnitForFuel = @"lbs";            
        }
        
        
      
        
        if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"forceUnitKG"].location != NSNotFound ) {     
            
            _inputQuickLoadPreset.text = [ [NSString alloc] initWithFormat:@"%.0f", [[_arrayName21 objectAtIndex: 33 ]floatValue] / 2.2046 ];        
            float toRound =  [_inputQuickLoadPreset.text floatValue] ;        
            int dummy = toRound / 10;        
            toRound =  (dummy * 10)+10;
            _inputQuickLoadPreset.text = [ [NSString alloc] initWithFormat:@"%.0f",toRound ];
            
            
            _segmentUnitsForItems.selectedSegmentIndex = 0;
            _segmentUnitsForFuel.selectedSegmentIndex = 0;
            selectedUnitForItems = @"kg";
            selectedUnitForFuel = @"kg";  
            
        }
        
        
        if ([fuelUnits isEqualToString:@"lbs"]) {
            _inputSpecificFuelMassPerVolume.text = [_arrayName21 objectAtIndex: 20 ] ; // lbs/gal             
        }else{
            _inputSpecificFuelMassPerVolume.text = [_arrayName21 objectAtIndex: 22 ] ; // kg/ltr 
        }
        
        if ([[_arrayName21 objectAtIndex:24] isEqualToString:@"volume"] ) {
            _segmentFuelVolumeOrMass.selectedSegmentIndex = 0;
            fuelEnterMode = @"volume";            
        }else{
            _segmentFuelVolumeOrMass.selectedSegmentIndex = 1;
            fuelEnterMode = @"mass";  
        }
    }
    
    
    if ([fuelEnterMode isEqualToString:@"volume"]) {
        _segmentFuelVolumeOrMass.selectedSegmentIndex = 0;
    }else{
        _segmentFuelVolumeOrMass.selectedSegmentIndex = 1;
    }
    
   
    
    
    
    if ([fuelUnits isEqualToString:@"lbs"]) {       
        _unitFuelDensity.text = @"lbs/Gal";
    }else{       
        _unitFuelDensity.text = @"kg/ltr";
    }
    
    
    if ([selectedUnitForItems isEqualToString:@"kg"]) {       
        _segmentUnitsForItems.selectedSegmentIndex = 0;
    }else{       
        _segmentUnitsForItems.selectedSegmentIndex = 1;
    }
    
    if ([selectedUnitForFuel isEqualToString:@"kg"]) {
        _segmentUnitsForFuel.selectedSegmentIndex = 0;
    }else{
        _segmentUnitsForFuel.selectedSegmentIndex = 1;
    }
    
 
    
    [self setUnitConversionFactors];    
    [self setCGwindows];    
    
    alternateCGenvelope = @"CGenvelope";    
    if ( [[_arrayName22 objectAtIndex:49]isEqualToString:@"yes"]) {
        
    }else{        
        if ([[_arrayName22 objectAtIndex:49] length] > 4) {            
             alternateCGenvelope = [_arrayName22 objectAtIndex:49] ;
            //NSLog(@"1setBasics setting alternateCGenvelope %@", alternateCGenvelope);
        }
    }
    
    //NSLog(@"s2etBasics setting alternateCGenvelope %@", alternateCGenvelope);
        
    [self setCGenvelope];    
    [self createLabelsForSetupPage];    
    [self createSelectorButtons];   
    
    NSString *ACTypeForLogoOnly = AC_Type;
    if (ACTypeForLogoOnly.length > 0) {
        if ([[ACTypeForLogoOnly substringFromIndex: [ACTypeForLogoOnly length] - 3] isEqualToString:@"P2P"] || [[ACTypeForLogoOnly substringFromIndex: [ACTypeForLogoOnly length] - 3] isEqualToString:@"T2P"]) {                        
          ACTypeForLogoOnly = [ACTypeForLogoOnly substringToIndex:[ACTypeForLogoOnly length] - 2];  
          ACTypeForLogoOnly = [ACTypeForLogoOnly stringByAppendingString:@"2+"]; 
        }
    }
    if (flagIsLandscape == 1) {
         _labelLogoOnlyACtype.text =  [[NSString alloc] initWithFormat:@"%@ %@", ACmanufacturer ,ACTypeForLogoOnly];
    }else{
         _labelLogoOnlyACtype.text =  [[NSString alloc] initWithFormat:@"%@", ACTypeForLogoOnly];
    }
    
    //large top view mode
    if ( [[_arrayName22 objectAtIndex:41] isEqualToString:@"yes"] ) {
        largeTopViewMode = 1;
    }else{
        largeTopViewMode = 0;                
    }
   
    [self loadACimages];
    [self loadFuelArrays];
    [self setItemsFlightLegData];
    _viewHeliCenterLabels.frame = CGRectMake(0, 0, 232, 556);
    [self setOptionalButtons];
    [self setGuidanceNeutral];  
    [self setFuelTankSettings];
    [self addPerformanceButtons];
    
   
    
    if ([AC_Type isEqualToString: @"H130"] || [AC_Type isEqualToString: @"R66"] || [AC_Type rangeOfString:@"R44Raven"].location != NSNotFound   || [AC_Type rangeOfString:@"R44Cadet"].location != NSNotFound   || [AC_Type rangeOfString:@"R22Beta"].location != NSNotFound  || [alternateCGenvelope rangeOfString:@"inverted"].location != NSNotFound  ) {
        flagLATinputH130 = 1;
    }else{
        flagLATinputH130 = 0;
    }
    datepick.minuteInterval = [[_arrayName23 objectAtIndex:7] integerValue];
    
    if ( [[_arrayName22 objectAtIndex:39] isEqualToString:@"Closed"] || [[_arrayName22 objectAtIndex:39] isEqualToString:@"closed"]) {
        flagFuelVisisble = 0;
    }else{
        flagFuelVisisble = 1;
    }
    //NSLog(@"flagFuelVisisble %.0f", flagFuelVisisble);
    
    UIImage *sliderImage = [UIImage imageNamed:@"sliderEmpty.png"];
    UIImage *sliderThumb = [UIImage imageNamed:@"triangle3.png"];
    UIImage *sliderImageYel;
    if ( [[_arrayName21 objectAtIndex:47] isEqualToString:@"Yellow"]) {
        sliderImageYel = [UIImage imageNamed:@"sliderYellowLine thin.png"];
    }else{
        sliderImageYel = [UIImage imageNamed:@"sliderGreenLine thin.png"];
    }
    
    [_sliderFuelMain1 setMaximumTrackImage:sliderImage forState:UIControlStateNormal];
    [_sliderFuelMain1 setMinimumTrackImage:sliderImageYel forState:UIControlStateNormal];
    [_sliderFuelMain1 setThumbImage:sliderThumb forState:UIControlStateNormal];
    [_sliderFuelLanding setMaximumTrackImage:sliderImage forState:UIControlStateNormal];
    [_sliderFuelLanding setMinimumTrackImage:sliderImageYel forState:UIControlStateNormal];
    [_sliderFuelLanding setThumbImage:sliderThumb forState:UIControlStateNormal];
    
  if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"fuelFlow"].location != NSNotFound ) {  
      //NSLog(@"1 _inputPHIOverrideFuelFlow %@ ", _inputPHIOverrideFuelFlow.text );
      //NSLog(@"1 inputFuelFlowOverride %@ ", inputFuelFlowOverride.text );
      if ([_inputPHIOverrideFuelFlow.text isEqualToString:inputFuelFlowOverride.text ]) {
          [self overrideFuelFlowFromSpecialData];
      }else{
          inputFuelFlowOverride.text = _inputPHIOverrideFuelFlow.text;
      }
  }  
    
    if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"sledWeight"].location != NSNotFound ) {  
    
        NSString *negativeSledWeight = [[NSString alloc] initWithFormat:@"%.1f", [_inputPHIOverrideSledWeight.text floatValue] * -1.0];
        [_arrayName17 replaceObjectAtIndex:linePatient withObject:negativeSledWeight];
    }
    
    _setToNowButton.hidden = NO;
    if (flagSpecialPHIFlightSettingPage == 1) {
        _setToNowButton.hidden = YES;
    }
    
     
    [self setTopViewWindowSettings];
    
}



- (void) setTopViewWindowSettings {
    
    //NSLog(@"setTopViewWindowSettings ");
    [self setInteriorMeasures];   
    _viewHelicopterInCenter.clipsToBounds = YES;    
    // plan mode is currently always Plan   ********************************************************************************************************************
    
    if (_segmentPlanMode.selectedSegmentIndex == 1) {
        //NSLog(@"plan mode");
        _viewButtonSet1.hidden = YES;
        _viewButtonSet2.hidden = NO;
        _viewStationsWindow.hidden = YES;       
        [viewMain bringSubviewToFront:_viewLegData];
        [viewMain bringSubviewToFront:_viewHelicopterInCenter];
        [viewMain bringSubviewToFront:_viewFuelPanel];
        
     
        [self setFuelPanelandLegDataViews];
        
        if (flagShowSliders == 1) {
            [_buttonToggleLegWeights setTitle:@"Show Leg Info" forState:UIControlStateNormal];
            _viewStationsWindow.hidden = NO;
            _viewLegData.hidden = YES;
        }
        if (flagShowSliders == 0) {
            [_buttonToggleLegWeights setTitle:@"Enter Station Weights" forState:UIControlStateNormal];
        }
    }
    
    self.scrollViewHeliCenter.delegate = self;
    
    [self arrangeWindows];
    
}


- (void) setFuelPanelandLegDataViews {
    
    //NSLog(@"setFuelPanelandLegDataViews" );
    
    if (triggerFuelAnimation == 1) {
        triggerFuelAnimation = 0;
        //NSLog(@"triggerFuelAnimation" );
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
    }
   
    
    float fuelPanelHeight = 0;
    fuelPanelHeight = [[_arrayName22 objectAtIndex:37] floatValue];
    if (fuelPanelHeight < 1) {
        fuelPanelHeight = 155;
    }
    
      _labelAvailableExternalLoad.frame = CGRectMake(80, 258, 242, 21);
    
    if (flagIsLandscape == 1) {
        float fuelPanelTop = 0;
        if (flagFuelVisisble == 1) {
            _viewFuelPanel.frame = CGRectMake(0, 718 - fuelPanelHeight , _viewFuelPanel.frame.size.width, 600 );
            fuelPanelTop = 718 - fuelPanelHeight;
        }else{
            _viewFuelPanel.frame = CGRectMake(0, 718, _viewFuelPanel.frame.size.width, 600 );
            fuelPanelTop = 718;
        }
        _viewLegData.frame = CGRectMake(0, 115, 646, fuelPanelTop - 125);
        if (flagSpecialPHIFlightSettingPage == 1) {
            if (flagFuelVisisble == 0) {
                _viewLegData.frame = CGRectMake(0, 115, 300, fuelPanelTop - 125);   
                enterPad.hidden = YES;
                UIImage *buttonmark = [UIImage imageNamed:@"Klammern.png"];        
                [_buttonEnterFuelMain setImage:buttonmark forState:UIControlStateNormal];  
            }else{
                [self setListoButtonsNeutral];        
                enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;        
                UIImage *buttonmark = [UIImage imageNamed:@"Klammern_Yel.png"];        
                [_buttonEnterFuelMain setImage:buttonmark forState:UIControlStateNormal];        
                EnterPadString = _labelSliderFuelMain.text; calculatorscreen.text = _labelSliderFuelMain.text; EnterValueTwo = 0;
                selectedItem = 25;   
                
            }
          
            
        }
        _viewLegDataItems.frame = CGRectMake(0, -8, _viewLegData.frame.size.width, _viewLegDataItems.frame.size.height);
        _scrollViewLegData.frame = CGRectMake(0, 25, _viewLegData.frame.size.width, _viewLegData.frame.size.height - 30);
        
      
        if ( [[_arrayName21 objectAtIndex:13] isEqualToString:@"noLat"]) {
            _labelAvailableExternalLoad.frame = CGRectMake(80, 430, 242, 21);
        }
        
    }else{
        
        float fuelPanelTop = 0;
        if (flagFuelVisisble == 1) {
            _viewFuelPanel.frame = CGRectMake(0, 657 - fuelPanelHeight , _viewFuelPanel.frame.size.width, fuelPanelHeight + 37);
            fuelPanelTop = 657 - fuelPanelHeight;
        }else{
            _viewFuelPanel.frame = CGRectMake(0, 657, _viewFuelPanel.frame.size.width, 37);
            fuelPanelTop = 657;
        }
        _viewLegData.frame = CGRectMake(0, 57, 642, fuelPanelTop - 67);
        if (flagSpecialPHIFlightSettingPage == 1) {
            if (flagFuelVisisble == 0) {
                _viewLegData.frame = CGRectMake(0, 57, 300, fuelPanelTop - 67);
                enterPad.hidden = YES; 
                UIImage *buttonmark = [UIImage imageNamed:@"Klammern.png"];        
                [_buttonEnterFuelMain setImage:buttonmark forState:UIControlStateNormal];  
            }else{
                [self setListoButtonsNeutral];        
                enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;        
                UIImage *buttonmark = [UIImage imageNamed:@"Klammern_Yel.png"];        
                [_buttonEnterFuelMain setImage:buttonmark forState:UIControlStateNormal];        
                EnterPadString = _labelSliderFuelMain.text; calculatorscreen.text = _labelSliderFuelMain.text; EnterValueTwo = 0;
                selectedItem = 25;                   
            }
            
        }
        _viewLegDataItems.frame = CGRectMake(0, -8, _viewLegData.frame.size.width, _viewLegDataItems.frame.size.height);
        _scrollViewLegData.frame = CGRectMake(0, 25, _viewLegData.frame.size.width, _viewLegData.frame.size.height - 30);
        
    }
    
    
    
     [self setHeliTopView];    
     [UIView commitAnimations];    
    
    float addForPanelHeight = 0;
    if (flagFuelVisisble == 1) {
        addForPanelHeight = [[_arrayName22 objectAtIndex:37] floatValue]; //fuelPanelHeight
    }
    
    [_scrollViewStations setContentSize:CGSizeMake(_viewStationsSlider.frame.size.width, yPixSliderValue + 150 + addForPanelHeight)];
    [_scrollViewStationsRight setContentSize:CGSizeMake(_viewStationsSliderRight.frame.size.width, yPixSliderValue + 150 + addForPanelHeight)];
    
    
    
}


- (void) setHeliTopView {
    
    //NSLog(@"setHeliTopView ");
    
    float yUpHeliIndividual = 0;
    yUpHeliIndividual = [[_arrayName21 objectAtIndex:37] floatValue];
    //NSLog(@"yUpHeliIndividual %.f ", yUpHeliIndividual);
    
    //viewMain
    //viewHelicopterInCenter
    //--scrollViewHeliCenter
    //      viewHeliCenterLabels
    //          ACtopView
    //          viewInterior (Measures)
    //------viewEquipmentOnHeli (=viewHeliCenterLabels)
    
    float boxMoveX = 0;
    /// check if boxed sliders
    if ( [[_arrayName24 objectAtIndex:5] isEqualToString:@"yes"] ) {
        boxMoveX = 15;
    }
    
    
    
    float xMoveConfigWindowLargeView = 0;
    float yMoveConfigWindowLargeView = 0;
    float xMoveConfigWindow = 0;
    float yMoveConfigWindow = 0;
    
    int Xversatz = -86; // -86
   
    if ([[_arrayName25 objectAtIndex:22] isEqualToString:@"signalComingFromBackend"]) {
        Xversatz = -91; // is more precise when coming from backend
    }
    
    
   [_scrollViewHeliCenter setContentOffset:CGPointZero animated:YES];
    //NSLog(@"boxMoveX %.0f", boxMoveX);    
    //NSLog(@"Xversatz %d", Xversatz);
    
    //NSLog(@"largeTopViewMode %d", largeTopViewMode);
    
    //NSLog(@"yUpHeliIndividual %.0f", yUpHeliIndividual);
   
    
    if (configMode == 1) {
        xMoveConfigWindowLargeView = -300;
        yMoveConfigWindowLargeView = 70;
        xMoveConfigWindow = - 180;
        yMoveConfigWindow = 120;
    }
   
    
    if (flagIsLandscape == 1) {
        float xMove = 0;
        float yMove = 0;
        
        _viewHelicopterInCenter.frame = CGRectMake( 0, 125 + yMove, 645, 595);
        
        if (largeTopViewMode == 1) {
            _viewStationsWindow.frame = CGRectMake( boxMoveX, 125, 250, 603 ) ;
            _viewStationsWindowRight.frame = CGRectMake( 2445, 125, 195, 603 );
            
            float xPHImove = 0;
            if (flagSpecialPHIFlightSettingPage == 1) {
                xPHImove = 30;
            }
            
            _scrollViewHeliCenter.frame = CGRectMake( 240 + xMove + xPHImove + xMoveConfigWindowLargeView, 50 + yMove + yUpHeliIndividual, 400, 550);
            _viewHeliCenterLabels.frame = CGRectMake(0, 0, _scrollViewHeliCenter.frame.size.width, _scrollViewHeliCenter.frame.size.height);
            _viewInterior.frame = CGRectMake(0, 0,  400, 566);
            _ACtopView.frame = CGRectMake([_iacACX.text floatValue] + 90, [_iacACY.text floatValue], [_iacACwidth.text floatValue], [_iacACheight.text floatValue]);
            _viewEquipmentOnHeli.frame = CGRectMake(-62, 48, 400, 566);
           
        }else{
            if (flagFuelVisisble == 0) {
                yMove = 40;
            }
            _viewStationsWindow.frame = CGRectMake( boxMoveX, 125, 195, 603 ) ;
            _viewStationsWindowRight.frame = CGRectMake( 450 - boxMoveX, 125, 195, 603 );
            _scrollViewHeliCenter.frame = CGRectMake( 204 + xMove + xMoveConfigWindow, 20 + yMove + yUpHeliIndividual, 233, 550);
            _viewHeliCenterLabels.frame = CGRectMake(0, 0, _scrollViewHeliCenter.frame.size.width, _scrollViewHeliCenter.frame.size.height);
            _viewInterior.frame = CGRectMake(Xversatz, 0,  400, 566);
            _ACtopView.frame = CGRectMake([_iacACX.text floatValue], [_iacACY.text floatValue], [_iacACwidth.text floatValue], [_iacACheight.text floatValue]);
            _viewEquipmentOnHeli.frame = CGRectMake(-62, 18, 400, 566);
        }
        
    }else{
        float xMove = 0;
        float yMove = -57;
        float yMove2 = 0;
        
        _viewHelicopterInCenter.frame = CGRectMake( 0, 125 + yMove, 645, 595);
        
        if (largeTopViewMode == 1) {
            float xPHImove = 0;
            if (flagSpecialPHIFlightSettingPage == 1) {
                xPHImove = 30;
            }            
            _viewStationsWindow.frame = CGRectMake( boxMoveX, 125 + yMove, 250, 603 ) ;
            _viewStationsWindowRight.frame = CGRectMake( 2445, 125 + yMove, 195, 603 );
            _scrollViewHeliCenter.frame = CGRectMake( 240 + xMove + xPHImove + xMoveConfigWindowLargeView, 50  + yUpHeliIndividual + yMoveConfigWindowLargeView, 400, 550);
            _viewHeliCenterLabels.frame = CGRectMake(0, 0, _scrollViewHeliCenter.frame.size.width, _scrollViewHeliCenter.frame.size.height);
            _viewInterior.frame = CGRectMake(0, 0,  400, 566);
            _ACtopView.frame = CGRectMake([_iacACX.text floatValue] + 84, [_iacACY.text floatValue], [_iacACwidth.text floatValue], [_iacACheight.text floatValue]);
            _viewEquipmentOnHeli.frame = CGRectMake(-62, 118, 400, 566);
        }else{
            if (flagFuelVisisble == 0) {
                yMove2 = 40;
            }
            _viewStationsWindow.frame = CGRectMake( boxMoveX, 125 + yMove, 195, 603 ) ;
            _viewStationsWindowRight.frame = CGRectMake( 445 - boxMoveX, 125 + yMove, 195, 603 );
            _scrollViewHeliCenter.frame = CGRectMake( 204 + xMove + xMoveConfigWindow, 20 + yMove2 + yUpHeliIndividual + yMoveConfigWindow, 233, 550);
            _viewHeliCenterLabels.frame = CGRectMake(0, 0, _scrollViewHeliCenter.frame.size.width, _scrollViewHeliCenter.frame.size.height);
            _viewInterior.frame = CGRectMake(Xversatz, 0,  400, 566);
            _ACtopView.frame = CGRectMake([_iacACX.text floatValue], [_iacACY.text floatValue], [_iacACwidth.text floatValue], [_iacACheight.text floatValue]);
            _viewEquipmentOnHeli.frame = CGRectMake(-62, 145, 400, 566);
        }
        
    }
    
  
    
    //NSLog(@"_viewInterior.frame.origin.x  %.0f", _viewStationsWindow.frame.origin.x); 
    //NSLog(@"_viewInterior.frame.origin.y  %.0f", _viewStationsWindow.frame.origin.y); 
    //NSLog(@"_viewHeliCenterLabels  %.0f", _viewHeliCenterLabels.frame.origin.x);    
    //NSLog(@"_ACtopView  %.0f", _ACtopView.frame.origin.x);
    
    
     [_scrollViewHeliCenter setContentSize:CGSizeMake(_scrollViewHeliCenter.frame.size.width, 456 + 290)];
    
    
    _labelConfigurationName2.frame = CGRectMake( _scrollViewHeliCenter.frame.origin.x , 9, _scrollViewHeliCenter.frame.size.width, 21);
    _labelSEtotalWeight2.frame = CGRectMake( _scrollViewHeliCenter.frame.origin.x, 30, _scrollViewHeliCenter.frame.size.width, 21);
    
    
    _viewStationsSlider.frame = CGRectMake(0, 0, _viewStationsWindow.frame.size.width, 2500);
    _scrollViewStations.frame = CGRectMake(0,0,_viewStationsWindow.frame.size.width, sliderWindowHeight);
    
    _viewStationsSliderRight.frame = CGRectMake(0, 0, _viewStationsWindowRight.frame.size.width, 2500);
    _scrollViewStationsRight.frame = CGRectMake(0,0,_viewStationsWindowRight.frame.size.width, sliderWindowHeight);
    
    if ( [[_arrayName24 objectAtIndex:5] isEqualToString:@"yes"] ) {
         [_scrollViewStations setScrollEnabled:NO];
         [_scrollViewStationsRight setScrollEnabled:NO];
    }else{
        [_scrollViewStations setScrollEnabled:YES];
        [_scrollViewStationsRight setScrollEnabled:YES];
    }
    
    
}




- (void) setInteriorMeasures {
    
    
    if ([[_arrayName22 objectAtIndex:41] isEqualToString:@"yes"] ) {
        largeTopViewMode = 1;
    }else{
        largeTopViewMode = 0;
    }
    
   //NSLog(@"setInteriorMeasures  largeTopViewMode  %d", largeTopViewMode);
    LongArmFrontSeat = [[_arrayName22 objectAtIndex: 5 ]floatValue] ;
    
     LongArmRearSeat = [[_arrayName22 objectAtIndex: 7 ]floatValue] ;
     LatArmLeftSeat = [[_arrayName22 objectAtIndex: 9 ]floatValue] ;
     LatArmRightSeat = [[_arrayName22 objectAtIndex: 11 ]floatValue] ;
    
    _iacMeasureFrontSeatsY.text =   [_arrayName22 objectAtIndex:14 ];
    _iacMeasureRearSeatsY.text =    [_arrayName22 objectAtIndex:16 ];
    _iacSeatWidth.text =            [_arrayName22 objectAtIndex:18 ];

    _iacSeatHeight.text =           [_arrayName22 objectAtIndex:20 ];
    _iacLatCenter.text =            [_arrayName22 objectAtIndex:22 ];
    _iacLatRight.text =             [_arrayName22 objectAtIndex:24 ];
    _iacACX.text =                  [_arrayName22 objectAtIndex:26 ];
    _iacACY.text =                  [_arrayName22 objectAtIndex:28 ];
    _iacACwidth.text =              [_arrayName22 objectAtIndex:30 ];
    _iacACheight.text =             [_arrayName22 objectAtIndex:32 ];
    _iacHeliYUp.text =             [_arrayName21 objectAtIndex: 37 ];


    _viewMeasureFrontSeats.frame = CGRectMake(_viewMeasureFrontSeats.frame.origin.x, [_iacMeasureFrontSeatsY.text floatValue], _viewMeasureFrontSeats.frame.size.width, _viewMeasureFrontSeats.frame.size.height);
    _viewMeasureRearSeats.frame = CGRectMake(_viewMeasureRearSeats.frame.origin.x, [_iacMeasureRearSeatsY.text floatValue], _viewMeasureRearSeats.frame.size.width, _viewMeasureRearSeats.frame.size.height);
    _viewSeatSize.frame = CGRectMake(_viewSeatSize.frame.origin.x, _viewSeatSize.frame.origin.y, [_iacSeatWidth.text floatValue] , [_iacSeatHeight.text floatValue]);
    _viewMeasureCenter.frame = CGRectMake([_iacLatCenter.text floatValue], _viewMeasureCenter.frame.origin.y, _viewMeasureCenter.frame.size.width , _viewMeasureCenter.frame.size.height);
    _viewMeasureLatRight.frame = CGRectMake([_iacLatCenter.text floatValue] + [_iacLatRight.text floatValue], _viewMeasureLatRight.frame.origin.y, _viewMeasureLatRight.frame.size.width , _viewMeasureLatRight.frame.size.height);
    
    
    
    return;
    
    
}




- (void) setConfiguration {
    
    
   //NSLog(@"setConfiguration");
    
    //NSLog (@"1 setConfiguration inputFuelFlowOverride %@", inputFuelFlowOverride.text);
    
    flagRefreshSpecialEquipmentList = 1;
    _inputPaxOnBoard.text = @"";
  
    
    for (int i = 1; i < arrayConfigurations.count+1  ; i++) {
        UIButton* btn = (UIButton*)[_viewConfigButtons viewWithTag: i ];
        UIImage *btnImage = [UIImage imageNamed:@"button generic dark.png"];
        [btn  setBackgroundImage:btnImage forState:UIControlStateNormal];
    }    
    [self saveRetainNames];    
    //NSLog(@"will retain: %@", arrayNamesToRetain); 
    
    [self loadArrayListo];    
    [self createListoItemsSlidersAndInterior];    
    [self MainRoutine];
    
    //NSLog (@"2 setConfiguration inputFuelFlowOverride %@", inputFuelFlowOverride.text);
    
     //NSLog(@"specialdata2 %@", specialdata2); forceUnitLBS
    if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"forceUnitLBS"].location != NSNotFound) {
        //NSLog(@"setConfiguration forceUnitLBS");
        _segmentUnitsForItems.selectedSegmentIndex = 1;
        [self convertWeightUnits];
        _segmentUnitsForFuel.selectedSegmentIndex = 1;
        [self convertFuelUnits];
    }else if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"forceUnitKG"].location != NSNotFound ) {       
        //NSLog(@"setConfiguration forceUnitKG");
        _segmentUnitsForItems.selectedSegmentIndex = 0;
        _segmentUnitsForFuel.selectedSegmentIndex = 0;
        [self convertWeightUnits];        
        if ([specialdata2 rangeOfString:@"GALLONS"].location != NSNotFound ) {
            _segmentUnitsForFuel.selectedSegmentIndex = 1;
            _segmentFuelVolumeOrMass.selectedSegmentIndex = 0;
            fuelEnterMode = @"volume";
        }
        if ([specialdata2 rangeOfString:@"POUNDS"].location != NSNotFound ) {
            _segmentUnitsForFuel.selectedSegmentIndex = 1;
            _segmentFuelVolumeOrMass.selectedSegmentIndex = 1;
            fuelEnterMode = @"mass";
        }
       
        [self convertFuelUnits];
       
        
    } else{
        //NSLog(@"no force");
        
    }
    
    //NSLog(@"3 selectedUnitForFue %@", selectedUnitForFuel);
    //NSLog(@"3 selectedUnitForItems %@", selectedUnitForItems);
}

- (void) saveRetainNames {
    
    //NSLog(@"saveRetainNames");
    
    arrayLinesToRetain = [[NSMutableArray alloc] init];
    arrayNamesToRetain = [[NSMutableArray alloc] init];
    arrayWeightsToRetain = [[NSMutableArray alloc] init];
    
    [self findLines];  
    //NSLog(@"lineLDW %f", lineLDW);
 
    for (int i = 3; i < lineLDW -1 ; i++) {
        
        //if (![[_arrayName7 objectAtIndex:i ] isEqualToString:@"-"] ||  [[_arrayName16 objectAtIndex:i ] isEqualToString:@"crew"]  ||  [[_arrayName16 objectAtIndex:i ] isEqualToString:@"crew L"]  ||  [[_arrayName16 objectAtIndex:i ] isEqualToString:@"crew R"]    ) {
        
       //NSLog(@"1 saving %@ %@ %@ ", [_arrayName1 objectAtIndex:i],  [_arrayName7 objectAtIndex:i], [_arrayName18 objectAtIndex:i]); 
        
        
         if ([[_arrayName18 objectAtIndex: i ] rangeOfString:@"retain"].location != NSNotFound   || [[_arrayName7 objectAtIndex: i ] rangeOfString:@"fuelTank"].location != NSNotFound) {
             //NSLog(@"2 saving %@ %@ ", [_arrayName1 objectAtIndex:i], [_arrayName18 objectAtIndex:i]); 
             
             if ([[_arrayName14 objectAtIndex: i ] rangeOfString:@"result"].location == NSNotFound  ) {
                 //NSLog(@"3 saving %@ %@ ", [_arrayName1 objectAtIndex:i], [_arrayName18 objectAtIndex:i]); 
                 //NSLog(@"retaining _arrayName1 %@", [_arrayName1 objectAtIndex:i ]);
                 [arrayLinesToRetain addObject:  [[NSString alloc] initWithFormat:@"%d", i]];
                 [arrayNamesToRetain addObject:  [_arrayName7 objectAtIndex:i ]];
                 [arrayWeightsToRetain addObject:[_arrayName2 objectAtIndex:i ]]; 
             }
             
             
         }
        
        
    }
    //NSLog(@"save arrayLinesToRetain %@ ", arrayLinesToRetain);  
   
    
}


- (void) retainCrewNames {
    
   
  
    
     //NSLog(@"arrayLinesToRetain %@", arrayLinesToRetain);
    
    // pilot name to retain crew weights
    // color the active button
    UIButton* btn = (UIButton*)[_viewConfigButtons viewWithTag: activeConfigButton];
    UIImage *btnImage = [UIImage imageNamed:@"button generic blue.png"];
    [btn  setBackgroundImage:btnImage forState:UIControlStateNormal];
    for (int i = 0; i < arrayLinesToRetain.count ; i++) {
        
        int retainLine = [[arrayLinesToRetain objectAtIndex:i]integerValue];
        
       
        
        
        if ([[_arrayName10 objectAtIndex: retainLine  ] rangeOfString:@"fuelTank"].location != NSNotFound  ) {
           
     
            
            valueField = (UITextField*)[_viewFuelSliders viewWithTag: 1200+ retainLine];
            
            //NSLog(@"2 YES retainLine %d", retainLine);
            
            //[valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [[arrayWeightsToRetain objectAtIndex:retainLine]floatValue]  ]];
            
            [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f",250.0  ]];
            
            [_arrayName2 replaceObjectAtIndex:retainLine withObject: [arrayWeightsToRetain objectAtIndex:i] ];
            
            NSString *arm = [_arrayName3 objectAtIndex:retainLine];
            
            // change moment
            [_arrayName4 replaceObjectAtIndex:retainLine withObject: [[NSString alloc] initWithFormat:@"%.1f", [[arrayWeightsToRetain objectAtIndex:i]floatValue]  * [arm floatValue]]  ];
            
            // get Arm Lat
            NSString *armLat = [_arrayName5 objectAtIndex:retainLine];
            // change momentLat
            [_arrayName6 replaceObjectAtIndex:retainLine withObject:[[NSString alloc] initWithFormat:@"%.1f", [[arrayWeightsToRetain objectAtIndex:i]floatValue] * [armLat floatValue]]  ];
           
            // update weight label 1000
            valueField = (UITextField*)[_viewFuelSliders viewWithTag: 1000+retainLine];
         
            
           
            
            if ([fuelEnterMode isEqualToString:@"mass"]) {
               
                if ([fuelUnits isEqualToString:selectedUnitForFuel] ) { 
                   [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [[arrayWeightsToRetain objectAtIndex:i]floatValue]   ]  ];                     
                }                
                
                if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
                   [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [[arrayWeightsToRetain objectAtIndex:i]floatValue] / 2.2046  ]  ];   
                    
                }
                
                if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [[arrayWeightsToRetain objectAtIndex:i]floatValue] * 2.2046  ]  ];   
                    
                }
                   
              
                    
            }else{
                
                //NSLog(@"selectedUnitForFuel %@", selectedUnitForFuel);
            
                if ([fuelUnits isEqualToString:selectedUnitForFuel] ) { 
                     [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [[arrayWeightsToRetain objectAtIndex:i]floatValue] / [_inputSpecificFuelMassPerVolume.text floatValue]     ]  ];                  
                }
                
                if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) {  
                    //slider is in pounds, so we go from punds to gallons to liter
                    //NSLog(@"gal to liter %@", [arrayWeightsToRetain objectAtIndex:i]  );
                    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f",  ([[arrayWeightsToRetain objectAtIndex:i]floatValue]/ [_inputSpecificFuelMassPerVolume.text floatValue]  * 3.78541)     ]  ];                   
                }
                
                if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) {  
                    //slider is in kilo, so we go from kilo  to liter to gallons
                    //NSLog(@"gal to liter %@", [arrayWeightsToRetain objectAtIndex:i]  );
                    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f",  ([[arrayWeightsToRetain objectAtIndex:i]floatValue]/ [_inputSpecificFuelMassPerVolume.text floatValue]  / 3.78541)     ]  ];                   
                }
                
                //baustelle
                
                
                
                
               
                
            }
            
            
            // update slider
            UISlider *slider = (UISlider*)[_viewFuelSliders viewWithTag:  retainLine];
            
            slider.value = [[arrayWeightsToRetain objectAtIndex:i]floatValue] ;
            
          
        }else{
            
            //NSLog(@"NOT a fuel");
                   
            
           
            
            [_arrayName7 replaceObjectAtIndex:retainLine withObject: [arrayNamesToRetain objectAtIndex:i] ];
            [_arrayName2 replaceObjectAtIndex:retainLine withObject: [arrayWeightsToRetain objectAtIndex:i] ];
            
            // change name in _viewStationsSlider
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200+retainLine];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200+retainLine];
            }
            [valueField  setText: [arrayNamesToRetain objectAtIndex:i] ];
            // get Arm Long
            NSString *arm = [_arrayName3 objectAtIndex:retainLine];
            
            // change moment
            [_arrayName4 replaceObjectAtIndex:retainLine withObject: [[NSString alloc] initWithFormat:@"%.1f", [[arrayWeightsToRetain objectAtIndex:i]floatValue]  * [arm floatValue]]  ];
            
            // get Arm Lat
            NSString *armLat = [_arrayName5 objectAtIndex:retainLine];
            // change momentLat
            [_arrayName6 replaceObjectAtIndex:retainLine withObject:[[NSString alloc] initWithFormat:@"%.1f", [[arrayWeightsToRetain objectAtIndex:i]floatValue] * [armLat floatValue]]  ];
            
            // update weight label 1000
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1000+retainLine];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1000+retainLine];
            }
            
            if ([unitsWeight.text isEqualToString:selectedUnitForItems] ) {
                [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [[arrayWeightsToRetain objectAtIndex:i]floatValue]   ]  ];
                
            }
            
            if ([unitsWeight.text isEqualToString:@"lbs"] & [selectedUnitForItems isEqualToString:@"kg"] ) {
                [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [[arrayWeightsToRetain objectAtIndex:i]floatValue] / 2.2046  ]  ];
                
            }
            
            if ([unitsWeight.text isEqualToString:@"kg"] & [selectedUnitForItems isEqualToString:@"lbs"] ) {
                [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [[arrayWeightsToRetain objectAtIndex:i]floatValue] * 2.2046  ]  ];
                
            }
            
            
            
            
            // update slider
            UISlider *slider = (UISlider*)[_viewStationsSlider viewWithTag:  retainLine];
            if (!slider) {
                slider = (UISlider*)[_viewStationsSliderRight viewWithTag:  retainLine];
            }
            slider.value = [[arrayWeightsToRetain objectAtIndex:i]floatValue] ;
            
        }
        
       
        
        
       
        
    }
    
}




- (void) animateCrossTOW {
    
    
    //NSLog(@"animateCrossTOW CGLongTOW %.2f", CGLongTOW);
    
    float xCGpos = leftBorderOfMeasureBox + ( (CGLongTOW -xAxisLeft) * xPixelFactor );
    float yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - weightTOW ) * yPixelFactor );
    if (isnan(xCGpos)) {
        xCGpos = 0;
    }
    if (isnan(yCGpos)) {
        yCGpos = 0;
    }
    crossTOW.center = CGPointMake( xCGpos, yCGpos);
    
    return;
    
    
    
}

- (void) animateCrossZFW {
    
    float xCGpos = leftBorderOfMeasureBox + ( (CGLongZFW -xAxisLeft) * xPixelFactor );
    float yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - weightZFW ) * yPixelFactor );
    
    if (isnan(xCGpos)) {
        xCGpos = 0;
    }
    if (isnan(yCGpos)) {
        yCGpos = 0;
    }
    crossZFW.center = CGPointMake( xCGpos, yCGpos);
    
    return;
    
    
    
}

- (void) animateCrossLDW {
    
    float xCGpos = leftBorderOfMeasureBox + ( (CGLongLDW -xAxisLeft) * xPixelFactor );
    float yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - weightLDW ) * yPixelFactor );
    if (isnan(xCGpos)) {
        xCGpos = 0;
    }
    if (isnan(yCGpos)) {
        yCGpos = 0;
    }
    crossLDW.center = CGPointMake( xCGpos, yCGpos);
    
    return;
    
}





- (void) animateCrossTOWforMail {
    
    float xCGpos = leftBorderOfMeasureBox2 + ( (CGLongTOW -xAxisLeft2) * xPixelFactor2 );
    float yCGpos = topBorderOfMeasureBox2  + (  (yAxisTop2 - weightTOW ) * yPixelFactor2 );
    if (isnan(xCGpos)) {
        xCGpos = 0;
    }
    if (isnan(yCGpos)) {
        yCGpos = 0;
    }
    _crossMailTow.center = CGPointMake( xCGpos, yCGpos);
    
    return;
    
    
    
    
    return;
    
    
    
}

- (void) animateCrossZFWforMail {
    
    
    float xCGpos = leftBorderOfMeasureBox2 + ( (CGLongZFW -xAxisLeft2) * xPixelFactor2 );
    float yCGpos = topBorderOfMeasureBox2  + (  (yAxisTop2 - weightZFW ) * yPixelFactor2 );
    if (isnan(xCGpos)) {
        xCGpos = 0;
    }
    if (isnan(yCGpos)) {
        yCGpos = 0;
    }
    
    
    _crossMailZFW.center = CGPointMake( xCGpos, yCGpos);
    
    
    
    
    
    
    return;
    
    
    
}

- (void) animateCrossLDWforMail {
    
    
    float xCGpos = leftBorderOfMeasureBox2 + ( (CGLongLDW -xAxisLeft2) * xPixelFactor2 );
    float yCGpos = topBorderOfMeasureBox2  + (  (yAxisTop2 - weightLDW ) * yPixelFactor2 );
    if (isnan(xCGpos)) {
        xCGpos = 0;
    }
    if (isnan(yCGpos)) {
        yCGpos = 0;
    }
    
    
    _crossMailLDW.center = CGPointMake( xCGpos, yCGpos);
    
    
    
    
    
    
    return;
    
    
    
}



- (void) animateCrossLAT {
    
    
    
    
    float xCGpos = leftBorderOfMeasureBoxLAT + ( (CGLATTOW -xAxisLeftLAT) * xPixelFactorLAT );
    float yCGpos = topBorderOfMeasureBoxLAT  + (  (yAxisTopLAT - weightTOW ) * yPixelFactorLAT );
    
    if (flagLATinputH130 == 1) {
        xCGpos = leftBorderOfMeasureBoxLAT + ( (CGLongTOW -xAxisLeftLAT) * xPixelFactorLAT );
        yCGpos = topBorderOfMeasureBoxLAT  + (  (yAxisTopLAT - CGLATTOW ) * yPixelFactorLAT );
    }
    if (isnan(xCGpos)) {
        xCGpos = 0;
    }
    if (isnan(yCGpos)) {
        yCGpos = 0;
    }
    
    crossLatTOW.center = CGPointMake( xCGpos, yCGpos);
    
    return;
    
}

- (void) animateCrossLATLDW {
    
    
    
    
    float xCGpos = leftBorderOfMeasureBoxLAT + ( (CGLATLDW -xAxisLeftLAT) * xPixelFactorLAT );
    float yCGpos = topBorderOfMeasureBoxLAT  + (  (yAxisTopLAT - weightLDW ) * yPixelFactorLAT );
    
    if (flagLATinputH130 == 1) {
        xCGpos = leftBorderOfMeasureBoxLAT + ( (CGLongLDW -xAxisLeftLAT) * xPixelFactorLAT );
        yCGpos = topBorderOfMeasureBoxLAT  + (  (yAxisTopLAT - CGLATLDW ) * yPixelFactorLAT );
    }
    if (isnan(xCGpos)) {
        xCGpos = 0;
    }
    if (isnan(yCGpos)) {
        yCGpos = 0;
    }
    
    _crossLatLDW.center = CGPointMake( xCGpos, yCGpos);
    
    return;
    
}


- (void) animateCrossLATZFW {
    
    
    
    
    float xCGpos = leftBorderOfMeasureBoxLAT + ( (CGLATZFW -xAxisLeftLAT) * xPixelFactorLAT );
    float yCGpos = topBorderOfMeasureBoxLAT  + (  (yAxisTopLAT - weightZFW ) * yPixelFactorLAT );
    
    if (flagLATinputH130 == 1) {
        xCGpos = leftBorderOfMeasureBoxLAT + ( (CGLongZFW -xAxisLeftLAT) * xPixelFactorLAT );
        yCGpos = topBorderOfMeasureBoxLAT  + (  (yAxisTopLAT - CGLATZFW ) * yPixelFactorLAT );
    }
    
    if (isnan(xCGpos)) {
        xCGpos = 0;
    }
    if (isnan(yCGpos)) {
        yCGpos = 0;
    }
    _crossLatZFW.center = CGPointMake( xCGpos, yCGpos);
    
    return;
    
}


- (void) animateCrossLATforMail {
    
    
    
    
    float xCGpos = leftBorderOfMeasureBoxLAT2 + ( (CGLATTOW -xAxisLeftLAT2) * xPixelFactorLAT2 );
    float yCGpos = topBorderOfMeasureBoxLAT2  + (  (yAxisTopLAT2 - weightTOW ) * yPixelFactorLAT2 );
    
    if (flagLATinputH130 == 1) {
        xCGpos = leftBorderOfMeasureBoxLAT2 + ( (CGLongTOW -xAxisLeftLAT2) * xPixelFactorLAT2 );
        yCGpos = topBorderOfMeasureBoxLAT2  + (  (yAxisTopLAT2 - CGLATTOW ) * yPixelFactorLAT2 );
    }
    if (isnan(xCGpos)) {
        xCGpos = 0;
    }
    if (isnan(yCGpos)) {
        yCGpos = 0;
    }
    _crossMailLAT.center = CGPointMake( xCGpos, yCGpos);
    
    return;
    
}


- (void) animateCrossLATforMail_LDW {
    
    
    
    
    float xCGpos = leftBorderOfMeasureBoxLAT2 + ( (CGLATLDW -xAxisLeftLAT2) * xPixelFactorLAT2 );
    float yCGpos = topBorderOfMeasureBoxLAT2  + (  (yAxisTopLAT2 - weightLDW ) * yPixelFactorLAT2 );
    
    if (flagLATinputH130 == 1) {
        xCGpos = leftBorderOfMeasureBoxLAT2 + ( (CGLongLDW -xAxisLeftLAT2) * xPixelFactorLAT2 );
        yCGpos = topBorderOfMeasureBoxLAT2  + (  (yAxisTopLAT2 - CGLATLDW ) * yPixelFactorLAT2 );
    }
    
    if (isnan(xCGpos)) {
        xCGpos = 0;
    }
    if (isnan(yCGpos)) {
        yCGpos = 0;
    }
    
    _crossMailLATLDW.center = CGPointMake( xCGpos, yCGpos);
    
    return;
    
}

- (void) animateCrossLATforMail_ZFW {
    
    
    
    
    float xCGpos = leftBorderOfMeasureBoxLAT2 + ( (CGLATZFW -xAxisLeftLAT2) * xPixelFactorLAT2 );
    float yCGpos = topBorderOfMeasureBoxLAT2  + (  (yAxisTopLAT2 - weightZFW ) * yPixelFactorLAT2 );
    
    if (flagLATinputH130 == 1) {
        xCGpos = leftBorderOfMeasureBoxLAT2 + ( (CGLongZFW -xAxisLeftLAT2) * xPixelFactorLAT2 );
        yCGpos = topBorderOfMeasureBoxLAT2  + (  (yAxisTopLAT2 - CGLATZFW ) * yPixelFactorLAT2 );
    }
    if (isnan(xCGpos)) {
        xCGpos = 0;
    }
    if (isnan(yCGpos)) {
        yCGpos = 0;
    }
    
    _crossMailLATZFW.center = CGPointMake( xCGpos, yCGpos);
    
    return;
    
}






- (void) drawCGenvelope {
    
    colorModeForCGenvelope =  0;
    

    
    [self.viewCGenvelopeFrame.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines and dots
    _viewMeasureCGenvelope.backgroundColor = [UIColor clearColor];
    
    if (colorModeForCGenvelope == 0) { _viewCGenvelopeFrame.backgroundColor = [UIColor clearColor];  }else{ _viewCGenvelopeFrame.backgroundColor = [UIColor whiteColor];    }
    
   //NSLog(@"_arrayCG1 %@", _arrayCG1 );
    //NSLog(@"factorApplyToNativeDistanceInchMM %.3f", factorApplyToNativeDistanceInchMM );
    
    // CG x and y labels
    float xIncrement = 0;
    float yIncrement = 0;
    float fontSize = 0;
    if ([_arrayCG1 count] > 0) {
        xAxisLeft     = [[_arrayCG1 objectAtIndex: 0 ] floatValue];
        if ([_arrayCG1 count] > 1) {
            xAxisRight    = [[_arrayCG1 objectAtIndex: 1 ] floatValue];
        }
        if ([_arrayCG1 count] > 2) {
            xIncrement    = [[_arrayCG1 objectAtIndex: 2 ] floatValue];
        }
        if ([_arrayCG1 count] > 3) {
            yAxisBottom   = [[_arrayCG1 objectAtIndex: 3 ] floatValue];
        }
        if ([_arrayCG1 count] > 4) {
            yAxisTop      = [[_arrayCG1 objectAtIndex: 4 ] floatValue];
        }
        if ([_arrayCG1 count] > 5) {
             yIncrement    = [[_arrayCG1 objectAtIndex: 5 ] floatValue];
        }
        if ([_arrayCG1 count] > 6) {
            fontSize     = [[_arrayCG1 objectAtIndex: 6 ] floatValue];
        }
    }
    
    
    
    // statics
    float labelWidth = 90;
    float labelHeight = 15;
    float xPos = 0, yPos = 0;
    
    leftBorderOfMeasureBox =   _viewMeasureCGenvelope.center.x - (_viewMeasureCGenvelope.layer.frame.size.width / 2.0) ;
    measureBoxWidth = _viewMeasureCGenvelope.layer.frame.size.width;
    
    float xIncrementValue = 0;
    float xIncrementPixel = 0;
    if (xIncrement !=0 && xAxisLeft !=0) {
        //NSLog(@"here !!!!");
        xIncrementValue = (xAxisRight - xAxisLeft) / xIncrement;
        xIncrementPixel = measureBoxWidth / xIncrement;
    }
    
    //NSLog(@"xAxisLeft %.1f",xAxisLeft);
    //NSLog(@"xIncrement %.1f",xIncrement);
    //NSLog(@"measureBoxWidth %.1f",measureBoxWidth);
    //NSLog(@"xIncrementPixel %.1f",xIncrementPixel);
    
    topBorderOfMeasureBox =   _viewMeasureCGenvelope.center.y - (_viewMeasureCGenvelope.layer.frame.size.height / 2.0) ;
    measureBoxHeight = _viewMeasureCGenvelope.layer.frame.size.height;
    
    float yIncrementValue = 0;
    float yIncrementPixel = 0;
    if (yIncrement !=0 && yAxisBottom !=0) {
        yIncrementValue = (yAxisTop - yAxisBottom) / yIncrement;
        yIncrementPixel = measureBoxHeight / yIncrement;
    }
    
    // make X labels
    int numberOfXLines = 0;
    for (int i = 0; i < xIncrement+1 ; i++) {
        numberOfXLines = numberOfXLines +1;
    }

    //NSLog(@"numberOfXLines %d",numberOfXLines);
    
    
    //NSLog(@"xIncrement %.1f",xIncrement);
   
    
    for (int i = 0; i < xIncrement+1 ; i++) {
        
        if (numberOfXLines > 8 ) {
            if (i %2) {
                continue;
            }
        }
        
        if (xAxisLeft + ( xIncrementValue * i) > xAxisRight) {
            // plot labels only if fit in frame
            continue;
        }
        
        
        
        xPos =  leftBorderOfMeasureBox + (xIncrementPixel * i);
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(xPos-(labelWidth/2), topBorderOfMeasureBox - labelHeight-2, labelWidth, labelHeight)];
        label.textAlignment = NSTextAlignmentCenter;
        if (colorModeForCGenvelope == 0) { label.textColor = [UIColor whiteColor];  }else{ label.textColor = [UIColor blackColor];    }
        label.font = [UIFont boldSystemFontOfSize:fontSize];
        NSString *labelFormat;
        
        //NSLog(@"xPos %.1f", xPos);
              
              
        if ([selectedUnitForItems isEqualToString:@"kg"]) {
            labelFormat = @"[mm]";
            if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
                labelFormat = @"[m]";
            }
        }else{
            labelFormat = @"[In]";
        }
        
        if (i == 0) {
            NSString *labelText = [ [NSString alloc] initWithFormat:labelFormat, xAxisLeft + ( xIncrementValue * i)  ];
            [label  setText: labelText  ];
        }else{
            NSString *labelText;
            if ([selectedUnitForItems isEqualToString:@"kg"]) {
                // millimeter                
                labelText = [ [NSString alloc] initWithFormat:@"%.0f", (xAxisLeft + ( xIncrementValue * i)) * factorApplyToNativeDistanceInchMM ];    
                //NSLog(@"1 labelText %@", labelText );
                if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {                    
                    // meter
                    //NSLog(@"2 labelText %@", labelText );
                    labelText = [ [NSString alloc] initWithFormat:@"%.2f", (xAxisLeft + ( xIncrementValue * i)) * factorApplyToNativeDistanceInchMM  ];
                }
            }else{
                // inches
                labelText = [ [NSString alloc] initWithFormat:@"%.1f", (xAxisLeft + ( xIncrementValue * i)) * factorApplyToNativeDistanceInchMM  ];
                //NSLog(@"3 labelText %@", labelText );
            }           
            [label  setText: labelText  ];
             //NSLog(@"labelText %@", labelText);
        }
        
        [_viewCGenvelopeFrame addSubview: label];
       
    }
    
    
    
    // make X lines
    
    for (int i = 0; i < xIncrement+1 ; i++) {
        xPos =  leftBorderOfMeasureBox + (xIncrementPixel * i);
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( xPos, topBorderOfMeasureBox )];
        [path addLineToPoint:CGPointMake( xPos, topBorderOfMeasureBox+ measureBoxHeight  )  ];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        if (colorModeForCGenvelope == 0) { shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];;  }else{ shapeLayer.strokeColor = [[UIColor blackColor] CGColor];    }
        shapeLayer.lineWidth = 0.5;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [self.viewCGenvelopeFrame.layer addSublayer:shapeLayer];
        
    }
    
    
    // make y labels
    for (int i = 0; i < yIncrement+1 ; i++) {
        
        if (i == 0) { // make first label the LBS label
            
            yPos =  topBorderOfMeasureBox + (yIncrementPixel * i);
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(leftBorderOfMeasureBox-labelWidth-4, yPos-(labelHeight/2)+(yIncrementPixel/3), labelWidth, labelHeight)];
            label.textAlignment = NSTextAlignmentRight;
            if (colorModeForCGenvelope == 0) { label.textColor = [UIColor whiteColor];  }else{ label.textColor = [UIColor blackColor];    }
            label.font = [UIFont boldSystemFontOfSize:fontSize];
            NSString *labelText;
            
            if ([selectedUnitForItems isEqualToString:@"kg"]) {
                labelText = @"[kg]";
            }else{
                labelText = @"[lbs]";
            }

            [label  setText: labelText  ];
            [_viewCGenvelopeFrame addSubview: label];
            
            
        }else{
            
            yPos =  topBorderOfMeasureBox + (yIncrementPixel * i);
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(leftBorderOfMeasureBox-labelWidth-4, yPos-(labelHeight/2), labelWidth, labelHeight)];
            label.textAlignment = NSTextAlignmentRight;
            if (colorModeForCGenvelope == 0) { label.textColor = [UIColor whiteColor];  }else{ label.textColor = [UIColor blackColor];    }
            label.font = [UIFont boldSystemFontOfSize:fontSize];
            
            NSString *labelText = [ [NSString alloc] initWithFormat:@"%.0f", (yAxisTop - ( yIncrementValue * i)) * factorApplyToNativeWeightforItems  ];
            [label  setText: labelText  ];
            [_viewCGenvelopeFrame addSubview: label];
        }
        
    }
  
    
    // make y lines
    for (int i = 0; i < yIncrement+1 ; i++) {
        
        yPos =  topBorderOfMeasureBox + (yIncrementPixel * i);
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( leftBorderOfMeasureBox, yPos )];
        [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox+ measureBoxWidth, yPos  )  ];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        if (colorModeForCGenvelope == 0) { shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];;  }else{ shapeLayer.strokeColor = [[UIColor blackColor] CGColor];    }
        shapeLayer.lineWidth = 0.5;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [self.viewCGenvelopeFrame.layer addSublayer:shapeLayer];
    }
    
    
    
    // make frame
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake( leftBorderOfMeasureBox, topBorderOfMeasureBox )];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox+ measureBoxWidth, topBorderOfMeasureBox  )  ];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox+ measureBoxWidth, topBorderOfMeasureBox+measureBoxHeight  )  ];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox, topBorderOfMeasureBox+measureBoxHeight  )  ];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox, topBorderOfMeasureBox  )  ];
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    if (colorModeForCGenvelope == 0) { shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];;  }else{ shapeLayer.strokeColor = [[UIColor blackColor] CGColor];    }
    shapeLayer.lineWidth = 1.5;
    shapeLayer.fillColor = [[UIColor clearColor] CGColor];
    [self.viewCGenvelopeFrame.layer addSublayer:shapeLayer];
    
    
    
    
    float numberOfPoints = 0;
    xPixelFactor = measureBoxWidth  / (xAxisRight-xAxisLeft);
    yPixelFactor = measureBoxHeight / (yAxisTop-yAxisBottom);
    
    // ******************************************************************************************************
    // ******************************************************************************************************
    
    // cge1
    // dotted envelope 1 for margin
    
    // ******************************************************************************************************
    // ******************************************************************************************************
    
    

    if ( [[_arrayName23 objectAtIndex:25] isEqualToString:@"yes"]) {
        
        //NSLog(@"margin ************************");
        
        // make dotted CG line
        
        float marginCGx = [_inputSafetyMargin.text floatValue] * xPixelFactor;
        
       
        
        UIBezierPath *pathCGline = [UIBezierPath bezierPath];
        
        numberOfPoints = 0;
        
        int flagfirstMoveToRight = 0;
        
        for (int i = 7; i < _arrayCG1MarginLine.count ; i++) {
            
            NSString *Xstring     = [_arrayCG1MarginLine objectAtIndex: i ];
            NSString *searchKeyword = @"/";
            NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
            
            if ([Xstring isEqualToString: @""]) {
                break;
            }
            
            NSString *XstringNext     = [_arrayCG1MarginLine objectAtIndex: i+1];
            if ([XstringNext isEqualToString: @""]) {
                XstringNext = Xstring;
            }
            
            searchKeyword = @"/";
            NSRange rangeOfYourStringNext = [XstringNext rangeOfString:searchKeyword];
            
            xVal = @"";
            yVal = @"";
            
            NSString *xValNext = @"";
            NSString *yValNext = @"";
            
            
            float xCGpos = 0;
            float yCGpos = 0;
            
            float xCGposNext = 0;
            float yCGposNext = 0;

            
            float xCGposMargined = 0;
            float yCGposMargined = 0;

            
            
            if(rangeOfYourString.location == NSNotFound)
            {
                // error condition — the text searchKeyword wasn't in 'string'
            }
            else{
                
                 //NSLog(@"------");
                
                
                xVal = [Xstring substringToIndex:rangeOfYourString.location];
                yVal = [Xstring substringFromIndex:rangeOfYourString.location+1];
                
                xValNext = [XstringNext substringToIndex:rangeOfYourStringNext.location];
                yValNext = [XstringNext substringFromIndex:rangeOfYourStringNext.location+1];
                
                //NSLog(@"xVal %@", xVal);
                //NSLog(@"xValNext %@", xValNext);
                
                xCGpos = leftBorderOfMeasureBox + ( ([xVal floatValue]-xAxisLeft) * xPixelFactor );
                yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - [yVal floatValue]) * yPixelFactor );
                
                xCGposNext = leftBorderOfMeasureBox + ( ([xValNext floatValue]-xAxisLeft) * xPixelFactor );
                yCGposNext = topBorderOfMeasureBox  + (  (yAxisTop - [yValNext floatValue]) * yPixelFactor );
                
               
                int caseIsFound = 0;
                
                
                //NSLog(@"xCGpos %f", xCGpos);
                
                if (xCGpos < xCGposNext & yCGpos > yCGposNext) {
                    caseIsFound = 1;                    
                    //NSLog(@"moving to the right and up" );
                    xCGposMargined = xCGpos + marginCGx ;
                    yCGposMargined = yCGpos;
                }
                
                if (xCGpos == xCGposNext & yCGpos > yCGposNext) {
                    caseIsFound = 1;
                    //NSLog(@"not moving and up" );
                    xCGposMargined = xCGpos + marginCGx ;
                    yCGposMargined = yCGpos;
                }
                
                if (xCGpos == xCGposNext & yCGpos < yCGposNext) {
                    caseIsFound = 1;
                    //NSLog(@"not moving and down" );
                    xCGposMargined = xCGpos - marginCGx;
                    yCGposMargined = yCGpos;
                }
                
                
                if (xCGpos < xCGposNext & yCGpos == yCGposNext) {
                    caseIsFound = 1;
                    //NSLog(@"moving to the right and steady" );
                    xCGposMargined = xCGpos + marginCGx;
                    yCGposMargined = yCGpos;
                    if (flagfirstMoveToRight == 0) {
                        //NSLog(@"moving to the right and steady first time" );
                        xCGposMargined = xCGpos + marginCGx;
                        yCGposMargined = yCGpos;
                        flagfirstMoveToRight = 1;
                    }else{
                        //NSLog(@"moving to the right and steady second time " );
                        xCGposMargined = xCGpos - marginCGx;
                        yCGposMargined = yCGpos;
                    }
                }
                
                
                if (xCGpos < xCGposNext & yCGpos < yCGposNext) {
                    caseIsFound = 1;
                    //NSLog(@"moving to the right and down" );
                    xCGposMargined = xCGpos - marginCGx;
                    yCGposMargined = yCGpos;
                }
                
                if (xCGpos > xCGposNext & yCGpos == yCGposNext) {
                    caseIsFound = 1;
                    //NSLog(@"moving to the left  and steady" );
                    xCGposMargined = xCGpos - marginCGx;
                    yCGposMargined = yCGpos;
                }
                
                if (xCGpos > xCGposNext & yCGpos > yCGposNext) {
                    caseIsFound = 1;
                    //NSLog(@"moving to the left and up" );
                    xCGposMargined = xCGpos + marginCGx;
                    yCGposMargined = yCGpos;
                }
                
                if (xCGpos > xCGposNext & yCGpos < yCGposNext) {
                    caseIsFound = 1;
                    //NSLog(@"moving to the left and down" );
                    xCGposMargined = xCGpos - marginCGx;
                    yCGposMargined = yCGpos;
                }
                
                
                if (xCGpos == xCGposNext & yCGpos == yCGposNext) {
                    caseIsFound = 1;
                    //NSLog(@"moving back to start" );
                    xCGposMargined = xCGpos + marginCGx;
                    yCGposMargined = yCGpos;
                    
                }

                if (caseIsFound == 0) {
                    //NSLog(@"---------------------------------------------- view caseIsFound 0");
                }
                
                //NSLog(@"xCGposMargined %f", xCGposMargined);
                if (numberOfPoints == 0) {
                    [pathCGline moveToPoint:CGPointMake( xCGposMargined, yCGposMargined )];
                   
                }else{
                     [pathCGline addLineToPoint:CGPointMake( xCGposMargined, yCGposMargined )];
                }
                
                              numberOfPoints = numberOfPoints + 1;
                
                
            }// end add to path
            
            
            
        }// end for next make path
        
        
        
        shapeLayerCGMargin = [CAShapeLayer layer];
        shapeLayerCGMargin.path = [pathCGline CGPath];
        
        shapeLayerCGMargin.lineWidth = 1.5;
        shapeLayerCGMargin.fillColor = [[UIColor clearColor] CGColor];
        
        [shapeLayerCGMargin setLineDashPattern:
        [NSArray arrayWithObjects:[NSNumber numberWithInt:10],
        [NSNumber numberWithInt:5],nil]];
        
        //[self.viewCGenvelopeFrame.layer addSublayer:shapeLayerCGMargin];
        
      } // end if check margin
    
    
    
    
    
    // ******************************************************************************************************
    // ******************************************************************************************************
    // cge1
    // envelope 1
    
    numberOfPoints = 0;
    UIBezierPath *pathCG = [UIBezierPath bezierPath];
    
    for (int i = 7; i < _arrayCG1.count ; i++) { /// make path
        
        // get point coordinates
        NSString *Xstring     = [_arrayCG1 objectAtIndex: i ];
        NSString *searchKeyword = @"/";
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];        
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        xVal = @"";
        yVal = @"";
        float xCGpos = 0;
        float yCGpos = 0;
        
        if(rangeOfYourString.location == NSNotFound)
        {
            // error condition — the text searchKeyword wasn't in 'string'
        }
        else{
            xVal = [Xstring substringToIndex:rangeOfYourString.location];
            yVal = [Xstring substringFromIndex:rangeOfYourString.location+1];
            
            if (numberOfPoints == 0) { // first point only
                xCGpos = leftBorderOfMeasureBox + ( ([xVal floatValue]-xAxisLeft) * xPixelFactor );
                yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - [yVal floatValue]) * yPixelFactor );
                [pathCG moveToPoint:CGPointMake( xCGpos, yCGpos )];
            }else{
                xCGpos = leftBorderOfMeasureBox + ( ([xVal floatValue]-xAxisLeft) * xPixelFactor );
                yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - [yVal floatValue]) * yPixelFactor );
                [pathCG addLineToPoint:CGPointMake( xCGpos, yCGpos )];
            }
            numberOfPoints = numberOfPoints + 1;
        }// end add to path
    }// end for next make path
    
    shapeLayerCG1 = [CAShapeLayer layer];
    shapeLayerCG1.path = [pathCG CGPath];
    shapeLayerCG1.lineWidth = 3.5;
    shapeLayerCG1.fillColor = [[UIColor clearColor] CGColor];
   
    
    // ******************************************************************************************************
    // ******************************************************************************************************
    // cge2
    // envelope 2
    
    numberOfPoints = 0;
    pathCG = [UIBezierPath bezierPath];
    
    for (int i = 7; i < _arrayCG2.count ; i++) { /// make path
        
        // get point coordinates
        NSString *Xstring     = [_arrayCG2 objectAtIndex: i ];
        NSString *searchKeyword = @"/";
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        xVal = @"";
        yVal = @"";
        float xCGpos = 0;
        float yCGpos = 0;
        
        if(rangeOfYourString.location == NSNotFound)
        {
            // error condition — the text searchKeyword wasn't in 'string'
        }
        else{
            xVal = [Xstring substringToIndex:rangeOfYourString.location];
            yVal = [Xstring substringFromIndex:rangeOfYourString.location+1];
            
            if (numberOfPoints == 0) { // first point only
                xCGpos = leftBorderOfMeasureBox + ( ([xVal floatValue]-xAxisLeft) * xPixelFactor );
                yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - [yVal floatValue]) * yPixelFactor );
                [pathCG moveToPoint:CGPointMake( xCGpos, yCGpos )];
            }else{
                xCGpos = leftBorderOfMeasureBox + ( ([xVal floatValue]-xAxisLeft) * xPixelFactor );
                yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - [yVal floatValue]) * yPixelFactor );
                [pathCG addLineToPoint:CGPointMake( xCGpos, yCGpos )];
            }
            numberOfPoints = numberOfPoints + 1;
        }// end add to path
    }// end for next make path
    
    shapeLayerCG2 = [CAShapeLayer layer];
    shapeLayerCG2.path = [pathCG CGPath];
    shapeLayerCG2.lineWidth = 3.5;
    shapeLayerCG2.fillColor = [[UIColor clearColor] CGColor];
    
    [self.viewCGenvelopeFrame.layer addSublayer:shapeLayerCG2];
    
    [self.viewCGenvelopeFrame.layer addSublayer:shapeLayerCG1];
    

    
    
    
     
    // ******************************************************************************************************
    // ******************************************************************************************************
    
    
    
    /// make dots
    for (int i = 7; i < _arrayCG1.count ; i++) { /// make dots
        // get point coordinates
        NSString *Xstring     = [_arrayCG1 objectAtIndex: i ];
        NSString *searchKeyword = @"/";
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        xVal = @"";
        yVal = @"";
        float xCGpos = 0;
        float yCGpos = 0;
        
        if(rangeOfYourString.location == NSNotFound)
        {            // error condition — the text searchKeyword wasn't in 'string'
        }
        else{
            xVal = [Xstring substringToIndex:rangeOfYourString.location];
            yVal = [Xstring substringFromIndex:rangeOfYourString.location+1];
            xCGpos = leftBorderOfMeasureBox + ( ([xVal floatValue]-xAxisLeft) * xPixelFactor );
            yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - [yVal floatValue]) * yPixelFactor );
            float dotSize = 10;
            CAShapeLayer *circleLayer = [CAShapeLayer layer];
            [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];
            [circleLayer setPosition:CGPointMake( xCGpos, yCGpos)];
            // Create a circle path.
            UIBezierPath *pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)];
            // Set the path on the layer
            [circleLayer setPath:[pathC CGPath]];
            // Set the stroke color
            [circleLayer setStrokeColor:[[UIColor blackColor] CGColor]];
            [circleLayer setFillColor:[[UIColor whiteColor] CGColor]];
            // Set the stroke line width
            [circleLayer setLineWidth:2.0f];
            [self.viewCGenvelopeFrame.layer addSublayer:circleLayer];
            
            if (flagShowCGEnvelopeValues == 1) {
                // make labels
                float labelHeight = 12;                
               
                UILabel *label = [[UILabel alloc] init];
                NSString *labelText = @"";            
                label.font = [UIFont systemFontOfSize:11];
                label.textAlignment = NSTextAlignmentCenter;
                label.textColor = [UIColor whiteColor];
                label.backgroundColor = [UIColor blackColor];             
                if (([xVal floatValue]*factorApplyToNativeDistanceInchMM) < 1000) {
                    labelText = [[NSString alloc] initWithFormat:@"%.1f", [xVal floatValue] *  factorApplyToNativeDistanceInchMM ];
                }else{
                    labelText = [[NSString alloc] initWithFormat:@"%.0f", [xVal floatValue] *  factorApplyToNativeDistanceInchMM ];
                }
                [label  setText: labelText];
               
                                
                float labelWidth = labelText.length * 8 ;
                label.frame = CGRectMake(xCGpos - (labelWidth/2), yCGpos - labelHeight-8 , labelWidth, labelHeight);
                [self.viewCGenvelopeFrame addSubview:label];                
                labelHeight = 12;
                label = [[UILabel alloc] init];
                label.font = [UIFont systemFontOfSize:11];
                label.textAlignment = NSTextAlignmentCenter;
                label.textColor = [UIColor whiteColor];
                label.backgroundColor = [UIColor blackColor];
                labelText = @"";
                if (([yVal floatValue]*factorApplyToNativeWeightforItems) < 1000) {
                    labelText = [[NSString alloc] initWithFormat:@"%.1f", [yVal floatValue] *  factorApplyToNativeWeightforItems ];
                }else{
                    labelText = [[NSString alloc] initWithFormat:@"%.0f", [yVal floatValue] *  factorApplyToNativeWeightforItems ];
                }
                [label  setText: labelText];
                labelWidth = labelText.length * 8 ;
                label.frame = CGRectMake(xCGpos - labelWidth - 8, yCGpos - (labelHeight/2) , labelWidth, labelHeight);
                [self.viewCGenvelopeFrame addSubview:label];
            }
        }// end add to path
        
    }// end for next make path
    
    if (flagShowCGEnvelopeValues == 1){
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(leftBorderOfMeasureBox+2, topBorderOfMeasureBox + 1 ,  measureBoxWidth-3, 17)];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor darkGrayColor];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:12];
        [label  setText: @"Longitudinal C.G." ];
        [_viewCGenvelopeFrame addSubview: label];
        
    }
    
    
   
    if ([trialCheck isEqualToString:@"isATrial"]) {
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(0, _viewCGenvelopeFrame.frame.size.height/2, _viewCGenvelopeFrame.frame.size.width, 20)];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor grayColor];
        label.textColor =yellowSpecialColor;
        label.font = [UIFont systemFontOfSize:16];
        [label  setText: @"TRIAL - NOT FOR FLIGHT PLANNING!" ];
        [_viewCGenvelopeFrame addSubview: label];
    }
    

    return;
    
    
    
}

- (void) drawCGenvelopeManifest {
   
    
    colorModeForCGenvelope =  1;
    [self.viewCGenvelopeFrame2.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines
    _viewMeasureCGenvelope2.backgroundColor = [UIColor clearColor];
    if (colorModeForCGenvelope == 0) { _viewCGenvelopeFrame2.backgroundColor = [UIColor blackColor];  }else{ _viewCGenvelopeFrame2.backgroundColor = [UIColor whiteColor];    }
    
    // CG x and y labels
    float xIncrement = 0;
    float yIncrement = 0;
    float fontSize = 0;
    if ([_arrayCG1 count] > 0) {
        xAxisLeft2     = [[_arrayCG1 objectAtIndex: 0 ] floatValue];
        if ([_arrayCG1 count] > 1) {
            xAxisRight2    = [[_arrayCG1 objectAtIndex: 1 ] floatValue];
        }
        if ([_arrayCG1 count] > 2) {
           xIncrement    = [[_arrayCG1 objectAtIndex: 2 ] floatValue];
        }
        if ([_arrayCG1 count] > 3) {
            yAxisBottom2   = [[_arrayCG1 objectAtIndex: 3 ] floatValue];
        }
        if ([_arrayCG1 count] > 4) {
            yAxisTop2      = [[_arrayCG1 objectAtIndex: 4 ] floatValue];
        }
        if ([_arrayCG1 count] > 5) {
            yIncrement    = [[_arrayCG1 objectAtIndex: 5 ] floatValue];
        }
        if ([_arrayCG1 count] > 6) {
            fontSize     = [[_arrayCG1 objectAtIndex: 6 ] floatValue];
        }
    }
    
    
    // statics
    float labelWidth = 50;
    float labelHeight = 15;
    float xPos = 0, yPos = 0;
    
    leftBorderOfMeasureBox2 =   _viewMeasureCGenvelope2.center.x - (_viewMeasureCGenvelope2.layer.frame.size.width / 2.0) ;
    measureBoxWidth2 = _viewMeasureCGenvelope2.layer.frame.size.width;
    
    float xIncrementValue = 0;
    float xIncrementPixel = 0;
    if (xIncrement != 0 && xAxisLeft2 != 0) {
        xIncrementValue = (xAxisRight2 - xAxisLeft2) / xIncrement;
        xIncrementPixel = measureBoxWidth2 / xIncrement;
    }
    
    
    topBorderOfMeasureBox2 =   _viewMeasureCGenvelope2.center.y - (_viewMeasureCGenvelope2.layer.frame.size.height / 2.0) ;
    measureBoxHeight2 = _viewMeasureCGenvelope2.layer.frame.size.height;
    
    float yIncrementValue = 0;
    float yIncrementPixel = 0;
    if (xIncrement != 0 && yAxisBottom2 != 0) {
        yIncrementValue = ((yAxisTop2 - yAxisBottom2) / yIncrement);
        yIncrementPixel = measureBoxHeight2 / yIncrement;
    }
    
    /// make X labels
    int numberOfXLines = 0;
    
    for (int i = 0; i < xIncrement+1 ; i++) {
        numberOfXLines = numberOfXLines +1;
    }
    
    for (int i = 0; i < xIncrement+1 ; i++) {
        
        if (numberOfXLines > 8 ) {
            if (i %2) {
                continue;
            }
        }
        
        if (xAxisLeft + ( xIncrementValue * i) > xAxisRight) {
            // plot labels only if fit in frame
            continue;
        }
        
        
        xPos =  leftBorderOfMeasureBox2 + (xIncrementPixel * i);
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(xPos-(labelWidth/2), topBorderOfMeasureBox2 - labelHeight-2, labelWidth, labelHeight)];
        label.textAlignment = NSTextAlignmentCenter;
        if (colorModeForCGenvelope == 0) { label.textColor = [UIColor whiteColor];  }else{ label.textColor = [UIColor blackColor];    }
        label.font = [UIFont boldSystemFontOfSize:fontSize];
        
        if (i == 0) {
        
            if ([selectedUnitForItems isEqualToString:@"kg"]) {
                NSString *labelText = @"[mm]"; [label  setText: labelText  ];
                if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
                    labelText = @"[m]"; [label  setText: labelText  ];
                }
            }else{
                NSString *labelText = @"[In]"; [label  setText: labelText  ];
            }
        }else{
            
            
            
            NSString *labelText;
            if ([selectedUnitForItems isEqualToString:@"kg"]) {
                // millimeter                
                labelText = [ [NSString alloc] initWithFormat:@"%.0f", (xAxisLeft + ( xIncrementValue * i)) * factorApplyToNativeDistanceInchMM ];    
                //NSLog(@"1 labelText %@", labelText );
                if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {                    
                    // meter
                    //NSLog(@"2 labelText %@", labelText );
                    labelText = [ [NSString alloc] initWithFormat:@"%.2f", (xAxisLeft + ( xIncrementValue * i)) * factorApplyToNativeDistanceInchMM  ];
                }
            }else{
                // inches
                labelText = [ [NSString alloc] initWithFormat:@"%.1f", (xAxisLeft + ( xIncrementValue * i)) * factorApplyToNativeDistanceInchMM  ];
                //NSLog(@"3 labelText %@", labelText );
            }           
            [label  setText: labelText  ];
            
            
            
            
            
            
            
            
            
        }

        
        [_viewCGenvelopeFrame2 addSubview: label];
    }
    
    
    
    // make X lines
    
    for (int i = 0; i < xIncrement+1 ; i++) {
        
        xPos =  leftBorderOfMeasureBox2 + (xIncrementPixel * i);
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( xPos, topBorderOfMeasureBox2 )];
        [path addLineToPoint:CGPointMake( xPos, topBorderOfMeasureBox2+ measureBoxHeight2  )  ];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        if (colorModeForCGenvelope == 0) { shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];;  }else{ shapeLayer.strokeColor = [[UIColor blackColor] CGColor];    }
        shapeLayer.lineWidth = 0.5;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [self.viewCGenvelopeFrame2.layer addSublayer:shapeLayer];
        
    }
    
    
    
    
    
    // make y labels
    
    for (int i = 0; i < yIncrement+1 ; i++) {
        
        if (i == 0) { // make first label the LBS label
            yPos =  topBorderOfMeasureBox2 + (yIncrementPixel * i);
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(leftBorderOfMeasureBox2-labelWidth-4, yPos-(labelHeight/2)+(yIncrementPixel/3), labelWidth, labelHeight)];
            label.textAlignment = NSTextAlignmentRight;
            if (colorModeForCGenvelope == 0) { label.textColor = [UIColor whiteColor];  }else{ label.textColor = [UIColor blackColor];    }
            label.font = [UIFont boldSystemFontOfSize:fontSize];
            NSString *labelText;
            
            if ([selectedUnitForItems isEqualToString:@"kg"]) {
                 labelText = @"[kg]";
            }else{
                 labelText = @"[lbs]";
            }
            [label  setText: labelText  ];
            [_viewCGenvelopeFrame2 addSubview: label];
        }else{
            yPos =  topBorderOfMeasureBox2 + (yIncrementPixel * i);
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(leftBorderOfMeasureBox2-labelWidth-4, yPos-(labelHeight/2), labelWidth, labelHeight)];
            label.textAlignment = NSTextAlignmentRight;
            if (colorModeForCGenvelope == 0) { label.textColor = [UIColor whiteColor];  }else{ label.textColor = [UIColor blackColor];    }
            label.font = [UIFont boldSystemFontOfSize:fontSize];
            NSString *labelText = [ [NSString alloc] initWithFormat:@"%.0f", (yAxisTop - ( yIncrementValue * i)) * factorApplyToNativeWeightforItems  ];
            [label  setText: labelText  ];
            [_viewCGenvelopeFrame2 addSubview: label];
        }
        
        
    }
    
    
    // make y lines
    
    for (int i = 0; i < yIncrement+1 ; i++) {
        
        yPos =  topBorderOfMeasureBox2 + (yIncrementPixel * i);
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( leftBorderOfMeasureBox2, yPos )];
        [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox2+ measureBoxWidth2, yPos  )  ];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        if (colorModeForCGenvelope == 0) { shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];;  }else{ shapeLayer.strokeColor = [[UIColor blackColor] CGColor];    }
        shapeLayer.lineWidth = 0.5;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [self.viewCGenvelopeFrame2.layer addSublayer:shapeLayer];
    }
    
    
    
    // make frame
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    
    [path moveToPoint:CGPointMake( leftBorderOfMeasureBox2, topBorderOfMeasureBox2 )];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox2+ measureBoxWidth2, topBorderOfMeasureBox2  )  ];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox2+ measureBoxWidth2, topBorderOfMeasureBox2+measureBoxHeight2  )  ];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox2, topBorderOfMeasureBox2+measureBoxHeight2  )  ];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox2, topBorderOfMeasureBox2  )  ];
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    if (colorModeForCGenvelope == 0) { shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];;  }else{ shapeLayer.strokeColor = [[UIColor blackColor] CGColor];    }
    shapeLayer.lineWidth = 1.5;
    shapeLayer.fillColor = [[UIColor clearColor] CGColor];
    [self.viewCGenvelopeFrame2.layer addSublayer:shapeLayer];
    
    
    
    
    
    
    
    
    
    
    // ******************************************************************************************
    
    xPixelFactor2 = measureBoxWidth2  / (xAxisRight2-xAxisLeft2);
    
    yPixelFactor2 = measureBoxHeight2 / (yAxisTop2-yAxisBottom2);
    
    
    float numberOfPoints = 0;
    
    UIBezierPath *pathCG = [UIBezierPath bezierPath];
    
    for (int i = 7; i < _arrayCG1.count ; i++) {
        
        NSString *Xstring     = [_arrayCG1 objectAtIndex: i ];
        NSString *searchKeyword = @"/";
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        
        
        xValcg = @"";
        yValcg = @"";
        
        float xCGpos = 0;
        float yCGpos = 0;
        
        if(rangeOfYourString.location == NSNotFound)
        {
            // error condition — the text searchKeyword wasn't in 'string'
        }
        else{
            
            xValcg = [Xstring substringToIndex:rangeOfYourString.location];
            yValcg = [Xstring substringFromIndex:rangeOfYourString.location+1];
            
            
            if (numberOfPoints == 0) { // first point only
                xCGpos = leftBorderOfMeasureBox2 + ( ([xValcg floatValue]-xAxisLeft2) * xPixelFactor2 );
                yCGpos = topBorderOfMeasureBox2  + (  (yAxisTop2 - [yValcg floatValue]) * yPixelFactor2 );
                [pathCG moveToPoint:CGPointMake( xCGpos, yCGpos )];
                
            }else{
                
                xCGpos = leftBorderOfMeasureBox2 + ( ([xValcg floatValue]-xAxisLeft2) * xPixelFactor2 );
                yCGpos = topBorderOfMeasureBox2  + (  (yAxisTop2 - [yValcg floatValue]) * yPixelFactor2 );
                [pathCG addLineToPoint:CGPointMake( xCGpos, yCGpos )];
            }
            numberOfPoints = numberOfPoints + 1;
        }// end add to path
    }// end for next make path
    
    CAShapeLayer *shapeLayer1manifest = [CAShapeLayer layer];
    shapeLayer1manifest.path = [pathCG CGPath];
    shapeLayer1manifest.strokeColor = [[UIColor colorWithRed:255.0/255.0f green:218.0/255.0f blue:0.0/255.0f alpha:1.0f] CGColor];
    if (colorModeForCGenvelope == 0) {  shapeLayer1manifest.strokeColor =[[UIColor colorWithRed:255.0/255.0f green:218.0/255.0f blue:0.0/255.0f alpha:1.0f] CGColor];  }else{ shapeLayer1manifest.strokeColor = [[UIColor redColor] CGColor];    }
    shapeLayer1manifest.lineWidth = 3.5;
    shapeLayer1manifest.fillColor = [[UIColor clearColor] CGColor];
    [self.viewCGenvelopeFrame2.layer addSublayer:shapeLayer1manifest];
    
    
    
    // ******************************************************************************************
    
    xPixelFactor2 = measureBoxWidth2  / (xAxisRight2-xAxisLeft2);
    
    yPixelFactor2 = measureBoxHeight2 / (yAxisTop2-yAxisBottom2);
    
    
    numberOfPoints = 0;
    
    pathCG = [UIBezierPath bezierPath];
    
    for (int i = 7; i < _arrayCG2.count ; i++) {
        
        NSString *Xstring     = [_arrayCG2 objectAtIndex: i ];
        NSString *searchKeyword = @"/";
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        
        
        xValcg = @"";
        yValcg = @"";
        
        float xCGpos = 0;
        float yCGpos = 0;
        
        if(rangeOfYourString.location == NSNotFound)
        {
            // error condition — the text searchKeyword wasn't in 'string'
        }
        else{
            
            xValcg = [Xstring substringToIndex:rangeOfYourString.location];
            yValcg = [Xstring substringFromIndex:rangeOfYourString.location+1];
            
            
            if (numberOfPoints == 0) { // first point only
                xCGpos = leftBorderOfMeasureBox2 + ( ([xValcg floatValue]-xAxisLeft2) * xPixelFactor2 );
                yCGpos = topBorderOfMeasureBox2  + (  (yAxisTop2 - [yValcg floatValue]) * yPixelFactor2 );
                [pathCG moveToPoint:CGPointMake( xCGpos, yCGpos )];
                
            }else{
                
                xCGpos = leftBorderOfMeasureBox2 + ( ([xValcg floatValue]-xAxisLeft2) * xPixelFactor2 );
                yCGpos = topBorderOfMeasureBox2  + (  (yAxisTop2 - [yValcg floatValue]) * yPixelFactor2 );
                [pathCG addLineToPoint:CGPointMake( xCGpos, yCGpos )];
            }
            numberOfPoints = numberOfPoints + 1;
        }// end add to path
    }// end for next make path
    
    CAShapeLayer *shapeLayer2manifest = [CAShapeLayer layer];
    shapeLayer2manifest.path = [pathCG CGPath];
    shapeLayer2manifest.strokeColor = [[UIColor colorWithRed:255.0/255.0f green:218.0/255.0f blue:0.0/255.0f alpha:1.0f] CGColor];
    if (colorModeForCGenvelope == 0) {  shapeLayer2manifest.strokeColor =[[UIColor colorWithRed:255.0/255.0f green:218.0/255.0f blue:0.0/255.0f alpha:1.0f] CGColor];  }else{ shapeLayer2manifest.strokeColor = [[UIColor redColor] CGColor];    }
    shapeLayer2manifest.lineWidth = 3.5;
    shapeLayer2manifest.fillColor = [[UIColor clearColor] CGColor];
    [self.viewCGenvelopeFrame2.layer addSublayer:shapeLayer2manifest];

    
    
     // ******************************************************************************************
    
    
    
    
    
    
    
    
    
    
    
    for (int i = 7; i < _arrayCG1.count ; i++) { /// make dots
        
        
        // get point coordinates
        
        
        NSString *Xstring     = [_arrayCG1 objectAtIndex: i ];
        
        NSString *searchKeyword = @"/";
        
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
        
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        
        xValcg = @"";
        
        yValcg = @"";
        
        float xCGpos = 0;
        
        float yCGpos = 0;
        
        
        
        if(rangeOfYourString.location == NSNotFound)
        {
            // error condition — the text searchKeyword wasn't in 'string'
        }
        else{
            
            xValcg = [Xstring substringToIndex:rangeOfYourString.location];
            
            yValcg = [Xstring substringFromIndex:rangeOfYourString.location+1];
            
            
            
            
            xCGpos = leftBorderOfMeasureBox2 + ( ([xValcg floatValue]-xAxisLeft2) * xPixelFactor2 );
            yCGpos = topBorderOfMeasureBox2  + (  (yAxisTop2 - [yValcg floatValue]) * yPixelFactor2 );
            
            
            float dotSize = 7;
            
            
            CAShapeLayer *circleLayer = [CAShapeLayer layer];
            
            [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];
            
            [circleLayer setPosition:CGPointMake( xCGpos, yCGpos)];
            
            // Create a circle path.
            
            UIBezierPath *pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)];
            
            // Set the path on the layer
            [circleLayer setPath:[pathC CGPath]];
            
            
            // Set the stroke color
            [circleLayer setStrokeColor:[[UIColor blackColor] CGColor]];
            
            [circleLayer setFillColor:[[UIColor whiteColor] CGColor]];
            
            // Set the stroke line width
            [circleLayer setLineWidth:2.0f];
            
            
            [self.viewCGenvelopeFrame2.layer addSublayer:circleLayer];
            
            
            
            
            
            
        }// end add to path
        
        
        
        
    }// end for next make path
    
    
    if ([trialCheck isEqualToString:@"isATrial"]) {
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(0, _viewCGenvelopeFrame2.frame.size.height/2, _viewCGenvelopeFrame2.frame.size.width, 20)];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor grayColor];
        label.textColor =yellowSpecialColor;
        label.font = [UIFont systemFontOfSize:16];
        [label  setText: @"TRIAL - NOT FOR FLIGHT PLANNING!" ];
        [_viewCGenvelopeFrame2 addSubview: label];
    }
    
    
    return;
    
    
    
}

- (void) drawCGenvelopeLAT {
    
    colorModeForCGenvelope =  0;
    
    
    [self.viewCGenvelopeFrame_LAT.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines
    
    _viewMeasureCGenvelope_LAT.backgroundColor = [UIColor clearColor];
    if (colorModeForCGenvelope == 0) { _viewCGenvelopeFrame_LAT.backgroundColor = [UIColor clearColor];  }else{ _viewCGenvelopeFrame_LAT.backgroundColor = [UIColor whiteColor];    }
    
    
    // CG x and y labels
    float xIncrement    = 0;
    float yIncrement    = 0;
    float fontSize     = 0;
    if ([_arrayCG1_LAT count] > 0) {
        
        xAxisLeft     = [[_arrayCG1_LAT objectAtIndex: 0 ] floatValue];
        if ([_arrayCG1_LAT count] > 1) {
            xAxisRight    = [[_arrayCG1_LAT objectAtIndex: 1 ] floatValue];
        }
        if ([_arrayCG1_LAT count] > 2) {
            xIncrement    = [[_arrayCG1_LAT objectAtIndex: 2 ] floatValue];
        }
        if ([_arrayCG1_LAT count] > 3) {
            yAxisBottom   = [[_arrayCG1_LAT objectAtIndex: 3 ] floatValue];
        }
        if ([_arrayCG1_LAT count] > 4) {
            yAxisTop      = [[_arrayCG1_LAT objectAtIndex: 4 ] floatValue];
        }
        if ([_arrayCG1_LAT count] > 5) {
            yIncrement    = [[_arrayCG1_LAT objectAtIndex: 5 ] floatValue];
        }
        if ([_arrayCG1_LAT count] > 6) {
            fontSize     = [[_arrayCG1_LAT objectAtIndex: 6 ] floatValue];
        }
        
    }
    
    
    // statics
    float labelWidth = 70;
    float labelHeight = 15;
    float xPos = 0, yPos = 0;
    
    leftBorderOfMeasureBox =   _viewMeasureCGenvelope_LAT.center.x - (_viewMeasureCGenvelope_LAT.layer.frame.size.width / 2.0) ;
    measureBoxWidth = _viewMeasureCGenvelope_LAT.layer.frame.size.width;
    
    float xIncrementValue = 0;
    float xIncrementPixel = 0;
    if (xIncrement != 0 && xAxisLeft != 0) {
        xIncrementValue = (xAxisRight - xAxisLeft) / xIncrement;
        xIncrementPixel = measureBoxWidth / xIncrement;
    }
    
    topBorderOfMeasureBox =   _viewMeasureCGenvelope_LAT.center.y - (_viewMeasureCGenvelope_LAT.layer.frame.size.height / 2.0) ;
    measureBoxHeight = _viewMeasureCGenvelope_LAT.layer.frame.size.height;
    
    //NSLog(@"measureBoxHeight %.0f", measureBoxHeight);
    
    float yIncrementValue = 0;
    float yIncrementPixel = 0;
    if (yIncrement != 0 && yAxisBottom != 0) {
        yIncrementValue = (yAxisTop - yAxisBottom) / yIncrement;
        yIncrementPixel = measureBoxHeight / yIncrement;
    }
    
    // make X labels
    
    int numberOfXLines = 0;
    for (int i = 0; i < xIncrement+1 ; i++) {
        numberOfXLines = numberOfXLines +1;
    }
    
    
    for (int i = 0; i < xIncrement+1 ; i++) {
        
        if (numberOfXLines > 8 ) {
            if (i %2) {
                continue;
            }
        }
        
        
        if (xAxisLeft + ( xIncrementValue * i) > xAxisRight) {
            // plot labels only if fit in frame
            continue;
        }
        
        
        xPos =  leftBorderOfMeasureBox + (xIncrementPixel * i);
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(xPos-(labelWidth/2), topBorderOfMeasureBox - labelHeight-2, labelWidth, labelHeight)];
        label.textAlignment = NSTextAlignmentCenter;
        if (colorModeForCGenvelope == 0) { label.textColor = [UIColor whiteColor];  }else{ label.textColor = [UIColor blackColor];    }
        label.font = [UIFont boldSystemFontOfSize:fontSize];
        
        if (i == 0) {
            if ([selectedUnitForItems isEqualToString:@"kg"]) {
                NSString *labelText = @"[mm]"; [label  setText: labelText  ];
                if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
                    labelText = @"[m]"; [label  setText: labelText  ];
                }
            }else{
                NSString *labelText = @"[In]"; [label  setText: labelText  ];
            }
        }else{
            
            
            NSString *labelText = [ [NSString alloc] initWithFormat:@"%.0f", (xAxisLeft + ( xIncrementValue * i)) * factorApplyToNativeDistanceInchMM   ];
            // if meter
            if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
                labelText = [ [NSString alloc] initWithFormat:@"%.2f", xAxisLeft + ( xIncrementValue * i)  ];            }
            [label  setText: labelText  ];
            
            
            
            
        }
        
        
        [_viewCGenvelopeFrame_LAT addSubview: label];
    }
    
    
    
    // make X lines
    
    for (int i = 0; i < xIncrement+1 ; i++) {
        xPos =  leftBorderOfMeasureBox + (xIncrementPixel * i);
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( xPos, topBorderOfMeasureBox )];
        [path addLineToPoint:CGPointMake( xPos, topBorderOfMeasureBox+ measureBoxHeight  )  ];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        if (colorModeForCGenvelope == 0) { shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];;  }else{ shapeLayer.strokeColor = [[UIColor blackColor] CGColor];    }
        shapeLayer.lineWidth = 0.5;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [self.viewCGenvelopeFrame_LAT.layer addSublayer:shapeLayer];
    }
    
    
    
    
    
    // make y labels
    
    for (int i = 0; i < yIncrement+1 ; i++) {
        if (i == 0) {
            yPos =  topBorderOfMeasureBox + (yIncrementPixel * i);
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(leftBorderOfMeasureBox-labelWidth-4, yPos-(labelHeight/2)+(yIncrementPixel/3), labelWidth, labelHeight)];
            label.textAlignment = NSTextAlignmentRight;
            if (colorModeForCGenvelope == 0) { label.textColor = [UIColor whiteColor];  }else{ label.textColor = [UIColor blackColor];    }
            label.font = [UIFont boldSystemFontOfSize:fontSize];
            NSString *labelText;
            
            if ([selectedUnitForItems isEqualToString:@"kg"]) {
                if (flagLATinputH130 == 1) {
                    labelText = @"[mm]";
                }else{
                    labelText = @"[kg]";
                }
            }else{
                if (flagLATinputH130 == 1) {
                    labelText = @"[In]";
                }else{
                    labelText = @"[lbs]";
                }
            }
            
            
            
            [label  setText: labelText  ];
            [_viewCGenvelopeFrame_LAT addSubview: label];
            
        }else{
            yPos =  topBorderOfMeasureBox + (yIncrementPixel * i);
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(leftBorderOfMeasureBox-labelWidth-4, yPos-(labelHeight/2), labelWidth, labelHeight)];
            label.textAlignment = NSTextAlignmentRight;
            if (colorModeForCGenvelope == 0) { label.textColor = [UIColor whiteColor];  }else{ label.textColor = [UIColor blackColor];    }
            label.font = [UIFont boldSystemFontOfSize:fontSize];
            
            NSString *labelText;
            
            if (flagLATinputH130 == 1) {
                labelText = [ [NSString alloc] initWithFormat:@"%.0f", (yAxisTop - ( yIncrementValue * i)) * factorApplyToNativeDistanceInchMM  ]; 
            }else{
                labelText = [ [NSString alloc] initWithFormat:@"%.0f", (yAxisTop - ( yIncrementValue * i)) * factorApplyToNativeWeightforItems  ];  
            }
            
            
            
            
            
            
            [label  setText: labelText  ];
            [_viewCGenvelopeFrame_LAT addSubview: label];
        }
    }
    
    
    // make y lines
    
    for (int i = 0; i < yIncrement+1 ; i++) {
        yPos =  topBorderOfMeasureBox + (yIncrementPixel * i);
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( leftBorderOfMeasureBox, yPos )];
        [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox+ measureBoxWidth, yPos  )  ];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        if (colorModeForCGenvelope == 0) { shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];;  }else{ shapeLayer.strokeColor = [[UIColor blackColor] CGColor];    }
        shapeLayer.lineWidth = 0.5;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [self.viewCGenvelopeFrame_LAT.layer addSublayer:shapeLayer];
    }
    
    
    
    // make frame
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    
    [path moveToPoint:CGPointMake( leftBorderOfMeasureBox, topBorderOfMeasureBox )];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox+ measureBoxWidth, topBorderOfMeasureBox  )  ];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox+ measureBoxWidth, topBorderOfMeasureBox+measureBoxHeight  )  ];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox, topBorderOfMeasureBox+measureBoxHeight  )  ];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBox, topBorderOfMeasureBox  )  ];
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    if (colorModeForCGenvelope == 0) { shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];;  }else{ shapeLayer.strokeColor = [[UIColor blackColor] CGColor];    }
    shapeLayer.lineWidth = 1.5;
    shapeLayer.fillColor = [[UIColor clearColor] CGColor];
    [self.viewCGenvelopeFrame_LAT.layer addSublayer:shapeLayer];
    
    
    
    
    // ******************************************************************************************
    
    xPixelFactor = measureBoxWidth  / (xAxisRight-xAxisLeft);
    yPixelFactor = measureBoxHeight / (yAxisTop-yAxisBottom);
    
    int flagMakeDashedLine = 0;   
    int flagDoNotMakeLine = 0;
    flagNoLatLimit = 0; 
    
    float numberOfPoints = 0;
    UIBezierPath *pathCG = [UIBezierPath bezierPath];
    
    
    for (int i = 7; i < _arrayCG1_LAT.count ; i++) { /// make path
        
        // get point coordinates
        NSString *Xstring     = [_arrayCG1_LAT objectAtIndex: i ];
        
        //NSLog(@"Xstring %@", Xstring);
     
        
        NSString *searchKeyword = @"/";
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        xVal = @"";
        yVal = @"";
        float xCGpos = 0;
        float yCGpos = 0;
        
        //NSLog(@"Xstring %@", Xstring);
        
        if ([Xstring rangeOfString:@"settings"].location != NSNotFound  ) {            
            flagDoNotMakeLine = 1;            
            NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"_"];
            NSArray *settings = [Xstring componentsSeparatedByCharactersInSet:charSet1];            
            if ([[settings objectAtIndex:7]isEqualToString:@"noLimit"] ) {
                flagNoLatLimit = 1;
                //NSLog(@"flagNoLatLimit %d", flagNoLatLimit);
            }
            
            if ([[settings objectAtIndex:0] rangeOfString:@"dashed"].location != NSNotFound  ) {              
                flagMakeDashedLine = 1;
            }
            xVal = [settings objectAtIndex:2];
            yVal = [settings objectAtIndex:3];
            xCGpos = leftBorderOfMeasureBox + ( ([xVal floatValue]-xAxisLeft) * xPixelFactor );
            yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - [yVal floatValue]) * yPixelFactor );
                        
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xCGpos, yCGpos,180,30 )];
            
            label.textAlignment = NSTextAlignmentLeft;            
            label.text = [settings objectAtIndex:1];   
            
            
            int fontSize = [[settings objectAtIndex:4] floatValue];
            label.font = [UIFont boldSystemFontOfSize:fontSize];
            
            if ([[settings objectAtIndex:5] rangeOfString:@"orange"].location != NSNotFound  ) {
                label.textColor = [UIColor orangeColor];                
            }
            if ([[settings objectAtIndex:5] rangeOfString:@"red"].location != NSNotFound  ) {
                label.textColor = [UIColor redColor];                
            }
            if ([[settings objectAtIndex:5] rangeOfString:@"yellow"].location != NSNotFound  ) {
                label.textColor = [UIColor yellowColor];                
            }
            if ([[settings objectAtIndex:6] rangeOfString:@"clear"].location != NSNotFound  ) {
                label.backgroundColor = [UIColor clearColor];                
            }
            if ([[settings objectAtIndex:6] rangeOfString:@"orange"].location != NSNotFound  ) {
                label.backgroundColor = [UIColor orangeColor];                
            }
            if ([[settings objectAtIndex:6] rangeOfString:@"red"].location != NSNotFound  ) {
                label.backgroundColor = [UIColor redColor];                
            }
            if ([[settings objectAtIndex:6] rangeOfString:@"yellow"].location != NSNotFound  ) {
                label.backgroundColor = [UIColor yellowColor];                
            }
            if ([[settings objectAtIndex:6] rangeOfString:@"white"].location != NSNotFound  ) {
                label.backgroundColor = [UIColor yellowColor];                
            }        
            [_viewCGenvelopeFrame_LAT addSubview:label];            
        }
        
        
        if(rangeOfYourString.location == NSNotFound || flagDoNotMakeLine == 1) {
            // error condition — the text searchKeyword wasn't in 'string'
            
        }else{
            
            xVal = [Xstring substringToIndex:rangeOfYourString.location];
            yVal = [Xstring substringFromIndex:rangeOfYourString.location+1];            
            if (numberOfPoints == 0) { // first point only
                xCGpos = leftBorderOfMeasureBox + ( ([xVal floatValue]-xAxisLeft) * xPixelFactor );
                yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - [yVal floatValue]) * yPixelFactor );
                [pathCG moveToPoint:CGPointMake( xCGpos, yCGpos )];
            }else{
                xCGpos = leftBorderOfMeasureBox + ( ([xVal floatValue]-xAxisLeft) * xPixelFactor );
                yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - [yVal floatValue]) * yPixelFactor );
                [pathCG addLineToPoint:CGPointMake( xCGpos, yCGpos )];
            }
            numberOfPoints = numberOfPoints + 1;
        }// end add to path
    }// end for next make path
    
    
    shapeLayerCG1Lat= [CAShapeLayer layer];
    shapeLayerCG1Lat.path = [pathCG CGPath];
    shapeLayerCG1Lat.lineWidth = 3.5;
    shapeLayerCG1Lat.fillColor = [[UIColor clearColor] CGColor];
    [self.viewCGenvelopeFrame_LAT.layer addSublayer:shapeLayerCG1Lat];
    
    for (int i = 7; i < _arrayCG1_LAT.count ; i++) { /// make dots
        
        // get point coordinates        
        NSString *Xstring     = [_arrayCG1_LAT objectAtIndex: i ];
        NSString *searchKeyword = @"/";
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
        if ([Xstring isEqualToString: @""]) {
            break;
        }        
        xVal = @"";
        yVal = @"";        
        float xCGpos = 0;
        float yCGpos = 0;
        
        if(rangeOfYourString.location == NSNotFound){
            // error condition — the text searchKeyword wasn't in 'string'
        }else{
            xVal = [Xstring substringToIndex:rangeOfYourString.location];
            yVal = [Xstring substringFromIndex:rangeOfYourString.location+1];
            
            xCGpos = leftBorderOfMeasureBox + ( ([xVal floatValue]-xAxisLeft) * xPixelFactor );
            yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - [yVal floatValue]) * yPixelFactor );
            
            float dotSize = 10;
            CAShapeLayer *circleLayer = [CAShapeLayer layer];
            [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];
            [circleLayer setPosition:CGPointMake( xCGpos, yCGpos)];
            // Create a circle path.
            UIBezierPath *pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)];
            // Set the path on the layer
            [circleLayer setPath:[pathC CGPath]];
            // Set the stroke color
            [circleLayer setStrokeColor:[[UIColor blackColor] CGColor]];
            [circleLayer setFillColor:[[UIColor whiteColor] CGColor]];
            // Set the stroke line width
            [circleLayer setLineWidth:2.0f];
            [_viewCGenvelopeFrame_LAT.layer addSublayer:circleLayer];
                        
            if (flagShowCGEnvelopeValues == 1) {
                // make labels
                float labelHeight = 11;
                UILabel *label = [[UILabel alloc] init];
                label.font = [UIFont systemFontOfSize:11];
                label.textAlignment = NSTextAlignmentCenter;
                label.textColor = [UIColor whiteColor];
                label.backgroundColor = [UIColor blackColor];
                NSString *labelText = @"";
                if (([xVal floatValue]*factorApplyToNativeDistanceInchMM) < 1000) {
                    labelText = [[NSString alloc] initWithFormat:@"%.1f", [xVal floatValue] *  factorApplyToNativeDistanceInchMM ];
                }else{
                    labelText = [[NSString alloc] initWithFormat:@"%.0f", [xVal floatValue] *  factorApplyToNativeDistanceInchMM ];
                }
                [label  setText: labelText];
                float labelWidth = labelText.length * 8 ;
                label.frame = CGRectMake(xCGpos - (labelWidth/2), yCGpos - labelHeight-8 , labelWidth, labelHeight);
                [_viewCGenvelopeFrame_LAT addSubview:label];
                //*****
                labelHeight = 12;
                label = [[UILabel alloc] init];
                label.font = [UIFont systemFontOfSize:11];
                label.textAlignment = NSTextAlignmentCenter;
                label.textColor = [UIColor whiteColor];
                label.backgroundColor = [UIColor blackColor];
                labelText = @"";
                if (([yVal floatValue]*factorApplyToNativeWeightforItems) < 1000) {
                    labelText = [[NSString alloc] initWithFormat:@"%.1f", [yVal floatValue] *  factorApplyToNativeWeightforItems ];
                }else{
                    labelText = [[NSString alloc] initWithFormat:@"%.0f", [yVal floatValue] *  factorApplyToNativeWeightforItems ];
                }
                [label  setText: labelText];
                labelWidth = labelText.length * 8 ;
                label.frame = CGRectMake(xCGpos - labelWidth - 8, yCGpos - (labelHeight/2) , labelWidth, labelHeight);
                [_viewCGenvelopeFrame_LAT addSubview:label];
            }
            
        }// end add to path
        
    }// end for next make path
        
    leftBorderOfMeasureBoxLAT = leftBorderOfMeasureBox;    
    xAxisLeftLAT = xAxisLeft;    
    xPixelFactorLAT = xPixelFactor;    
    topBorderOfMeasureBoxLAT = topBorderOfMeasureBox;    
    yAxisTopLAT = yAxisTop;    
    yPixelFactorLAT = yPixelFactor;
    
    if (flagMakeDashedLine == 1) {
        //NSLog(@"flagMakeDashedLine 1");
        [shapeLayerCG1Lat setLineDashPattern:
        [NSArray arrayWithObjects:[NSNumber numberWithInt:15],
        [NSNumber numberWithInt:5],nil]];
        shapeLayerCG1Lat.lineWidth = 1.2;
    }
    
    if (flagShowCGEnvelopeValues == 1){
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(leftBorderOfMeasureBox+2, topBorderOfMeasureBox + 1 ,  measureBoxWidth-3, 17)];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor darkGrayColor];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:12];
        [label  setText: @"Lateral C.G." ];
        [_viewCGenvelopeFrame_LAT addSubview: label];
        
    }
    
    
    if ([trialCheck isEqualToString:@"isATrial"]) {
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(0, _viewCGenvelopeFrame_LAT.frame.size.height/2, _viewCGenvelopeFrame_LAT.frame.size.width, 20)];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor grayColor];
        label.textColor =yellowSpecialColor;;
        label.font = [UIFont systemFontOfSize:16];
        [label  setText: @"TRIAL - NOT FOR FLIGHT PLANNING!" ];
        [_viewCGenvelopeFrame_LAT addSubview: label];
    }
    
    
    return;
    
}



- (void) drawCGenvelopeLATManifest {
    
    
    colorModeForCGenvelope =  1;
    [self.viewCGenvelopeFrame2_LAT.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines
    _viewMeasureCGenvelope2_LAT.backgroundColor = [UIColor clearColor];    
    if (colorModeForCGenvelope == 0) { _viewCGenvelopeFrame2_LAT.backgroundColor = [UIColor clearColor];  }else{ _viewCGenvelopeFrame2_LAT.backgroundColor = [UIColor whiteColor];    }
    
    // CG x and y labels
    float xIncrement = 0;
    float yIncrement = 0;
    float fontSize = 0;
    if ([_arrayCG1_LAT count] > 0) {
        xAxisLeftLAT2     = [[_arrayCG1_LAT objectAtIndex: 0 ] floatValue];
        if ([_arrayCG1_LAT count] > 1) {
            xAxisRight    = [[_arrayCG1_LAT objectAtIndex: 1 ] floatValue];
        }
        if ([_arrayCG1_LAT count] > 2) {
            xIncrement    = [[_arrayCG1_LAT objectAtIndex: 2 ] floatValue];
        }
        if ([_arrayCG1_LAT count] > 3) {
            yAxisBottom   = [[_arrayCG1_LAT objectAtIndex: 3 ] floatValue];
        }
        if ([_arrayCG1_LAT count] > 4) {
            yAxisTopLAT2      = [[_arrayCG1_LAT objectAtIndex: 4 ] floatValue];
        }
        if ([_arrayCG1_LAT count] > 5) {
            yIncrement    = [[_arrayCG1_LAT objectAtIndex: 5 ] floatValue];
        }
        if ([_arrayCG1_LAT count] > 6) {
            fontSize     = [[_arrayCG1_LAT objectAtIndex: 6 ] floatValue];
        }
    }
    // statics    
    float labelWidth = 50;    
    float labelHeight = 15;    
    float xPos = 0, yPos = 0;
    
    leftBorderOfMeasureBoxLAT2 =   _viewMeasureCGenvelope2_LAT.center.x - (_viewMeasureCGenvelope2_LAT.layer.frame.size.width / 2.0) ;
    measureBoxWidth = _viewMeasureCGenvelope2_LAT.layer.frame.size.width;
    
    
    float xIncrementValue = 0;
    float xIncrementPixel = 0;
    
    if (xIncrement != 0 && xAxisLeftLAT2 != 0) {
        xIncrementValue = (xAxisRight - xAxisLeftLAT2) / xIncrement;
        xIncrementPixel = measureBoxWidth / xIncrement;
    }
    
    topBorderOfMeasureBoxLAT2 =   _viewMeasureCGenvelope2_LAT.center.y - (_viewMeasureCGenvelope2_LAT.layer.frame.size.height / 2.0) ;
    measureBoxHeight = _viewMeasureCGenvelope2_LAT.layer.frame.size.height;
    
    float yIncrementValue = 0;
    float yIncrementPixel = 0;
    if (yIncrement != 0 && yAxisBottom != 0) {
        yIncrementValue = (yAxisTopLAT2 - yAxisBottom) / yIncrement;
        yIncrementPixel = measureBoxHeight / yIncrement;
    }
    
    // make X labels
    int numberOfXLines = 0;
    for (int i = 0; i < xIncrement+1 ; i++) {
        numberOfXLines = numberOfXLines +1;
    }
    for (int i = 0; i < xIncrement+1 ; i++) {        
        
        if (numberOfXLines > 8 ) {
            if (i %2) {
                continue;
            }
        }        
        if (xAxisLeftLAT2 + ( xIncrementValue * i) > xAxisRight) {
            // plot labels only if fit in frame
            continue;
        }        
        xPos =  leftBorderOfMeasureBoxLAT2 + (xIncrementPixel * i);
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(xPos-(labelWidth/2), topBorderOfMeasureBoxLAT2 - labelHeight-2, labelWidth, labelHeight)];
        label.textAlignment = NSTextAlignmentCenter;
        if (colorModeForCGenvelope == 0) { label.textColor = [UIColor whiteColor];  }else{ label.textColor = [UIColor blackColor];    }
        label.font = [UIFont boldSystemFontOfSize:fontSize];
        if (i == 0) {
            if ([selectedUnitForItems isEqualToString:@"kg"]) {
                NSString *labelText = @"[mm]"; [label  setText: labelText  ];
                if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
                    labelText = @"[m]"; [label  setText: labelText  ];
                }

            }else{
                NSString *labelText = @"[In]"; [label  setText: labelText  ];
            }
        }else{
            NSString *labelText = [ [NSString alloc] initWithFormat:@"%.0f", (xAxisLeftLAT2 + ( xIncrementValue * i)) * factorApplyToNativeDistanceInchMM  ];
            if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
                labelText = [ [NSString alloc] initWithFormat:@"%.2f", xAxisLeftLAT2 + ( xIncrementValue * i)  ];
            }            
            [label  setText: labelText  ];  
        }
        [_viewCGenvelopeFrame2_LAT addSubview: label];
    }
    
    // make X lines
    for (int i = 0; i < xIncrement+1 ; i++) {        
        xPos =  leftBorderOfMeasureBoxLAT2 + (xIncrementPixel * i);        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( xPos, topBorderOfMeasureBoxLAT2 )];
        [path addLineToPoint:CGPointMake( xPos, topBorderOfMeasureBoxLAT2+ measureBoxHeight  )  ];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        if (colorModeForCGenvelope == 0) { shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];;  }else{ shapeLayer.strokeColor = [[UIColor blackColor] CGColor];    }
        shapeLayer.lineWidth = 0.5;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [self.viewCGenvelopeFrame2_LAT.layer addSublayer:shapeLayer];        
    }
    
    
    // make y labels    
    for (int i = 0; i < yIncrement+1 ; i++) {        
        if (i == 0) { // make first label the LBS label
            
            yPos =  topBorderOfMeasureBoxLAT2 + (yIncrementPixel * i);
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(leftBorderOfMeasureBoxLAT2-labelWidth-4, yPos-(labelHeight/2)+(yIncrementPixel/3), labelWidth, labelHeight)];
            label.textAlignment = NSTextAlignmentRight;
            if (colorModeForCGenvelope == 0) { label.textColor = [UIColor whiteColor];  }else{ label.textColor = [UIColor blackColor];    }
            label.font = [UIFont boldSystemFontOfSize:fontSize];
            NSString *labelText;
            if ([selectedUnitForItems isEqualToString:@"kg"]) {
                if (flagLATinputH130 == 1) {
                    labelText = @"mm";
                }else{
                    labelText = @"kg";
                }
            }else{
                if (flagLATinputH130 == 1) {
                    labelText = @"In";
                }else{
                    labelText = @"lbs";
                }
            }            [label  setText: labelText  ];
            [_viewCGenvelopeFrame2_LAT addSubview: label];
            
            
            
        }else{            
            yPos =  topBorderOfMeasureBoxLAT2 + (yIncrementPixel * i);
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(leftBorderOfMeasureBoxLAT2-labelWidth-4, yPos-(labelHeight/2), labelWidth, labelHeight)];
            label.textAlignment = NSTextAlignmentRight;
            if (colorModeForCGenvelope == 0) { label.textColor = [UIColor whiteColor];  }else{ label.textColor = [UIColor blackColor];    }
            label.font = [UIFont boldSystemFontOfSize:fontSize];
            NSString *labelText = [ [NSString alloc] initWithFormat:@"%.0f", (yAxisTopLAT2 - ( yIncrementValue * i)) * factorApplyToNativeWeightforItems  ];
            [label  setText: labelText  ];
            [_viewCGenvelopeFrame2_LAT addSubview: label];
        }
    }
    
    // make y lines
    for (int i = 0; i < yIncrement+1 ; i++) {        
        yPos =  topBorderOfMeasureBoxLAT2 + (yIncrementPixel * i);        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( leftBorderOfMeasureBoxLAT2, yPos )];
        [path addLineToPoint:CGPointMake( leftBorderOfMeasureBoxLAT2+ measureBoxWidth, yPos  )  ];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        if (colorModeForCGenvelope == 0) { shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];;  }else{ shapeLayer.strokeColor = [[UIColor blackColor] CGColor];    }
        shapeLayer.lineWidth = 0.5;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [self.viewCGenvelopeFrame2_LAT.layer addSublayer:shapeLayer];
    }
    
    
    
    // make frame
    
    UIBezierPath *path = [UIBezierPath bezierPath];    
    [path moveToPoint:CGPointMake( leftBorderOfMeasureBoxLAT2, topBorderOfMeasureBoxLAT2 )];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBoxLAT2+ measureBoxWidth, topBorderOfMeasureBoxLAT2  )  ];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBoxLAT2+ measureBoxWidth, topBorderOfMeasureBoxLAT2+measureBoxHeight  )  ];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBoxLAT2, topBorderOfMeasureBoxLAT2+measureBoxHeight  )  ];
    [path addLineToPoint:CGPointMake( leftBorderOfMeasureBoxLAT2, topBorderOfMeasureBoxLAT2  )  ];
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    if (colorModeForCGenvelope == 0) { shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];;  }else{ shapeLayer.strokeColor = [[UIColor blackColor] CGColor];    }
    shapeLayer.lineWidth = 1.5;
    shapeLayer.fillColor = [[UIColor clearColor] CGColor];
    [self.viewCGenvelopeFrame2_LAT.layer addSublayer:shapeLayer];
    
    
    // ******************************************************************************************
    
    xPixelFactorLAT2 = measureBoxWidth  / (xAxisRight-xAxisLeftLAT2);    
    yPixelFactorLAT2 = measureBoxHeight / (yAxisTopLAT2-yAxisBottom);    
    
    float numberOfPoints = 0;    
    UIBezierPath *pathCG = [UIBezierPath bezierPath];
    
    int flagMakeDashedLine = 0;   
    int flagDoNotMakeLine = 0;
    
    for (int i = 7; i < _arrayCG1_LAT.count ; i++) { /// make path
        
       

        // get point coordinates
        NSString *Xstring     = [_arrayCG1_LAT objectAtIndex: i ];        
        NSString *searchKeyword = @"/";        
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];        
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        
        xVal = @"";        
        yVal = @"";        
        float xCGpos = 0;        
        float yCGpos = 0;

        if ([Xstring rangeOfString:@"settings"].location != NSNotFound  ) {            
            flagDoNotMakeLine = 1;            
            NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"_"];
            NSArray *settings = [Xstring componentsSeparatedByCharactersInSet:charSet1];            
           
            
            if ([[settings objectAtIndex:0] rangeOfString:@"dashed"].location != NSNotFound  ) {              
                flagMakeDashedLine = 1;
            }
            xVal = [settings objectAtIndex:2];
            yVal = [settings objectAtIndex:3];
            xCGpos = leftBorderOfMeasureBoxLAT2 + ( ([xVal floatValue]-xAxisLeftLAT2) * xPixelFactorLAT2 );
            yCGpos = topBorderOfMeasureBoxLAT2  + (  (yAxisTopLAT2 - [yVal floatValue]) * yPixelFactorLAT2 );
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xCGpos, yCGpos,180,30 )];
            
            label.textAlignment = NSTextAlignmentLeft;            
            label.text = [settings objectAtIndex:1];   
            //NSLog(@"label.text %@", label.text);
            
            int fontSize = [[settings objectAtIndex:4] floatValue];
            label.font = [UIFont boldSystemFontOfSize:fontSize];
            
            if ([[settings objectAtIndex:5] rangeOfString:@"orange"].location != NSNotFound  ) {
                label.textColor = [UIColor orangeColor];                
            }
            if ([[settings objectAtIndex:5] rangeOfString:@"red"].location != NSNotFound  ) {
                label.textColor = [UIColor redColor];                
            }
            if ([[settings objectAtIndex:5] rangeOfString:@"yellow"].location != NSNotFound  ) {
                label.textColor = [UIColor yellowColor];                
            }
            if ([[settings objectAtIndex:6] rangeOfString:@"clear"].location != NSNotFound  ) {
                label.backgroundColor = [UIColor clearColor];                
            }
            if ([[settings objectAtIndex:6] rangeOfString:@"orange"].location != NSNotFound  ) {
                label.backgroundColor = [UIColor orangeColor];                
            }
            if ([[settings objectAtIndex:6] rangeOfString:@"red"].location != NSNotFound  ) {
                label.backgroundColor = [UIColor redColor];                
            }
            if ([[settings objectAtIndex:6] rangeOfString:@"yellow"].location != NSNotFound  ) {
                label.backgroundColor = [UIColor yellowColor];                
            }
            if ([[settings objectAtIndex:6] rangeOfString:@"white"].location != NSNotFound  ) {
                label.backgroundColor = [UIColor yellowColor];                
            }        
            [_viewCGenvelopeFrame2_LAT addSubview:label];            
        }
        
        
        if(rangeOfYourString.location == NSNotFound || flagDoNotMakeLine == 1 )
        {
            // error condition — the text searchKeyword wasn't in 'string'
        }
        else{            
            xVal = [Xstring substringToIndex:rangeOfYourString.location];            
            yVal = [Xstring substringFromIndex:rangeOfYourString.location+1];            
            
            if (numberOfPoints == 0) { // first point only                
                xCGpos = leftBorderOfMeasureBoxLAT2 + ( ([xVal floatValue]-xAxisLeftLAT2) * xPixelFactorLAT2 );
                yCGpos = topBorderOfMeasureBoxLAT2  + (  (yAxisTopLAT2 - [yVal floatValue]) * yPixelFactorLAT2 );                
                [pathCG moveToPoint:CGPointMake( xCGpos, yCGpos )];
                
            }else{                
                xCGpos = leftBorderOfMeasureBoxLAT2 + ( ([xVal floatValue]-xAxisLeftLAT2) * xPixelFactorLAT2 );                
                yCGpos = topBorderOfMeasureBoxLAT2  + (  (yAxisTopLAT2 - [yVal floatValue]) * yPixelFactorLAT2 );                
                [pathCG addLineToPoint:CGPointMake( xCGpos, yCGpos )];                
            }            
            numberOfPoints = numberOfPoints + 1;            
            
        }// end add to path
    }// end for next make path
    
    CAShapeLayer *shapeLayer2 = [CAShapeLayer layer];
    shapeLayer2.path = [pathCG CGPath];
    shapeLayer2.strokeColor = [[UIColor colorWithRed:255.0/255.0f green:218.0/255.0f blue:0.0/255.0f alpha:1.0f] CGColor];
    if (colorModeForCGenvelope == 0) {  shapeLayer2.strokeColor =[[UIColor colorWithRed:255.0/255.0f green:218.0/255.0f blue:0.0/255.0f alpha:1.0f] CGColor];  }else{ shapeLayer2.strokeColor = [[UIColor redColor] CGColor];    }
    shapeLayer2.lineWidth = 3.5;
    shapeLayer2.fillColor = [[UIColor clearColor] CGColor];
    [_viewCGenvelopeFrame2_LAT.layer addSublayer:shapeLayer2];
    
    if (flagMakeDashedLine == 1) {
        [shapeLayer2 setLineDashPattern:
         [NSArray arrayWithObjects:[NSNumber numberWithInt:15],
          [NSNumber numberWithInt:5],nil]];
        shapeLayer2.lineWidth = 1.2;
    }
    
    
    
    for (int i = 7; i < _arrayCG1_LAT.count ; i++) { /// make dots
        
        // get point coordinates
        NSString *Xstring     = [_arrayCG1_LAT objectAtIndex: i ];        
        NSString *searchKeyword = @"/";        
        NSRange rangeOfYourString = [Xstring rangeOfString:searchKeyword];
        if ([Xstring isEqualToString: @""]) {
            break;
        }
        
        xVal = @"";        
        yVal = @"";        
        float xCGpos = 0;        
        float yCGpos = 0;
        
        if(rangeOfYourString.location == NSNotFound)
        {
            // error condition — the text searchKeyword wasn't in 'string'
        }
        else{
            
            xVal = [Xstring substringToIndex:rangeOfYourString.location];            
            yVal = [Xstring substringFromIndex:rangeOfYourString.location+1];            
            xCGpos = leftBorderOfMeasureBoxLAT2 + ( ([xVal floatValue]-xAxisLeftLAT2) * xPixelFactorLAT2 );
            yCGpos = topBorderOfMeasureBoxLAT2  + (  (yAxisTopLAT2 - [yVal floatValue]) * yPixelFactorLAT2 );                        
            float dotSize = 10;
            
            CAShapeLayer *circleLayer = [CAShapeLayer layer];            
            [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];            
            [circleLayer setPosition:CGPointMake( xCGpos, yCGpos)];            
            // Create a circle path.            
            UIBezierPath *pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)];            
            // Set the path on the layer
            [circleLayer setPath:[pathC CGPath]];
            // Set the stroke color
            [circleLayer setStrokeColor:[[UIColor blackColor] CGColor]];
            [circleLayer setFillColor:[[UIColor whiteColor] CGColor]];
            // Set the stroke line width
            [circleLayer setLineWidth:2.0f];
            [_viewCGenvelopeFrame2_LAT.layer addSublayer:circleLayer];
                        
        }// end add to path
        
        
        
        
    }// end for next make path
    
    if ([trialCheck isEqualToString:@"isATrial"]) {
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(0, _viewCGenvelopeFrame2_LAT.frame.size.height/2, _viewCGenvelopeFrame2_LAT.frame.size.width, 20)];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor grayColor];
        label.textColor =yellowSpecialColor;
        label.font = [UIFont systemFontOfSize:16];
        [label  setText: @"TRIAL - NOT FOR FLIGHT PLANNING!" ];
        [_viewCGenvelopeFrame2_LAT addSubview: label];
    }
    
    
    
    
    
    
    return;
    
    
    
}




// *************************************************************************************************************************************************************************
// *************************************************************************************************************************************************************************
// *************************************************************************************************************************************************************************

// *************************************************************************************************************************************************************************



- (void) setCGenvelope {
    
    //NSLog (@"setCGenvelope ");
    if ([_arrayName21 count] > 5){
        //unitsWeight.text = [_arrayName21 objectAtIndex: 5  ];
    }
    
    
    [self initializeCGArrays];
    
    [self drawCGenvelopeLATManifest];
    
    [self drawCGenvelopeLAT];
    
    [self drawCGenvelope];
    
    [self drawCGenvelopeManifest];
    
    
    
}


-(void) initializeCGArrays {
    
    //NSLog (@"1initializeCGArrays alternateCGenvelope %@", alternateCGenvelope);
    _arrayCG1 = [[NSMutableArray alloc] init];
    _arrayCG2 = [[NSMutableArray alloc] init];
    _arrayCG1_LAT = [[NSMutableArray alloc] init];
    _arrayCG1MarginLine = [[NSMutableArray alloc] init];

    
    NSString *CGenvelopeName = alternateCGenvelope;
    
     //NSLog(@"alternateCGenvelope %@",alternateCGenvelope);
    
    if (alternateCGenvelope.length > 1 && ![alternateCGenvelope isEqualToString:@"CGexternal"] && ![alternateCGenvelope isEqualToString:@"CGenvelope"] ) {
        
        
        
        CGenvelopeName = alternateCGenvelope;
        
        //xNSLog(@"CGenvelopeName %@ ", CGenvelopeName);
        
        //arrayKey = [ [NSString alloc] initWithFormat:@"%@_CGmulti_%@_arrayCG1", AC_Type, CGenvelopeName ];
         arrayKey = [ [NSString alloc] initWithFormat:@"%@_CGmulti_%@%@", AC_Type, CGenvelopeName,  @"_arrayCG1" ];
        [_arrayCG1 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: arrayKey ] mutableCopy]];
        
        //NSLog(@"arrayKey %@ ", arrayKey);
        
        
        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_CGmulti_%@%@", AC_Type, CGenvelopeName,  @"_arrayCG1_LAT" ];
        [_arrayCG1_LAT setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: arrayKey ] mutableCopy]];
        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_CGmulti_%@%@", AC_Type, CGenvelopeName,  @"_arrayCG2" ];
        [_arrayCG2 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: arrayKey ] mutableCopy]];
        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_CGmulti_%@%@", AC_Type, CGenvelopeName,  @"_arrayCG1MarginLine" ];
        [_arrayCG1MarginLine setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: arrayKey ] mutableCopy]];
        
        
    }else{        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@%@", AC_Type, CGenvelopeName,  @"_arrayCG1" ];
        
        //NSLog(@"2 initializeCGArrays ");
        
        [_arrayCG1 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: arrayKey ] mutableCopy]];
        [_arrayCG2 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"%@_%@_arrayCG2", AC_Type, CGenvelopeName] ] mutableCopy]];
        [_arrayCG1_LAT setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"%@_%@_arrayCG1_LAT", AC_Type, CGenvelopeName] ] mutableCopy]];
        [_arrayCG1MarginLine setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"%@_%@_arrayCG1MarginLine", AC_Type, CGenvelopeName] ] mutableCopy]];
    }
    

    
    
   
    
    //NSLog (@"_arrayCG1 %@", _arrayCG1);
    //NSLog (@"_arrayCG2 %@", _arrayCG2);
    //NSLog (@"_arrayCG1_LAT %@", _arrayCG1_LAT);
    //NSLog (@"_arrayCG1MarginLine %@", _arrayCG1MarginLine);
    
    [self makeFreakViewShape1];
    [self makeFreakViewShape2];
    [self makeFreakViewLateral];
    [self makeFreakViewShapeMargin];
    
}






    
    

// dList **********************************************************************************************************


- (IBAction)actionEnterText:(UITextField *)sender {
    
    
  
    
    dListInputFieldTag = sender.tag;
    
    //NSLog(@"123 dListInputFieldTag %f", dListInputFieldTag);
    
    UITextField* field = (UITextField*)[_viewDepartureDestinationFields viewWithTag: dListInputFieldTag];
    
    field.enabled = NO;
    
    _viewDlist.hidden = NO;
    
    [viewOne bringSubviewToFront:_viewDlist];
    
    [dListClass_ initializeDlistWindow];
    
    [dListClass_ activateTextfield];
    
  

    
    
}


- (IBAction)actionDListButton:(UIButton*)sender  {
    
    dListInputFieldTag = sender.tag;
    
    _viewDlist.hidden = NO;
    
    [viewOne bringSubviewToFront:_viewDlist];
    
    [dListClass_ initializeDlistWindow];
    
    [dListClass_ activateTextfield];
    
    
    
    
}



-(void) dListSetInputField {
    
    
  
    
    UITextField* field = (UITextField*)[_viewDepartureDestinationFields viewWithTag: dListInputFieldTag];
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    NSString *dListInputText    = [defaults  stringForKey:@"dListInputText"];
    
    [field setText: dListInputText];
    
    field.enabled = YES;

    _viewDlist.hidden = YES;
    
    [self calculateListo];
    
    

}




-(void) dListCancel {
    
    
    
    _viewDlist.hidden = YES;
    
    
    
}


-(void) closeFleetManagerView {
    
    //NSLog(@"closeFleetManagerView ");
    
    _viewFleetManager.hidden = YES;
    
    _viewSelectHelicopter.hidden = YES;
    
}

-(void) closeFleetManagerAndOpenWBpage {
    
    //NSLog(@"closeFleetManagerAndOpenWBpage");
    _viewFleetManager.hidden = YES;    
    _viewSelectHelicopter.hidden = YES;
    
    displayWindow = 0;
    [self displayWindows];
    
}




// dList end **********************************************************************************************************

- (void)handleSingleTapOnCGEnvelope:(UIPanGestureRecognizer *)recognizer {
    //NSLog(@"handleSingleTapOnCGEnvelope");
    if (flagShowCGEnvelopeValues == 0) {
        flagShowCGEnvelopeValues = 1;
        [self setCGwindows];
    }else{
        flagShowCGEnvelopeValues = 0;
        [self setCGwindows];
    }
    [self setCGenvelope];
    [self MainRoutine];
}

- (void)handleSingleTapOnCGEnvelopeLat:(UIPanGestureRecognizer *)recognizer {
    //NSLog(@"handleSingleTapOnCGEnvelope");
    if (flagShowCGEnvelopeValues == 0) {
        flagShowCGEnvelopeValues = 1;
        [self setCGwindows];
    }else{
        flagShowCGEnvelopeValues = 0;
        [self setCGwindows];
    }
    [self setCGenvelope];
     [self MainRoutine];
}



- (IBAction)sliderActionKIAS:(id)sender {
    int dummy = _sliderKIAS.value/2;
    _sliderKIAS.value = dummy * 2;
    [self MainRoutine];
}

- (IBAction)sliderActionFuelMain1:(id)sender {
    
    int sliderSpan = _sliderFuelMain1.maximumValue - _sliderFuelMain1.minimumValue ;
    int fivePercentofSliderRange =  (_sliderFuelMain1.maximumValue - _sliderFuelMain1.minimumValue) * 0.03;
    int increment = 0;
    if (sliderSpan <= 60) {        increment = 1;  }
    if (sliderSpan > 60 & sliderSpan <= 100) {        increment = 5;  }
    if (sliderSpan > 100) {        increment = 10;  } 
    
    float dummyFactor = increment;    
    if ([fuelEnterMode isEqualToString:@"mass"]) {
        dummyFactor = increment / [_inputSpecificFuelMassPerVolume.text floatValue];
    }
    
    if ((_sliderFuelMain1.maximumValue - dummyFactor) < _sliderFuelMain1.value  ) {
        dummyFactor = 1;
    }
    
    int dummy = _sliderFuelMain1.value/dummyFactor;
    _sliderFuelMain1.value = dummy * dummyFactor;
    
    
    if (_switchAutoLandingFuel.on == YES) {      
        if (_sliderFuelMain1.value < _sliderFuelLanding.value ) {             
            _sliderFuelMain1.value = _sliderFuelLanding.value;
        }       
    }else{        
        if (_sliderFuelLanding.value >= _sliderFuelMain1.value ) {
            _sliderFuelLanding.value = _sliderFuelMain1.value - fivePercentofSliderRange;
        } 
    }
    
    if (flagSpecialPHIFlightSettingPage == 1) {
        if ([fuelEnterMode isEqualToString:@"mass"]) {
             calculatorscreen.text = [ [NSString alloc] initWithFormat:@"%.0f", _sliderFuelMain1.value * [_inputSpecificFuelMassPerVolume.text floatValue]];
        }else{
              calculatorscreen.text = [ [NSString alloc] initWithFormat:@"%.0f", _sliderFuelMain1.value ];            
        }       
        EnterPadString = calculatorscreen.text;
        
    }
    
    //NSLog(@"sliderActionFuelMain1 %.1f", _sliderFuelMain1.value) ;
    
    
    [self MainRoutine];
    
}


- (IBAction)sliderActionFuelLanding:(id)sender {
    
    int sliderSpan = _sliderFuelLanding.maximumValue - _sliderFuelLanding.minimumValue ;
    int fivePercentofSliderRange =  (_sliderFuelLanding.maximumValue - _sliderFuelLanding.minimumValue) * 0.05;
    int increment = 0;
    if (sliderSpan <= 60) {        increment = 1;  }
    if (sliderSpan > 60 & sliderSpan <= 100) {        increment = 5;  }
    if (sliderSpan > 100) {        increment = 10;  }
      
    if (_switchAutoLandingFuel.on == YES) {
        return;
    }
    
    float dummyFactor = increment;    
    if ([fuelEnterMode isEqualToString:@"mass"]) {
        dummyFactor = increment / [_inputSpecificFuelMassPerVolume.text floatValue];
    }    
    if ((_sliderFuelLanding.maximumValue - dummyFactor) < _sliderFuelLanding.value  ) {
        dummyFactor = 1;
    }    
    int dummy = _sliderFuelLanding.value/dummyFactor;
    _sliderFuelLanding.value = dummy * dummyFactor;
    
    if (_sliderFuelLanding.value >= _sliderFuelMain1.value ) {
        _sliderFuelLanding.value = _sliderFuelMain1.value - fivePercentofSliderRange;
    } 
    
    [self MainRoutine];
    
}


- (IBAction)buttonActionEnterFuelMain:(id)sender {
        
    
    if (flagButtonPressed == 0) {        
        [self setListoButtonsNeutral];        
        enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;        
        UIImage *buttonmark = [UIImage imageNamed:@"Klammern_Yel.png"];        
        [_buttonEnterFuelMain setImage:buttonmark forState:UIControlStateNormal];        
        EnterPadString = @"0"; calculatorscreen.text = @"0"; EnterValueTwo = 0;
        selectedItem = 25;
        
    } else {[self setButtonMarksNeutral];}
    
    
    
    
    
}




- (IBAction)buttonActionEnterFuelLanding:(id)sender {
    
    
    if (_switchAutoLandingFuel.on == YES) {
        return;
    }
    
    
    
    if (flagButtonPressed == 0) {
        
        [self setListoButtonsNeutral];
        
        enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;
        
        UIImage *buttonmark = [UIImage imageNamed:@"Klammern_Yel.png"];
        
        [_buttonEnterFuelLanding setImage:buttonmark forState:UIControlStateNormal];
        
        EnterPadString = @"0"; calculatorscreen.text = @"0"; EnterValueTwo = 0;
        
        
        
        selectedItem = 26;
        
    } else {[self setButtonMarksNeutral];}
    
    
    
    
    
}






- (IBAction)buttonActionEnterFuelMainPercent:(id)sender {
    
    
    
    if (flagButtonPressed == 0) {
        
        [self setListoButtonsNeutral];
        
        enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;
        
        UIImage *buttonmark = [UIImage imageNamed:@"Klammern_Yel.png"];
        
        [_buttonEnterFuelMainPercent setImage:buttonmark forState:UIControlStateNormal];
        
        EnterPadString = @"0"; calculatorscreen.text = @"0"; EnterValueTwo = 0;
        
        
        
        selectedItem = 27;
        
    } else {[self setButtonMarksNeutral];}
    
    
    
    
    
}


- (IBAction)buttonActionEnterFuelLandingPercent:(id)sender {
    
    
    if (_switchAutoLandingFuel.on == YES) {
        return;
    }
    
    
    if (flagButtonPressed == 0) {
        
        [self setListoButtonsNeutral];
        
        enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;
        
        UIImage *buttonmark = [UIImage imageNamed:@"Klammern_Yel.png"];
        
        [_buttonEnterFuelLandingPercent setImage:buttonmark forState:UIControlStateNormal];
        
        EnterPadString = @"0"; calculatorscreen.text = @"0"; EnterValueTwo = 0;
        
        
        
        selectedItem = 28;
        
    } else {[self setButtonMarksNeutral];}
    
    
    
    
    
}


- (IBAction)buttonActionEnterFlightTimeMinutes:(id)sender {
    
    
    if (flagButtonPressed == 0) {
        
        [self setListoButtonsNeutral];
        
        enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;
        
        UIImage *buttonmark = [UIImage imageNamed:@"Klammern_Yel.png"];
        
        [_buttonEnterFlightTimeMinutes setImage:buttonmark forState:UIControlStateNormal];
        
        EnterPadString = @"0"; calculatorscreen.text = @"0"; EnterValueTwo = 0;
        
        
        
        selectedItem = 29;
        
        
    } else {[self setButtonMarksNeutral];}
    
    
    
    
    
}




- (IBAction)actionDisplayTimers:(id)sender {
    
    if (displayWindow == 15) {
        
        displayWindow = 0;
    } else {
        displayWindow = 15;
    }
    
    [self displayWindows];
    
    
}
- (IBAction)buttonActionTimer:(UIButton*)sender {
    
 
    NSDate *currentTime = datepick.date;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"HH:mm"];
    
    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [dateFormatter setTimeZone:gmt];
    
    NSTimeZone *localTZ = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTZ];
    
    NSString *localTimeString = [dateFormatter stringFromDate: currentTime];
    
    
    
    
    if (sender.tag == 1) {
        _inputTimer1.text = localTimeString;
    }
    
    if (sender.tag == 2) {
        _inputTimer2.text = localTimeString;
    }
    
    if (sender.tag == 3) {
        _inputTimer3.text = localTimeString;
    }
    
    if (sender.tag == 4) {
        _inputTimer4.text = localTimeString;
    }
    
    if (sender.tag == 5) {
        _inputTimer5.text = localTimeString;
    }
    
    if (sender.tag == 6) {
        _inputTimer6.text = localTimeString;
    }
    
    
    
}



- (void)actionFullScreenPerfChart: (float)receivedChartState{
    
    //NSLog(@"doing actionFullScreenPerfChart receivedChartState = %f",receivedChartState );
    
    if (flagIsLandscape == 1) {
        
        if (receivedChartState == 0) {
            calculatePerformanceClassView_.frame = CGRectMake(0, 114, 646, 634);
        }else{
            
            calculatePerformanceClassView_.frame = CGRectMake(0, 114, 1024, 634);
            
        }
        
        
    }else{
        
        if (receivedChartState == 0) {
            calculatePerformanceClassView_.frame = CGRectMake(0, 114 - 58, 646, 634);
        }else{
            
            calculatePerformanceClassView_.frame = CGRectMake(0, 114 - 58, 768, 1000);
            
        }
        
        
    }
    
}


- (IBAction)buttonActionDisplayEnvironment:(id)sender {
    
    [self actionPerfbuttonsNepp];
    
}

- (void)actionPerfbuttonsNepp {
    
    selectedChartButton = 1;    
    triggerOpenChart = 1;
    
    //NSLog(@"selectedChartButton %f ", selectedChartButton);    
    //NSLog(@"displayWindow %f ", displayWindow);
       
    if (displayWindow == 0) {
        
        //NSLog(@"1");
        displayWindow = 101;
         [calculatePerformanceClass_ triggerLoadSliderData];
        triggerDoNotShowPerfChart = 1;
        [self displayWindows];
        _viewLegButtons.hidden = NO;
        
    }else{
        //NSLog(@"2");
        displayWindow = 0;
        triggerDoNotShowPerfChart = 0;
         [self displayWindows];
    }
    
     UIView *signalStripe = (UIView *)[_viewUniversalButtons viewWithTag:999];
     signalStripe.hidden = YES;
    
    
    [self MainRoutine];
    
}


- (void)actionPerfbuttons :(UIButton*)sender {
    selectedChartButton = sender.tag;
    
   
    
    _labelNotePlanMode.hidden = YES;
    triggerOpenChart = 1;
    
    if (triggerDoNotShowPerfChart == 1) {
        triggerDoNotShowPerfChart = 0;        
        previousdButton = sender.tag;
        displayWindow = 0;
        [self displayWindows];
    }
    //NSLog(@"selectedChartButton %f ", selectedChartButton);    
    //NSLog(@"previousdButton %f ", previousdButton);
    
    // reset view
    pinchScale= 1.0;
    moveupDown = 0; moveLeftRight = 0;
    UIView *signalStripe = (UIView *)[_viewUniversalButtons viewWithTag:999];
    
    UIButton *perfButton = (UIButton *)sender;
    displayWindow = sender.tag + 100;
    
    if (previousdButton == sender.tag) {
        
        if (perfButton.selected == NO) {
            perfButton.selected = YES;
               [calculatePerformanceClass_ triggerLoadSliderData];
            signalStripe.frame = CGRectMake(perfButton.frame.origin.x, signalStripe.frame.origin.y, signalStripe.frame.size.width, signalStripe.frame.size.height);
            //NSLog(@"1 actionPerfbuttons gleicher button wie vorher und er war NICHT selected %d", flagPerfBoxOn);
            if (flagPerfBoxOn == 1) {
                flagPerfBoxOn = 0;
                [self addPerformanceButtons];
                displayWindow = sender.tag + 100;
                [self displayWindows];
            }
        }else{
            perfButton.selected = NO; displayWindow = 0; [self displayWindows]; [self MainRoutine];
        }
    }
    
    if (previousdButton != sender.tag) {
        //NSLog(@"3  anderer button  %d", flagPerfBoxOn);
        UIButton *prevButt = (UIButton *)[self.viewTopDisplayButtons viewWithTag:previousdButton];
        prevButt.selected = NO;
        perfButton.selected = YES;
           [calculatePerformanceClass_ triggerLoadSliderData];
        previousdButton = sender.tag;
        signalStripe.frame = CGRectMake(perfButton.frame.origin.x, signalStripe.frame.origin.y, signalStripe.frame.size.width, signalStripe.frame.size.height);        
        if (flagPerfBoxOn == 1) {
            flagPerfBoxOn = 0;
            [self addPerformanceButtons];
            displayWindow = sender.tag + 100;
            [self displayWindows];
        }
    }
    
    if (displayWindow > 100) {
        signalStripe.hidden = NO;
    }else{
        signalStripe.hidden = YES;
    }
    
    if (flagIsLandscape == 0) {
        signalStripe.hidden = YES;
    }else{
        signalStripe.hidden = NO;
    }
    
    [self MainRoutine];
    [self MainRoutine];
}


// performance ***********************************************************************************
// performance ***********************************************************************************
// performance ***********************************************************************************




- (void) loadPerfChartData {
   
 
    NSArray *componentsReducedCharts = [[NSArray alloc] init];   
    if (_arrayName25.count >=53 ) {
        NSString *reducedPerfCharts = [_arrayName25 objectAtIndex:53]; //extra10
        NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"+"];
        componentsReducedCharts = [reducedPerfCharts componentsSeparatedByCharactersInSet:charSet];  
    } 
   
    if (componentsReducedCharts.count > 1) {
        chartsArray = componentsReducedCharts;
    }else{
        // get chart names from chartsArray
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@_%@_%@_%@", ACCategory, ACmanufacturer, AC_Type, ACVariant, @"availableCharts" ];       
        chartsArray = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];        
    }

    
    //NSLog( @"loadPerfChartData chartsArray %@ ", chartsArray );
    [perfButtonChartNames removeAllObjects];
    [perfButtonUserNames removeAllObjects];
    amountofButtonsNeeded = 0;
    
        
    for(int i =0; i<chartsArray.count; i++) {
        //NSLog(@"chartsArray i  %d", i);
        // get info General files
        chartNameForThisInfoFile = [chartsArray objectAtIndex:i];
        //NSLog(@"chartNameForThisInfoFile %@", chartNameForThisInfoFile );
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@", chartNameForThisInfoFile, @"infoGeneral" ];
        //NSLog(@"infoGeneral  %@", [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy] );
        infoFilesGeneral = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
        
        //next3  statue !!!!! watt ein fuck! 12. Dez 2018
        //NSLog(@"infoFilesGeneral %@", infoFilesGeneral);     
        //NSLog(@"infoFilesGeneral.count %lu", (unsigned long)infoFilesGeneral.count);
        
        //NSLog(@"infoFilesGeneral  %@", infoFilesGeneral);
        //NSLog(@"[infoFilesGeneral objectAtIndex:3]  %@", [infoFilesGeneral objectAtIndex:3]);
        
        if (infoFilesGeneral.count > 4) {
            
            //NSLog(@"0");   
           
            if ([[infoFilesGeneral objectAtIndex:3] rangeOfString:@"next"].location != NSNotFound  ) {
                //NSLog(@"1");        
                if ([[infoFilesGeneral objectAtIndex:0] rangeOfString:@"FXX"].location != NSNotFound  ) {
                       if ([[infoFilesGeneral objectAtIndex:0] rangeOfString:@"TOGroundRoll"].location != NSNotFound  ) {             
                        amountofButtonsNeeded = amountofButtonsNeeded + 1; 
                            //NSLog(@"2");  
                     
                    }
                    if ([[infoFilesGeneral objectAtIndex:0] rangeOfString:@"LDGGroundRoll"].location != NSNotFound  ) {                        
                        amountofButtonsNeeded = amountofButtonsNeeded + 1;  
                         //NSLog(@"3");  
                    }                    
                    
                    if ([[infoFilesGeneral objectAtIndex:0] rangeOfString:@"CruiseComp"].location != NSNotFound  ) {                   
                        amountofButtonsNeeded = amountofButtonsNeeded + 1;  
                         //NSLog(@"4");  
                    }
                    
                }else{                   
                    amountofButtonsNeeded = amountofButtonsNeeded + 1;
                     //NSLog(@"5");  
                }              
               
                [perfButtonChartNames addObject:chartNameForThisInfoFile];
                //NSLog(@"adding Button for  %@", chartNameForThisInfoFile );
            }
            
        
      
            //add1ceiling
            //NSLog(@"[[infoFilesGeneral objectAtIndex:3]  %@", [infoFilesGeneral objectAtIndex:3] );                 
            if ([[infoFilesGeneral objectAtIndex:3] rangeOfString:@"criteria1"].location != NSNotFound  ) {
                amountofButtonsNeeded = amountofButtonsNeeded + 1;
                [perfButtonChartNames addObject:chartNameForThisInfoFile];
                //NSLog(@"2 amountofButtonsNeeded %.0d", amountofButtonsNeeded);  
            }else if ([[infoFilesGeneral objectAtIndex:2] rangeOfString:@"Ceiling"].location != NSNotFound  ) {
                amountofButtonsNeeded = amountofButtonsNeeded + 1;
                [perfButtonChartNames addObject:chartNameForThisInfoFile];
                //NSLog(@"3 amountofButtonsNeeded %.0d", amountofButtonsNeeded);  
            }else if ([[infoFilesGeneral objectAtIndex:3] rangeOfString:@"select"].location != NSNotFound  ) {
                amountofButtonsNeeded = amountofButtonsNeeded + 1;
                [perfButtonChartNames addObject:chartNameForThisInfoFile];
                //NSLog(@"4 amountofButtonsNeeded %.0d", amountofButtonsNeeded);  
            }else if ([[infoFilesGeneral objectAtIndex:3] rangeOfString:@"Custom"].location != NSNotFound  ) {
                amountofButtonsNeeded = amountofButtonsNeeded + 1;
                [perfButtonChartNames addObject:chartNameForThisInfoFile];
                //NSLog(@"5 amountofButtonsNeeded %.0d", amountofButtonsNeeded);  
            }else if ([[infoFilesGeneral objectAtIndex:3] isEqualToString:@""]  ) {
                //NSLog(@"nothing  found - make a button but do not write info");
                amountofButtonsNeeded = amountofButtonsNeeded + 1;
                [perfButtonChartNames addObject:chartNameForThisInfoFile];
                //NSLog(@"adding Button for  %@", chartNameForThisInfoFile );
                //NSLog(@"6 amountofButtonsNeeded %.0d", amountofButtonsNeeded);  
            }else if ([[infoFilesGeneral objectAtIndex:3] rangeOfString:@"noButton"].location != NSNotFound  ) {
                //NSLog(@"do not make a button");
                // do not make a button
            }else if ([[infoFilesGeneral objectAtIndex:0] rangeOfString:@"ClimbComp"].location != NSNotFound  ) {                   
                amountofButtonsNeeded = amountofButtonsNeeded + 1;
                 //NSLog(@"6");  
            }else if ([[infoFilesGeneral objectAtIndex:0] rangeOfString:@"CruiseComp"].location != NSNotFound  ) {                   
                amountofButtonsNeeded = amountofButtonsNeeded + 1;
                 //NSLog(@"7");  
            }
            
           
            
        }else{
            
           //NSLog(@"8");
            
            if (infoFilesGeneral.count > 3 & [[infoFilesGeneral objectAtIndex:3] rangeOfString:@"noButton"].location != NSNotFound) {
                //no button
                 //NSLog(@"9");
                
            }else{
                amountofButtonsNeeded = amountofButtonsNeeded + 1;
                 //NSLog(@"10");
            }
                
            
         
            [perfButtonChartNames addObject:chartNameForThisInfoFile];
            //NSLog(@"adding Button for  %@", chartNameForThisInfoFile );
            
           
        }

    }
    
  
    
    //NSLog( @"amountofButtonsNeeded %d", amountofButtonsNeeded);
    
   
    
}




- (void) calcPerformance {
   
 
    triggerSetDefaultsForPerformanceCharts = triggerSetDefaultsForPerformanceCharts + 1;
    
    
    [_arrayExternalLoadRestrictions removeAllObjects];
    float sendFuelWeightKg = _sliderFuelMain1.value * [_inputSpecificFuelMassPerVolume.text floatValue];
    
    //check if hoist er external is activated:
    
    //externalLoadActivated = [[_arrayName8 objectAtIndex:lineExternal] integerValue];
    
    
    if ([[_arrayName8 objectAtIndex:lineExternal] floatValue] > 1 ) {
        externalLoadActivated = 1;
    }else{
        externalLoadActivated = 0;
    }
    
    
    if ([[_arrayName8 objectAtIndex:lineExternal] floatValue] * [[_arrayName2 objectAtIndex:lineExternal] floatValue] > 1 ) {
        externalLoadAttached = 1;
    }else{
        externalLoadAttached = 0;
    }
    
    
    if ([[_arrayName8 objectAtIndex:lineHoistLoad] floatValue] > 1 ) {
        hoistActivated = 1;
    }else{
        hoistActivated = 0;
    }
 
    
    if ([[_arrayName8 objectAtIndex:lineHoistLoad] floatValue] * [[_arrayName2 objectAtIndex:lineHoistLoad] floatValue] > 1 ) {
        hoistLoadAttached = 1;
    }else{
        hoistLoadAttached = 0;
    }
        
    
    //NSLog(@"start lineExternal  %.0f ", lineExternal);
    //NSLog(@"start externalLoadActivated  %d ", externalLoadActivated);
    
 
    
    [calculatePerformanceClass_ transferMethod:OAT sendPA:Hp  sendAltimeterUSA:sliderQNH.value sendHeadWindKts:_sliderHeadwind2.value   sendACweight:weightTOW sendACLandingweight:weightLDW sendSelectedChartButton:selectedChartButton  sendISADiff:ISAdif   sendAltimeterInches:sliderQNH.value sendPenaltyWeight:penaltyWeight sendPenaltyFtMin:penaltyFtMin sendFuelWeight:sendFuelWeightKg sendDA:densityalt sendACWeightUnit:unitsWeight.text sendIAS:_sliderIAS.value sendRatingIndex:_sliderRatingIndex.value sendPROPRPM:_sliderPROPRPM.value sendselectedUnitForItems: selectedUnitForItems ];
    
    
    
    if (triggerDoNotShowPerfChart == 1) {
        [viewMain bringSubviewToFront:viewEnvironment]; viewEnvironment.hidden = NO;
    }
    
    if (displayWindow > 100 & triggerDoNotShowPerfChart == 0) {
        [viewOne bringSubviewToFront:calculatePerformanceClassView_];
        [viewMain bringSubviewToFront:viewEnvironment]; viewEnvironment.hidden = NO;
        calculatePerformanceClassView_.hidden = NO;        
    }else{
        calculatePerformanceClassView_.hidden = YES;
    }
    
    
}// end calc Performance




- (IBAction)actionImportPerfData:(id)sender {
    
    if (![self is_online]) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Error"
                              message:@"Cannot reach server. Please check if this device is online."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        
       }else {
           
           
           alertFlag = 1000;
           
           
           UIAlertView *alert = [[UIAlertView alloc]
                                 
                                 initWithTitle:@"Aircraft Data Reset"
                                 
                                 message:@"This will reset all aircraft data and delete the data from the active flight. Please save or send you load manifest first. Depending on your internet connection the download can take up to a minute or two. Are you sure?"
                                 
                                 delegate:self
                                 
                                 cancelButtonTitle:@"CANCEL"
                                 
                                 
                                 
                                 otherButtonTitles:@"RESET", nil];
           
           [alert show];
           
           
           
                   
           }
    
}



- (void) loadACData {
    importPerformanceData *_importPerformanceData = [[importPerformanceData alloc]init];
    [_importPerformanceData loadPerformanceData: @"loadDataFromFleetControl"];
    [calculatePerformanceClass_ resetPreviousChartName ];
    [self addPerformanceButtons];
    [self importConfigsFromFleetControl];
    [self loadHelicoptersFromServerVoid];
    [self MainRoutine];
    [self anncounceNewACData];
}

- (void) anncounceNewACData {
    
    _viewLoadingData.hidden = YES;    
    //NSLog(@"anncounceNewACData   availableACTypes %@", availableACTypes);
    NSString *acList = @"";
    for(int i =0; i<availableACTypes.count; i++) {
         acList = [acList stringByAppendingString:[availableACTypes objectAtIndex:i]];
         acList = [acList stringByAppendingString:@"\n"];
    }    
   NSString *message = [ [NSString alloc] initWithFormat:@"Loaded AC types: \n\n%@", acList ];
   message = [message stringByAppendingString:@"\nTo create new flights with these aircraft: Open the -Flight Manager- and select \n-Create New Flight-"];
   //NSLog(@"message   %@", message);
   UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Aircraft Data Update"
                          message:message
                          delegate:self
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil];
    [alert show];
}





- (IBAction)actionImportConfigDataFromFleetControl:(id)sender {
    
    if ([self is_online]) {
        
        
        alertFlag = 1020;
        
        
        UIAlertView *alert = [[UIAlertView alloc]
                              
                              initWithTitle:@"Config Data Reset"
                              
                              message:@"This will reset the data from the active flight. Please save or send you load manifest first. Depending on your internet connection the download can take up to a minute. Are you sure?"
                              
                              delegate:self
                              
                              cancelButtonTitle:@"CANCEL"
                              
                              
                              
                              otherButtonTitles:@"RESET", nil];
        
        [alert show];
        

        
        
        
    }else {
        //NSLog(@"Device offline.");
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Can not update Data!"
                              message:@"Device Offline"
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }
    
    return;
}


- (void) importConfigsFromFleetControl {
    

    importConfigurations *_importConfigurations = [[importConfigurations alloc]init];
    [_importConfigurations loadConfigurationData : @"loadDataFromFleetControl"];
        
    // load initial config
    [self loadArrayListo];   
    [self setConfiguration];    
    [self SaveValues];    
    [self createListoItemsSlidersAndInterior];
    [self makeConfigButtons];
    _viewLoadingData.hidden = YES;
    
}



- (void) startImportConfigsFromFleetControl {
    
    _viewLoadingData.hidden = NO;
    [viewOne bringSubviewToFront: _viewLoadingData];
    [_loadDatapinner startAnimating];
    [self performSelector: @selector (importConfigsFromFleetControl) withObject:nil afterDelay: 0.1f];
    
    
    
}









- (IBAction)actionReloadConfigData:(id)sender {
    
  
    importConfigurations *_importConfigurations = [[importConfigurations alloc]init];
    [_importConfigurations loadConfigurationData : @"loadDataFromiPad"];
    
    // load initial config
    [self loadArrayListo];
    [self setConfiguration];
    [self SaveValues];
    [self createListoItemsSlidersAndInterior];
    [self makeConfigButtons];
    
}


- (IBAction)actionReloadPerfData:(id)sender {
    
    importPerformanceData *_importPerformanceData = [[importPerformanceData alloc]init];
    [_importPerformanceData loadPerformanceData: @"loadDataFromiPad"];
    
    [calculatePerformanceClass_ resetPreviousChartName ];
    [self addPerformanceButtons];
    
    triggerSetDefaultsForPerformanceCharts = 0;
    
    [self loadArrayListo];
    [self setConfiguration];
    [self SaveValues];
    [self createListoItemsSlidersAndInterior];
    [self makeConfigButtons];
}






- (IBAction)actionSegment:(id)sender {
    
    [self MainRoutine];
    
}

// special equipment list /***********************************************************************************************'




- (void) loadDefaultEquipmentArrays {
    
    //NSLog(@"loadDefaultEquipmentArrays ");
    //NSLog(@"configuration %d ", configuration);
    //NSLog(@"AC_Type %@ ", AC_Type);
    //NSLog(@"vFlightRegistration %@ ", vFlightRegistration.text);
    
    if (flagSpecialPHIFlightSettingPage == 1) {        
        [self convertPHIEquipment];
    }else{
        [arrayConfigurations setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"arrayConfigurations%@", AC_Type] ] mutableCopy]];    
        NSString *configName = [arrayConfigurations[configuration] stringByReplacingOccurrencesOfString:@" " withString:@""]   ;    
        NSString *key;    
        if ([[_arrayName2 objectAtIndex:0] isEqualToString:@"noReg"] || [[_arrayName2 objectAtIndex:0] isEqualToString:@""]) {
            key = [NSString stringWithFormat:@"defaultEquip_%@_%@", @"noReg" , configName];
        }else{        
            key = [NSString stringWithFormat:@"defaultEquip_%@_%@", vFlightRegistration.text, configName]; 
        }
        [arrayPackageName setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayPackageName"]] mutableCopy]];
        [arrayConfigItemName setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemName"]] mutableCopy]];
        [arrayConfigItemWeight setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemWeight"]] mutableCopy]];
        [arrayConfigItemArmLong setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemArmLong"]] mutableCopy]];
        [arrayConfigItemMomLong setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemMomLong"]] mutableCopy]];
        [arrayConfigItemArmLat setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemArmLat"]] mutableCopy]];
        [arrayConfigItemMomLat setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemMomLat"]] mutableCopy]];
        [arrayConfigIteminOut setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigIteminOut"]] mutableCopy]];
        [arrayConfigItemLocked setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemLocked"]] mutableCopy]];
        [arrayConfigItemData setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemData"]] mutableCopy]];
        [arrayConfigItemMoved setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemMoved"]] mutableCopy]];
        [arrayConfigItemAltLong setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemAltLong"]] mutableCopy]];
        [arrayConfigItemAltLat setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemAltLat"]] mutableCopy]];
        [arrayConfigItemMovable setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemMovable"]] mutableCopy]];
        [arrayConfigItemTrigger setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemTrigger"]] mutableCopy]];
        [arrayConfigItemItemR1 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemItemR1"]] mutableCopy]];
        [arrayConfigItemItemR2 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemItemR2"]] mutableCopy]];
        [arrayConfigItemItemR3 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemItemR3"]] mutableCopy]];
        
    }
    
   
}


- (IBAction)actionViewSpecialEquipList:(id)sender {
    
    //NSLog(@"actionViewSpecialEquipList ");
    
    
    guidanceDictionary[@"guidanceBtnSetEquipment"] =  @"ok";
    if (_viewSpecialEquiplist.hidden == YES) {
        _viewSpecialEquiplist.hidden = NO;
        [viewOne bringSubviewToFront:_viewSpecialEquiplist];
        [viewOne bringSubviewToFront:viewTopTop];        
        [self createSpecialEquipListItems];
    }else{
        _viewSpecialEquiplist.hidden = YES;
    }
    [self SaveValues];
    [self MainRoutine];
}


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


// step 1

- (IBAction)actionDropDownAvailableACTypes:(id)sender {
    
    //NSLog(@"1 actionDropDownAvailableACTypes ...");
    
    NSMutableArray *specialArrayAvailableCallsigns = [[NSMutableArray alloc] init];
    [specialArrayAvailableCallsigns setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"arrayConfigButtonsRegistration%@", _dropDownAvailableACTypes.text] ] mutableCopy]];
    //NSLog(@"specialArrayAvailableCallsigns %@", specialArrayAvailableCallsigns);
    
    
    NSMutableArray *specialArrayConfigurations = [[NSMutableArray alloc] init];
    [specialArrayConfigurations setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"arrayConfigurations%@", _dropDownAvailableACTypes.text] ] mutableCopy]];
    //NSLog(@"1 kill");
    //NSLog(@"specialArrayConfigurations %@", specialArrayConfigurations);
    
    
    NSMutableArray *specialArrayAvailableCallsignAndConfig = [[NSMutableArray alloc] init];
    
    for(int i =0; i<specialArrayAvailableCallsigns.count; i++) {
        
        NSString *callsignConfigCombination = [NSString stringWithFormat:@"%@ >%@", [specialArrayAvailableCallsigns objectAtIndex:i], [specialArrayConfigurations objectAtIndex:i]    ];
        
        [specialArrayAvailableCallsignAndConfig addObject:callsignConfigCombination];
        
    }
    
    //NSLog(@"specialArrayAvailableCallsignAndConfig  %@", specialArrayAvailableCallsignAndConfig);
    
    
    
    _dropDownAvailableCallsigns.items = specialArrayAvailableCallsignAndConfig;
    
    _dropDownAvailableCallsigns.text = @"select";
    
    
}

// step 2

- (IBAction)actionDropDownAvailableCallsigns:(id)sender {
    
    //NSLog(@"actionDropDownAvailableCallsigns ...");
    
    
    
    NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@">"];
    NSArray *components = [_dropDownAvailableCallsigns.text componentsSeparatedByCharactersInSet:charSet];
    
    alternateACType = _dropDownAvailableACTypes.text;
    
    alternateCallsign = [[components objectAtIndex:0] stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    alternateConfig = [[components objectAtIndex:1] stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    //NSLog(@"alternateACType %@", alternateACType);
    //NSLog(@"alternateCallsign %@", alternateCallsign);
    //NSLog(@"alternateConfig %@", alternateConfig);
    
    flagUsingAlternateEquipment = 1;
    
    [self loadAlternateEquipmentArrays];
    
    [self createSpecialEquipListItems];
    
    [self computeSpecialEquipmentTotals];
    
    [self MainRoutine];
    
}






- (void) loadAlternateEquipmentArrays {
    //NSLog(@"loadAlternateEquipmentArrays ");
    
    //NSLog(@"configuration %d ", configuration);
    //NSLog(@"AC_Type %@ ", AC_Type);
    //NSLog(@"vFlightRegistration %@ ", vFlightRegistration.text);
    
    [arrayConfigurations setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"arrayConfigurations%@", alternateACType] ] mutableCopy]];
   
    //NSLog(@"arrayConfigurations %@ ", arrayConfigurations);
    //NSLog(@"config name  %@ ", [arrayConfigurations objectAtIndex:configuration]);
    //NSString *configName = [arrayConfigurations[configuration] stringByReplacingOccurrencesOfString:@" " withString:@""]   ;
    //NSString *key = [NSString stringWithFormat:@"defaultEquip_%@_%@", vFlightRegistration.text, configName];
    
    NSString *configName = alternateConfig;
    
    
    NSString *key = [NSString stringWithFormat:@"defaultEquip_%@_%@", alternateCallsign, configName];
    
    [arrayPackageName setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayPackageName"]] mutableCopy]];
    [arrayConfigItemName setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemName"]] mutableCopy]];
    [arrayConfigItemWeight setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemWeight"]] mutableCopy]];
    [arrayConfigItemArmLong setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemArmLong"]] mutableCopy]];
    [arrayConfigItemMomLong setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemMomLong"]] mutableCopy]];
    [arrayConfigItemArmLat setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemArmLat"]] mutableCopy]];
    [arrayConfigItemMomLat setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemMomLat"]] mutableCopy]];
    [arrayConfigIteminOut setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigIteminOut"]] mutableCopy]];
    [arrayConfigItemLocked setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemLocked"]] mutableCopy]];
    [arrayConfigItemData setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemData"]] mutableCopy]];
    [arrayConfigItemMoved setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemMoved"]] mutableCopy]];
    [arrayConfigItemAltLong setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemAltLong"]] mutableCopy]];
    [arrayConfigItemAltLat setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemAltLat"]] mutableCopy]];
    [arrayConfigItemMovable setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemMovable"]] mutableCopy]];
    [arrayConfigItemTrigger setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemTrigger"]] mutableCopy]];
    [arrayConfigItemItemR1 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemItemR1"]] mutableCopy]];
    [arrayConfigItemItemR2 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemItemR2"]] mutableCopy]];
    [arrayConfigItemItemR3 setArray: [[[NSUserDefaults standardUserDefaults] objectForKey:[key stringByAppendingString:@"arrayConfigItemItemR3"]] mutableCopy]];
    
    //NSLog(@"arrayConfigItemName %@ ", arrayConfigItemName);
    
    
}


- (void) createSpecialEquipListItemsForManifest {
    
    
    //NSLog(@"createSpecialEquipListItemsForManifest ");    
    NSString *equipUnitLength =@"";
    
    if ([selectedUnitForItems isEqualToString:@"lbs"]) {
        _labelSpecialEquipUnitMass.text = @"lbs";
        _labelSpecialEquipUnitMass2.text = @"lbs";
        _labelSpecialEquipUnitLong.text = @"lbs.In";
        _labelSpecialEquipUnitLong2.text = @"lbs.In";
        _labelSpecialEquipUnitLat.text = @"lbs.In";
        _labelSpecialEquipUnitLat2.text = @"lbs.In";
        equipUnitLength = @"In";
    }else{
        _labelSpecialEquipUnitMass.text = @"kg";
        _labelSpecialEquipUnitMass2.text = @"kg";
        _labelSpecialEquipUnitLong.text = @"kg.mm";
        _labelSpecialEquipUnitLong2.text = @"kg.mm";
        _labelSpecialEquipUnitLat.text = @"kg.mm";
        _labelSpecialEquipUnitLat2.text = @"kg.mm";
        equipUnitLength = @"mm";
    }
    
    // check if we need to convert the list"    
    
    for(UIView *subview in [_viewEquipmentListOverManifest subviews]) {
        [subview removeFromSuperview];
    }    
    
    float xPos1 = 20;
    float yGap = 40;
    float xGap = 90;
    float xGap2 = 80;
    int itemCount = -1;
    float kneiffer = 0;
    float kneiffer2 = 0;    
    
    kneiffer = -120;
    kneiffer2 = -70;
    
    float xRow = 0;
    
    int itemNumber = 0;
    
    int yCount = 0;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1 + 10 + xRow, 30  , 500 +  kneiffer2, 30)];
    label.font = [UIFont boldSystemFontOfSize:20];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = [UIColor blackColor];
    [label  setText: @"Equipment On Board"];           
    
    [_viewEquipmentListOverManifest addSubview: label];
    
    
    float totalEWeight = 0;
    float totalEArm = 0;
    float totalEArmLat = 0;
    
    for(int i =0; i<arrayConfigItemName.count; i++) {    
        
       
        
        itemCount = itemCount + 1;
        yCount = yCount + 1;
        
        if ([[arrayConfigItemName objectAtIndex: i ] isEqualToString:@"DrawLine"]) {
            //NSLog(@"DrawLine");
            // DrawLine
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0 , (itemCount *yGap)  , 900, 30)];
            textField.borderStyle = UITextBorderStyleNone;
            textField.minimumFontSize = 5;
            textField.font = [UIFont boldSystemFontOfSize:14];
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            textField.textAlignment = NSTextAlignmentLeft;
            textField.enabled = NO;
            textField.backgroundColor = [UIColor clearColor];
            textField.textColor = [UIColor blackColor];
            [textField addTarget:self
                          action:@selector(closeKeyboard:)
                forControlEvents:UIControlEventEditingDidEndOnExit];
            [textField  setText: @"--------------------------------------------------------------------------------------------------------------------------"];
            textField.tag = i+1000;
            [_viewEquipmentListOverManifest addSubview: textField];
            
        }else if ([[arrayConfigItemName objectAtIndex: i ] isEqualToString:@"PackageName"]  || [[arrayConfigItemName objectAtIndex: i ] isEqualToString:@"Package"]  ) {
            //NSLog(@"PackageName");
            //package name
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0 ,  (itemCount *yGap)  , 1024, 35)];
            textField.borderStyle = UITextBorderStyleNone;
            textField.minimumFontSize = 5;
            textField.font = [UIFont boldSystemFontOfSize:17];
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            textField.textAlignment = NSTextAlignmentLeft;
            textField.enabled = NO;
            textField.backgroundColor = [UIColor blackColor];
            textField.textColor = [UIColor blackColor];
            
            [textField addTarget:self
                          action:@selector(closeKeyboard:)
                forControlEvents:UIControlEventEditingDidEndOnExit];
            [textField  setText: [arrayPackageName objectAtIndex: i ]   ];
            [textField  setText: [NSString stringWithFormat:@"     Package: %@", [arrayPackageName objectAtIndex: i ]  ]   ];
            textField.tag = i+1000;
            [_viewEquipmentListOverManifest addSubview: textField];
            // package in / out button
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(xPos1 + ( 7 * xGap) + xGap2 + 50 + kneiffer,  (itemCount *yGap)  , 120, 35);
            [btn addTarget:self
                    action:@selector(actionPackageInOut:)
          forControlEvents:UIControlEventTouchUpInside];
            btn.tag = i+30000;
            //NSLog(@"make btn.tag %d", btn.tag);
            [btn setTitle: @"ALL IN/OUT" forState: UIControlStateNormal];
            btn.backgroundColor = [UIColor whiteColor];
            [btn  setBackgroundImage:[UIImage imageNamed: @"button blue top184x52.png" ] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            if ([[arrayConfigItemLocked objectAtIndex: i ] isEqualToString:@"locked"]) {
                btn.enabled = NO;
                [btn setTitle: @"LOCKED" forState: UIControlStateNormal];
                [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            }else{
                btn.enabled = YES;
            }
            //[btn  setBackgroundImage:[UIImage imageNamed: @"button minus red.png" ] forState:UIControlStateNormal];
            [_viewEquipmentListOverManifest addSubview:btn];
            
        }else{
            
            itemNumber = itemNumber + 1;
          
            
            if (itemNumber == 25) {
                yCount = 1;
                xRow = 300;
            }
            
            if (itemNumber == 50) {
                yCount = 1;
                xRow = 600;
            }
            
            // in / out button
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(0 ,  (itemCount *yGap)  , 50, 30);
            [btn addTarget:self
                    action:@selector(actionSpecialEquipmentInOut:)
          forControlEvents:UIControlEventTouchUpInside];
            btn.tag = i+20000;
            //NSLog(@"make btn.tag %d", btn.tag);
                        
            // item name
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1 + 10 + xRow, 25 + (yCount *yGap)- 6  , 500 +  kneiffer2, 30)];
            label.font = [UIFont boldSystemFontOfSize:13];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor blackColor];
             if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"OUT"] ) {
                  label.textColor = [UIColor redColor];
                  [label  setText: [NSString stringWithFormat:@"%d OUT: %@",itemNumber, [arrayConfigItemName objectAtIndex: i ] ]   ];        
             }else{
                 [label  setText: [NSString stringWithFormat:@"%d: %@",itemNumber, [arrayConfigItemName objectAtIndex: i ] ]   ];        
                 
             }
               
            label.tag = i + 75000;
            [_viewEquipmentListOverManifest addSubview: label];
            
            
            // item data
            label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1 + 10 + xRow,   25 + (yCount *yGap) + 11  , 300, 30)];
            label.font = [UIFont boldSystemFontOfSize:12];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor darkGrayColor];            
            float replaceArmLong =0;
            float replaceArmLat =0;            
            replaceArmLong = [ [arrayConfigItemArmLong objectAtIndex: i ] floatValue];
            replaceArmLat = [[arrayConfigItemArmLat objectAtIndex: i ] floatValue];
            
            
            //NSLog(@"arrayConfigItemArmLong %@", arrayConfigItemArmLong );
            
            
            if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"ALT"] ) {
                replaceArmLong = [[arrayConfigItemAltLong objectAtIndex:i] floatValue];
                replaceArmLat = [[arrayConfigItemAltLat objectAtIndex:i] floatValue];
                label.textColor = lightOrangeColor;
            }
            
            if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"MOVED"]) {
                NSString *text = [arrayConfigItemMoved objectAtIndex: i  ];
                NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@":"];
                NSArray *arrayComponents = [text componentsSeparatedByCharactersInSet:charSet1];
                replaceArmLong = [[arrayComponents objectAtIndex:0] floatValue];
                replaceArmLat = [[arrayComponents objectAtIndex:1] floatValue];
                label.textColor = lightBlueColor;
            }
            
            float convertedWeight, convertedArm, convertedArmLat;
            
            convertedWeight = [[arrayConfigItemWeight objectAtIndex: i ] floatValue];
            convertedArm = replaceArmLong;
            convertedArmLat = replaceArmLat;
            
            if ([[_arrayName21 objectAtIndex: 5  ] isEqualToString:@"lbs"] & [selectedUnitForItems isEqualToString:@"kg"]) {
                //convert from original lbs to kg  and inches to mm
                convertedWeight = convertedWeight / 2.2046;
                convertedArm = convertedArm * 25.4;
                convertedArmLat = convertedArmLat * 25.4;
            }
            if ([[_arrayName21 objectAtIndex: 5  ] isEqualToString:@"kg"] & [selectedUnitForItems isEqualToString:@"lbs"]) {
                //convert from original kg to lbs  and mm to inches
                convertedWeight = convertedWeight * 2.2046;
                convertedArm = convertedArm / 25.4;
                convertedArmLat = convertedArmLat / 25.4;
            }
            
            
            
            
         
            
           
            
            
           
            if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"OUT"] ) {
                [label  setText: @""];
                
                  [label  setText: [NSString stringWithFormat:@"(%.1f%@, Long: %.0f%@, Lat: %.0f%@)",  convertedWeight, _labelSpecialEquipUnitMass.text, replaceArmLong, equipUnitLength, replaceArmLat, equipUnitLength   ]];
                
            }else{
                    [label  setText: [NSString stringWithFormat:@"%.1f%@, Long: %.0f%@, Lat: %.0f%@",  convertedWeight, _labelSpecialEquipUnitMass.text, replaceArmLong, equipUnitLength, replaceArmLat, equipUnitLength   ]];
                 totalEWeight =  totalEWeight + convertedWeight;
            }
            
            
            label.tag = i + 70000;
            [_viewEquipmentListOverManifest addSubview: label];
            
            
            //NSLog(@"[arrayConfigItemMovable objectAtIndex: i  ] %@", [arrayConfigItemMovable objectAtIndex: i  ] );
            
            
            
        }       // end else is line
    }
    
    yCount = yCount + 1;
    
    label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1 + 10 + xRow, 35 + (yCount *yGap)- 6  , 500 +  kneiffer2, 30)];
    //label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1 + 12 + xRow, 30  , 500 +  kneiffer2, 30)];
    label.font = [UIFont boldSystemFontOfSize:17];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = [UIColor blackColor];
    [label  setText: [NSString stringWithFormat:@"Total Weight: %.1f%@",  totalEWeight, _labelSpecialEquipUnitMass.text ]];          
    
    [_viewEquipmentListOverManifest addSubview: label];
    
    
    
    
}

- (void) createSpecialEquipListItems {
    
    
    _viewAddStation.hidden = YES;
    _viewAddEquipmentItem.hidden = YES;
    
    //NSLog(@"createSpecialEquipListItems selectedUnitForItems %@", selectedUnitForItems);
    
    NSString *equipUnitLength =@"";
    
    _labelEquipListName.text = _dropDownAvailablePHIEquipLists.text;
    
    if ([selectedUnitForItems isEqualToString:@"lbs"]) {
        _labelSpecialEquipUnitMass.text = @"lbs";
        _labelSpecialEquipUnitMass2.text = @"lbs";
        _labelSpecialEquipUnitLong.text = @"lbs.In";
        _labelSpecialEquipUnitLong2.text = @"lbs.In";
        _labelSpecialEquipUnitLat.text = @"lbs.In";
        _labelSpecialEquipUnitLat2.text = @"lbs.In";
        equipUnitLength = @"In";
    }else{
        _labelSpecialEquipUnitMass.text = @"kg";
        _labelSpecialEquipUnitMass2.text = @"kg";
        _labelSpecialEquipUnitLong.text = @"kg.mm";
        _labelSpecialEquipUnitLong2.text = @"kg.mm";
        _labelSpecialEquipUnitLat.text = @"kg.mm";
        _labelSpecialEquipUnitLat2.text = @"kg.mm";
        equipUnitLength = @"mm";
    }
    
    // check if we need to convert the list"    
    for(UIView *subview in [_viewConfiguratorStationItems subviews]) {
        [subview removeFromSuperview];
    }
    for(UIView *subview in [_viewEquipmentOnHeli subviews]) {
        [subview removeFromSuperview];
    }
    
    //NSLog(@"_labelSpecialEquipUnitMass %@", _labelSpecialEquipUnitMass.text);    
    _dropDownAvailableACTypes.items = availableACTypes;    
    //NSLog(@"arrayConfigItemName %@", arrayConfigItemName);
    
    float xPos1 = 50;
    float yGap = 40;
    float xGap = 90;
    float xGap2 = 80;
    int itemCount = -1;
    float kneiffer = 0;
    float kneiffer2 = 0;
    
    if (flagIsLandscape == 1) {
        kneiffer = 0;
        kneiffer2 = 0;
    }else{
        kneiffer = -120;
        kneiffer2 = -90;
    }    
    kneiffer = -120;
    kneiffer2 = -70;
    int itemNumber = 0;
    
    if ([_labelConfigurationName2.text isEqualToString:@""]) {
        if (arrayConfigurations.count > 1) {
            _labelConfigurationName2.text = arrayConfigurations[configuration]; 
        }
    }
    _labelSpecialEquipConfigName.text = _labelConfigurationName2.text;
  
    
    //NSLog(@"arrayPackageName .count %@", arrayPackageName);
    //NSLog(@"arrayConfigItemName .count %@", arrayConfigItemName);
                       
                       
    for(int i =0; i<arrayConfigItemName.count; i++) {
        
        //NSLog(@"drawing %d %@", i, [arrayConfigItemName objectAtIndex: i ]);
    
       
        
        itemCount = itemCount + 1;
        
        
        
        
        if ([[arrayConfigItemName objectAtIndex: i ] isEqualToString:@"DrawLine"]) {
            //NSLog(@"DrawLine");
            // DrawLine
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0 , (itemCount *yGap)  , 900, 30)];
            textField.borderStyle = UITextBorderStyleNone;
            textField.minimumFontSize = 5;
            textField.font = [UIFont boldSystemFontOfSize:14];
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            textField.textAlignment = NSTextAlignmentLeft;
            textField.enabled = NO;
            textField.backgroundColor = [UIColor clearColor];
            textField.textColor = [UIColor whiteColor];
            [textField addTarget:self
                          action:@selector(closeKeyboard:)
                forControlEvents:UIControlEventEditingDidEndOnExit];
            [textField  setText: @"--------------------------------------------------------------------------------------------------------------------------"];
            textField.tag = i+1000;
            [_viewConfiguratorStationItems addSubview: textField];
            
        }else if ([[arrayConfigItemName objectAtIndex: i ] isEqualToString:@"PackageName"]  || [[arrayConfigItemName objectAtIndex: i ] isEqualToString:@"Package"]  ) {
    
            //NSLog(@"1111 [arrayPackageName objectAtIndex: i ]  %@", [arrayPackageName objectAtIndex: i ] );
            
            //package name
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(110 ,  (itemCount *yGap)  , 1024, 35)];
            textField.borderStyle = UITextBorderStyleNone;
            textField.minimumFontSize = 5;
            textField.font = [UIFont boldSystemFontOfSize:16];
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            textField.textAlignment = NSTextAlignmentLeft;
            textField.enabled = NO;
            textField.backgroundColor = [UIColor lightGrayColor];
            textField.textColor = [UIColor blackColor];              
            //example
            //|noReg;Demo Config;Test;Medical Pack;12;5800;69600;200;2400;;IN;sp;a1;a2;MOVABLE;;r1;r2;r3|
            [textField addTarget:self
                          action:@selector(closeKeyboard:)
                forControlEvents:UIControlEventEditingDidEndOnExit];
            [textField  setText: [arrayPackageName objectAtIndex: i ]   ];
        
            [textField  setText: [NSString stringWithFormat:@"     Package: %@", [arrayPackageName objectAtIndex: i ]  ]   ];
            textField.tag = i+1000;
            [_viewConfiguratorStationItems addSubview: textField];
                               
            // package in / out button
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(0,  (itemCount *yGap)  , 120, 35);
            [btn addTarget:self
                    action:@selector(actionPackageInOut:)
          forControlEvents:UIControlEventTouchUpInside];
            btn.tag = i+30000;
            //NSLog(@"make btn.tag %d", btn.tag);
            [btn setTitle: @"PACK IN/OUT" forState: UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:14];
            btn.backgroundColor = [UIColor whiteColor];
            btn.showsTouchWhenHighlighted = YES;
            [btn  setBackgroundImage:[UIImage imageNamed: @"button blue top184x52.png" ] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            if ([[arrayConfigItemLocked objectAtIndex: i ] isEqualToString:@"locked"]) {
                btn.enabled = NO;
                [btn setTitle: @"LOCKED" forState: UIControlStateNormal];
                [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            }else{
                btn.enabled = YES;
            }
            
            [_viewConfiguratorStationItems addSubview:btn];
            
            // **********************************************************
            // add item button
            btn = [UIButton buttonWithType:UIButtonTypeCustom];
            if (flagIsLandscape == 1) {
                btn.frame = CGRectMake(455+70,  (itemCount *yGap)  , 50, 35);
            }else{
                btn.frame = CGRectMake(362+70,  (itemCount *yGap)  , 50, 35);
            }
            
            [btn addTarget:self
                    action:@selector(actionAddItemToPackage:)
            forControlEvents:UIControlEventTouchUpInside];
            btn.tag = i+35000;
            //NSLog(@"make btn.tag %d", btn.tag);
            [btn setTitle: @"+" forState: UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:16];
            btn.backgroundColor = [UIColor whiteColor];
            btn.showsTouchWhenHighlighted = YES;
            [btn  setBackgroundImage:[UIImage imageNamed: @"button blue top184x52.png" ] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [_viewConfiguratorStationItems addSubview:btn];
            
            
            
            
            
        }else{
            
            //NSLog(@"2222 [arrayPackageName objectAtIndex: i ]  %@", [arrayPackageName objectAtIndex: i ] );
            
            itemNumber = itemNumber + 1;
            int flagAlternate = 0;            
            // in / out button
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(0 ,  (itemCount *yGap)  , 50, 30);
            [btn addTarget:self
                    action:@selector(actionSpecialEquipmentInOut:)
          forControlEvents:UIControlEventTouchUpInside];
            btn.tag = i+20000;
            //NSLog(@"make btn.tag %d", btn.tag);            
            //NSLog(@"1");            
            if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"OUT"] ) {
                [btn setTitle: @"OUT" forState: UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:16];
                btn.backgroundColor = [UIColor redColor];
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                                
                if ([[arrayConfigItemLocked objectAtIndex: i ] isEqualToString:@"locked"]) {
                    [btn setTitle: @"" forState: UIControlStateNormal];
                }
            }
            if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"IN"] ) {
                [btn setTitle: @"IN" forState: UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:16];
                btn.backgroundColor = [UIColor greenColor];
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                if ([[arrayConfigItemLocked objectAtIndex: i ] isEqualToString:@"locked"]) {
                    [btn setTitle: @"" forState: UIControlStateNormal];
                }
            }
            
            if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"ALT"] ) {
                [btn setTitle: @"ALT" forState: UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:16];
                btn.backgroundColor = lightOrangeColor;
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                flagAlternate = 1;
            }
          
            
            if ([[arrayConfigIteminOut objectAtIndex:i] isEqualToString:@"MOVED"]) {
                [btn setTitle: @"MOVED" forState: UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:13];
                btn.backgroundColor = [UIColor blueColor];
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                
            }
            
            
            if ([[arrayConfigItemLocked objectAtIndex: i ] isEqualToString:@"locked"]) {
                btn.enabled = NO;
            }else{
                btn.enabled = YES;
            }
            [_viewConfiguratorStationItems addSubview:btn];
            
            // show item button
            btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(60 ,  (itemCount *yGap)  , 250, 30);
            [btn addTarget:self
                    action:@selector(actionShowEquipItem:)
          forControlEvents:UIControlEventTouchUpInside];
            btn.tag = i+90000;
            btn.backgroundColor = [UIColor clearColor];
            [_viewConfiguratorStationItems addSubview:btn];
            
            if ([[arrayConfigItemLocked objectAtIndex: i ] isEqualToString:@"locked"]) {
                UIImageView *image =[[UIImageView alloc] initWithFrame:CGRectMake(14, (itemCount *yGap) + 3 ,25,25)];
                image.image=[UIImage imageNamed:@"lockBlack.png"];
                [btn setTitle: @"" forState: UIControlStateNormal];
                [_viewConfiguratorStationItems addSubview:image];
                UIImageView *darkImage =[[UIImageView alloc] initWithFrame:CGRectMake(0,  (itemCount *yGap) ,50,30)];
                darkImage.backgroundColor = [UIColor blackColor];
                darkImage.alpha = 0.3;
                [_viewConfiguratorStationItems addSubview:darkImage];
            }
            
            // get alternate long and lat
            NSString *replaceLong;
            NSString *replaceLat;
            float armLong = 0;
            float armLat = 0;
            if (flagAlternate == 1) {
                
                armLong = [[arrayConfigItemAltLong objectAtIndex:1] floatValue];
                armLat = [[arrayConfigItemAltLong objectAtIndex:1] floatValue];
                replaceLong = [NSString stringWithFormat:@"%.0f",armLong ];
                replaceLat = [NSString stringWithFormat:@"%.0f",armLat ];
                //NSLog(@"replaceLong %@", replaceLong);
                //NSLog(@"replaceLat %@", replaceLat);
            }
            
            if (_viewConfigurator.hidden == NO) {
                // create symbols on heli
                float itemLong = 0;
                float itemLat  = 0;
                if (flagAlternate == 1) {
                    itemLong = armLong;
                    itemLat  = armLat;
                }else{
                    
                    if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"MOVED"]) {
                        NSString *text = [arrayConfigItemMoved objectAtIndex: i  ];
                        NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@":"];
                        NSArray *arrayComponents = [text componentsSeparatedByCharactersInSet:charSet1];
                        itemLong = [[arrayComponents objectAtIndex:0] floatValue];
                        itemLat = [[arrayComponents objectAtIndex:1] floatValue];
                        
                    }else{
                        
                        itemLong = [ [arrayConfigItemArmLong objectAtIndex: i ] floatValue];
                        itemLat  = [ [arrayConfigItemArmLat objectAtIndex: i  ] floatValue];
                    }
                    
                }
                
                float LongScale = (_viewMeasureRearSeats.center.y - _viewMeasureFrontSeats.center.y) / (LongArmRearSeat - LongArmFrontSeat) ;
                float LatPixLeftSeat    = _viewMeasureCenter.center.x;
                float LatPixRightSeat  = _viewMeasureLatRight.center.x;
                float LatScale = (LatPixRightSeat - LatPixLeftSeat) / (LatArmRightSeat - LatArmLeftSeat) ;
                float itemWidth = 20;
                float itemHeight = 20;
                float LongPixPosition = 0;
                float LatPixPosition = 0;
                float yOffset = 0;
                float latOffset = 0;
                
                UILabel *label =[[UILabel alloc] initWithFrame:CGRectMake(LatPixPosition + latOffset, LongPixPosition + yOffset, itemWidth , itemHeight ) ];
                label.textAlignment = NSTextAlignmentCenter;
                label.font = [UIFont boldSystemFontOfSize:14];
                
                if (flagAlternate == 1) {
                    label.backgroundColor = lightOrangeColor;
                }else{
                    if ([[arrayConfigIteminOut objectAtIndex:i] isEqualToString:@"MOVED"]) {
                        label.backgroundColor = [UIColor blueColor];
                        label.textColor = [UIColor whiteColor];
                    }else{
                        
                        if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"OUT"] ) {
                            label.backgroundColor = [UIColor redColor];
                            label.textColor = [UIColor whiteColor];
                        }else{
                            label.backgroundColor = [UIColor whiteColor];
                            label.textColor = [UIColor blackColor];
                        }
                        
                        
                    }
                    
                }
                
                LongPixPosition =  (( (LongScale * (itemLong - LongArmFrontSeat)) + _viewMeasureFrontSeats.center.y  )  - (itemHeight/2))   ;
                LatPixPosition =   ( (LatScale *  (itemLat -  LatArmLeftSeat))   + LatPixLeftSeat      )  - (itemWidth/2);
                label.frame = CGRectMake(LatPixPosition + latOffset, LongPixPosition + yOffset, itemWidth , itemHeight );
                label.text = [NSString stringWithFormat:@"%d",itemNumber];
                label.tag = i + 50000;
                [_viewEquipmentOnHeli addSubview:label];
                
                
                
                
            }else{
                // if view hidden
                
            }
            
            
            // item name
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1 + 10 ,  (itemCount *yGap)- 6  , 500 +  kneiffer2, 30)];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor whiteColor];
            [label  setText: [NSString stringWithFormat:@"%d: %@",itemNumber,  [arrayConfigItemName objectAtIndex: i ] ]   ];
            if (flagAlternate == 1) {
                label.textColor = lightOrangeColor;
            }
            label.tag = i + 75000;
            [_viewConfiguratorStationItems addSubview: label];
            
            
            // item data
            label = [[UILabel alloc] initWithFrame:CGRectMake(xPos1 + 10,  (itemCount *yGap) + 11  , 300, 30)];
            label.font = [UIFont boldSystemFontOfSize:13];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];
            
            float replaceArmLong =0;
            float replaceArmLat =0;
            
            replaceArmLong = [ [arrayConfigItemArmLong objectAtIndex: i ] floatValue];
            replaceArmLat = [[arrayConfigItemArmLat objectAtIndex: i ] floatValue];
            
            if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"ALT"] ) {
                replaceArmLong = [[arrayConfigItemAltLong objectAtIndex:i] floatValue];
                replaceArmLat = [[arrayConfigItemAltLat objectAtIndex:i] floatValue];
                label.textColor = lightOrangeColor;
            }
            
            if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"MOVED"]) {
                NSString *text = [arrayConfigItemMoved objectAtIndex: i  ];
                NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@":"];
                NSArray *arrayComponents = [text componentsSeparatedByCharactersInSet:charSet1];
                replaceArmLong = [[arrayComponents objectAtIndex:0] floatValue];
                replaceArmLat = [[arrayComponents objectAtIndex:1] floatValue];
                label.textColor = lightBlueColor;
            }
            
            float convertedWeight, convertedArm, convertedArmLat;
            
            convertedWeight = [[arrayConfigItemWeight objectAtIndex: i ] floatValue];
            convertedArm = replaceArmLong;
            convertedArmLat = replaceArmLat;
            if (_arrayName21.count > 5) {
                if ([[_arrayName21 objectAtIndex: 5  ] isEqualToString:@"lbs"] & [selectedUnitForItems isEqualToString:@"kg"]) {
                    //convert from original lbs to kg  and inches to mm
                    convertedWeight = convertedWeight / 2.2046;
                    convertedArm = convertedArm * 25.4;
                    convertedArmLat = convertedArmLat * 25.4;
                }
                if ([[_arrayName21 objectAtIndex: 5  ] isEqualToString:@"kg"] & [selectedUnitForItems isEqualToString:@"lbs"]) {
                    //convert from original kg to lbs  and mm to inches
                    convertedWeight = convertedWeight * 2.2046;
                    convertedArm = convertedArm / 25.4;
                    convertedArmLat = convertedArmLat / 25.4;
                }
            }
            
            
            
            
            
        
            [label  setText: [NSString stringWithFormat:@"%.1f%@, Long: %.0f%@, Lat: %.0f%@",  convertedWeight, _labelSpecialEquipUnitMass.text, replaceArmLong, equipUnitLength, replaceArmLat, equipUnitLength   ]];
            
            if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"OUT"] ) {
                [label  setText: @""];
            }
            label.tag = i + 70000;
            [_viewConfiguratorStationItems addSubview: label];
            
            
            //NSLog(@"[arrayConfigItemMovable objectAtIndex: i  ] %@", [arrayConfigItemMovable objectAtIndex: i  ] );
            
            
            
            if ( [[arrayConfigItemMovable objectAtIndex: i  ] isEqualToString:@"MOVABLE"]) {
                
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.titleLabel.font = [UIFont systemFontOfSize:16];
                
                if (flagIsLandscape == 1) {
                    btn.frame = CGRectMake(470,  (itemCount *yGap)  , 100, 35);
                }else{
                    btn.frame = CGRectMake(410,  (itemCount *yGap)  , 70, 35);
                    
                }
                
                [btn addTarget:self
                        action:@selector(actionMoveEquipItem:)
              forControlEvents:UIControlEventTouchUpInside];
                btn.tag = i+40000;
                //NSLog(@"make btn.tag %d", btn.tag);
                [btn setTitle: @"MOVE" forState: UIControlStateNormal];
                btn.backgroundColor = [UIColor blueColor];
                //[btn  setBackgroundImage:[UIImage imageNamed: @"button blue top184x52.png" ] forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [_viewConfiguratorStationItems addSubview:btn];
                
                if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"OUT"] || [[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"ALT"]  || [[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"MOVED"] ) {
                    btn.hidden = YES;
                    
                }
            }
            
            
            if ( ![[arrayConfigItemAltLong objectAtIndex: i  ] isEqualToString:@""]) {
                
                
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.titleLabel.font = [UIFont systemFontOfSize:16];
                
                if ( [[arrayConfigItemMovable objectAtIndex: i  ] isEqualToString:@"MOVABLE"]) {
                    
                    if (flagIsLandscape == 1) {
                        btn.frame = CGRectMake(370,  (itemCount *yGap)  , 100, 35);
                        [btn setTitle: @"ALTERNATE" forState: UIControlStateNormal];
                    }else{
                        btn.frame = CGRectMake(340,  (itemCount *yGap)  , 70, 35);
                        [btn setTitle: @"ALT" forState: UIControlStateNormal];
                        
                    }
                    
                }else{
                    if (flagIsLandscape == 1) {
                        btn.frame = CGRectMake(470,  (itemCount *yGap)  , 100, 35);
                        [btn setTitle: @"ALTERNATE" forState: UIControlStateNormal];
                    }else{
                        btn.frame = CGRectMake(410,  (itemCount *yGap)  , 70, 35);
                        [btn setTitle: @"ALT" forState: UIControlStateNormal];
                    }
                    
                }
                
                
                
                
                
                [btn addTarget:self
                        action:@selector(actionSetEquipItemToAlternate:)
              forControlEvents:UIControlEventTouchUpInside];
                btn.tag = i+60000;
                //NSLog(@"make btn.tag %d", btn.tag);
                
                btn.backgroundColor = lightOrangeColor;
                //[btn  setBackgroundImage:[UIImage imageNamed: @"button blue top184x52.png" ] forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [_viewConfiguratorStationItems addSubview:btn];
                if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"OUT"] || [[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"ALT"]  || [[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"MOVED"] ) {
                    btn.hidden = YES;
                }
            }
            
            // make restore button
            btn = [UIButton buttonWithType:UIButtonTypeCustom];
            
            
            if (flagIsLandscape == 1) {
                btn.frame = CGRectMake(470,  (itemCount *yGap)  , 100, 35);
                btn.titleLabel.font = [UIFont systemFontOfSize:16];
                
            }else{
                btn.frame = CGRectMake(410,  (itemCount *yGap)  , 70, 35);
                btn.titleLabel.font = [UIFont systemFontOfSize:13];
            }
            
            [btn addTarget:self
                    action:@selector(actionRestoreEquip:)
          forControlEvents:UIControlEventTouchUpInside];
            btn.tag = i+80000;
            [btn setTitle: @"RESTORE" forState: UIControlStateNormal];
            btn.backgroundColor = [UIColor lightGrayColor];
            [_viewConfiguratorStationItems addSubview:btn];
            btn.hidden = YES;
            
            if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"ALT"]  || [[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"MOVED"]  ) {
                
                if ([[arrayConfigItemLocked objectAtIndex: i ] isEqualToString:@"locked"]) {
                    btn.hidden = YES;
                }else{
                    btn.hidden = NO;
                }
                
            }
            
            /*
             // make edit station button
             btn = [UIButton buttonWithType:UIButtonTypeCustom];
             btn.frame = CGRectMake(450,  (itemCount *yGap)  , 120, 35);
             [btn addTarget:self
             action:@selector(actionRestoreEquip:)
             forControlEvents:UIControlEventTouchUpInside];
             btn.tag = i+95000;
             [btn setTitle: @"EDIT STATION" forState: UIControlStateNormal];
             btn.titleLabel.font = [UIFont systemFontOfSize:14];
             [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
             btn.backgroundColor = [UIColor lightGrayColor];
             [_viewConfiguratorStationItems addSubview:btn];
             btn.hidden = YES;
             */
            
            
            
            
            
        }       // end else is line
    }
    
    NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
    if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
    if ([userExtraCheck rangeOfString:@"allowCustomEquipment"].location != NSNotFound  ) {  
        //add button
         UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
           btn.frame = CGRectMake(0 ,  (arrayConfigItemName.count  *yGap + 10)  , 120, 30);
           [btn addTarget:self
                   action:@selector(actionEnterSpecialEquipmentItem:)
         forControlEvents:UIControlEventTouchUpInside];
         
         [btn setTitle: @"Add Station" forState: UIControlStateNormal];
         btn.titleLabel.font = [UIFont systemFontOfSize:16];
         btn.backgroundColor = [UIColor darkGrayColor];
         [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];      
         [_viewConfiguratorStationItems addSubview:btn];       
        
    }
    
    
}

- (void) actionEnterSpecialEquipmentItem:(UIButton*)sender {
    
    // create enter window
     enterView = [[UIView alloc] initWithFrame:CGRectMake(0,0,_viewConfiguratorStationItems.frame.size.width + 10, 1800)];
    
     for(UIView *subview in [enterView subviews]) {
           [subview removeFromSuperview];
       }
    
     enterView.backgroundColor = [UIColor blackColor];
     [_viewConfiguratorStationItems addSubview:enterView]; 
    
    float labelDiff = -25;
    float lineY = 70;
    //name
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake( 10 , lineY  , 180, 31)];
           textField.borderStyle = UITextBorderStyleRoundedRect;
           textField.font = [UIFont boldSystemFontOfSize:16];
           textField.autocorrectionType = UITextAutocorrectionTypeNo;
           textField.textAlignment = NSTextAlignmentLeft;
           textField.enabled = YES;
           textField.backgroundColor = [UIColor whiteColor];
           textField.textColor = [UIColor blackColor];           
           [textField  setText: @""]; 
           textField.tag = 100;
           [enterView addSubview: textField];
    
   UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake( 10  , lineY  + labelDiff, 180, 31)];
               label.font = [UIFont boldSystemFontOfSize:14];
               label.textAlignment = NSTextAlignmentLeft;
               label.textColor = [UIColor lightGrayColor];
    [label setText: @"Item Name"];
    [enterView addSubview: label];
    
    //weight
    textField = [[UITextField alloc] initWithFrame:CGRectMake( 200 , lineY  , 80, 31)];         
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.font = [UIFont boldSystemFontOfSize:16];
    textField.autocorrectionType = UITextAutocorrectionTypeNo;
    textField.textAlignment = NSTextAlignmentLeft;
    textField.enabled = YES;
    textField.backgroundColor = [UIColor whiteColor];
    textField.textColor = [UIColor blackColor];           
    [textField  setText: @""]; 
    textField.tag = 200;
    [enterView addSubview: textField];
    
    label = [[UILabel alloc] initWithFrame:CGRectMake( 200  , lineY  + labelDiff, 80, 31)];
               label.font = [UIFont boldSystemFontOfSize:14];
               label.textAlignment = NSTextAlignmentLeft;
               label.textColor = [UIColor lightGrayColor];
    [label setText: @"Weight"];
    [enterView addSubview: label];
    
    //arm LONG
    textField = [[UITextField alloc] initWithFrame:CGRectMake( 290 , lineY  , 80, 31)];         
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.font = [UIFont boldSystemFontOfSize:16];
    textField.autocorrectionType = UITextAutocorrectionTypeNo;
    textField.textAlignment = NSTextAlignmentLeft;
    textField.enabled = YES;
    textField.backgroundColor = [UIColor whiteColor];
    textField.textColor = [UIColor blackColor];           
    [textField  setText: @""]; 
    textField.tag = 300;
    [enterView addSubview: textField];
    
    label = [[UILabel alloc] initWithFrame:CGRectMake( 290 , lineY + labelDiff , 80, 31)];
                  label.font = [UIFont boldSystemFontOfSize:14];
                  label.textAlignment = NSTextAlignmentLeft;
                  label.textColor = [UIColor lightGrayColor];
       [label setText: @"Arm LONG"];
       [enterView addSubview: label];
    
    //arm LAT
    textField = [[UITextField alloc] initWithFrame:CGRectMake( 380 , lineY  , 80, 31)];         
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.font = [UIFont boldSystemFontOfSize:16];
    textField.autocorrectionType = UITextAutocorrectionTypeNo;
    textField.textAlignment = NSTextAlignmentLeft;
    textField.enabled = YES;
    textField.backgroundColor = [UIColor whiteColor];
    textField.textColor = [UIColor blackColor];           
    [textField  setText: @""]; 
    textField.tag = 400;
    [enterView addSubview: textField];
    
    label = [[UILabel alloc] initWithFrame:CGRectMake( 380 , lineY  + labelDiff, 80, 31)];
               label.font = [UIFont boldSystemFontOfSize:14];
               label.textAlignment = NSTextAlignmentLeft;
               label.textColor = [UIColor lightGrayColor];
    [label setText: @"Arm LAT"];
    [enterView addSubview: label];
    
    
    
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
      btn.frame = CGRectMake(10 ,  150  , 150, 30);
      [btn addTarget:self
              action:@selector(actionAddSpecialEquipmentItem:)
    forControlEvents:UIControlEventTouchUpInside];
    
    [btn setTitle: @"Add This Station" forState: UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    btn.backgroundColor = [UIColor greenColor];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];      
    [enterView addSubview:btn];  
    
    btn = [UIButton buttonWithType:UIButtonTypeCustom];
      btn.frame = CGRectMake(200 ,  150  , 80, 30);
      [btn addTarget:self
              action:@selector(actionCancelAddSpecialEquipmentItem:)
    forControlEvents:UIControlEventTouchUpInside];
    
    [btn setTitle: @"Cancel" forState: UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    btn.backgroundColor = [UIColor lightGrayColor];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];      
    [enterView addSubview:btn];  
    
    
    
}

- (void) actionCancelAddSpecialEquipmentItem:(UIButton*)sender {
     [enterView removeFromSuperview];
}

- (void) actionAddSpecialEquipmentItem:(UIButton*)sender {
    
   
    
    UITextField *itemField = (UITextField *)[enterView viewWithTag: 100  ];    
    NSString *itemText = itemField.text;
 
    itemField = (UITextField *)[enterView viewWithTag: 200  ];
       NSString *weight = itemField.text;
    
    itemField = (UITextField *)[enterView viewWithTag: 300  ];
    NSString *arm = itemField.text;
    
    itemField = (UITextField *)[enterView viewWithTag: 400  ];
       NSString *armLat = itemField.text;
    
    float summe = [weight floatValue] * [arm floatValue]  ;
    //NSLog(@"summe %f", summe);
    if (summe == 0) {
        [enterView removeFromSuperview];
    }else{
        [arrayConfigItemName         addObject: itemText];
                               [arrayConfigItemWeight       addObject: weight];
                               [arrayConfigItemArmLong      addObject: arm];
          NSString *momLong = [NSString stringWithFormat:@"%.1f", [weight floatValue] *  [arm floatValue]];
                               [arrayConfigItemMomLong      addObject: momLong];
         
                               [arrayConfigItemArmLat       addObject: armLat];
          NSString *momLat = [NSString stringWithFormat:@"%.1f", [weight floatValue] *  [armLat floatValue]];
        
        
                               [arrayConfigItemMomLat       addObject: momLat];
                               [arrayConfigItemLocked       addObject: @""];
                               [arrayConfigIteminOut        addObject: @"IN"];
                               [arrayConfigItemData         addObject: @""];
                               [arrayConfigItemMoved        addObject: @""];
                               [arrayConfigItemAltLong      addObject: @""];
                               [arrayConfigItemAltLat       addObject: @""];
                               [arrayConfigItemMovable      addObject: @""];
                               [arrayConfigItemTrigger      addObject: @""];                       
                               [arrayConfigItemItemR1       addObject: @""];
                               [arrayConfigItemItemR2       addObject: @""];
                               [arrayConfigItemItemR3       addObject: @""];
            
            _viewConfiguratorStationItems.frame = CGRectMake(0, 0, 1024, arrayConfigItemName.count * 40 + 250);
            [_scrollViewConfiguratorItems setContentSize:CGSizeMake(_scrollViewConfiguratorItems.frame.size.width, _viewConfiguratorStationItems.frame.size.height)];
            [self createSpecialEquipListItems];
            [self computeSpecialEquipmentTotals];
            [self MainRoutine];
          [enterView removeFromSuperview];
        
    }
  
                       
    
}




- (void) actionShowEquipItem:(UIButton*)sender {
    
    int itemNr = sender.tag - 90000;
    
    UILabel *label = (UILabel *)[_viewEquipmentOnHeli viewWithTag: itemNr + 50000  ];
    
    [_viewEquipmentOnHeli bringSubviewToFront:label];
    
    
    label.alpha = 1;
    label.backgroundColor = yellowSpecialColor;
    label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, 20, 20);
    label.textColor = [UIColor clearColor];
    
    
    [UIView animateWithDuration:0.4
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionRepeat
                     animations:^{
                         [UIView setAnimationRepeatCount:3]; // **This should appear in the beginning of the block**
                         label.alpha = 0.2;
                         label.frame = CGRectMake(label.frame.origin.x-10, label.frame.origin.y-10, 40, 40);
                     }
                     completion:^(BOOL finished) {
                         
                         if ([[arrayConfigIteminOut objectAtIndex:itemNr] isEqualToString:@"MOVED"]) {
                             label.backgroundColor = [UIColor blueColor];
                             label.alpha = 1.0;
                             label.frame = CGRectMake(label.frame.origin.x+10, label.frame.origin.y+10, 20, 20);
                             label.textColor = [UIColor whiteColor];
                         }else if ([[arrayConfigIteminOut objectAtIndex:itemNr] isEqualToString:@"ALT"]) {
                             label.backgroundColor = lightOrangeColor;
                             label.alpha = 1.0;
                             label.frame = CGRectMake(label.frame.origin.x+10, label.frame.origin.y+10, 20, 20);
                             label.textColor = [UIColor blackColor];
                         }else{
                             label.alpha = 1.0;
                             label.frame = CGRectMake(label.frame.origin.x+10, label.frame.origin.y+10, 20, 20);
                             
                             if ([[arrayConfigIteminOut objectAtIndex: itemNr ] isEqualToString:@"OUT"] ) {
                                 label.backgroundColor = [UIColor redColor];
                                 label.textColor = [UIColor whiteColor];
                             }else{
                                 label.backgroundColor = [UIColor whiteColor];
                                 label.textColor = [UIColor blackColor];
                             }
                             
                         }
                         
                         
                         
                         
                         
                         
                         
                     }];
    
    
}

- (void) actionRestoreEquip:(UIButton*)sender {
    
    int itemNr = sender.tag - 80000;
    
    [arrayConfigIteminOut replaceObjectAtIndex:itemNr withObject: @"IN"  ];
    UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 20000 ];
    [btn setTitle: @"IN" forState: UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    btn.backgroundColor = [UIColor greenColor];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    
    UILabel *label = (UILabel *)[_viewEquipmentOnHeli viewWithTag: itemNr + 50000 ];
    label.backgroundColor = [UIColor whiteColor];
    [_viewEquipmentOnHeli bringSubviewToFront:label];
    label.textColor = [UIColor blackColor];
    label.hidden = NO;
    
    
    // move the item! to the original position
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1.0];
    float itemLong = 0;
    float itemLat  = 0;
    itemLong = [ [arrayConfigItemArmLong objectAtIndex: itemNr ] floatValue];
    itemLat  = [ [arrayConfigItemArmLat objectAtIndex: itemNr  ] floatValue];
    float LongScale = (_viewMeasureRearSeats.center.y - _viewMeasureFrontSeats.center.y) / (LongArmRearSeat - LongArmFrontSeat) ;
    float LatPixLeftSeat    = _viewMeasureCenter.center.x;
    float LatPixRightSeat  = _viewMeasureLatRight.center.x;
    float LatScale = (LatPixRightSeat - LatPixLeftSeat) / (LatArmRightSeat - LatArmLeftSeat) ;
    //NSLog (@"LatArmRightSeat %f@ ", LatArmRightSeat);
    float itemWidth = 20;
    float itemHeight = 20;
    float LongPixPosition = 0;
    float LatPixPosition = 0;
    float yOffset = 0;
    float latOffset = 0;
    LongPixPosition =  (( (LongScale * (itemLong - LongArmFrontSeat)) + _viewMeasureFrontSeats.center.y  )  - (itemHeight/2))   ;
    LatPixPosition =   ( (LatScale *  (itemLat -  LatArmLeftSeat))   + LatPixLeftSeat      )  - (itemWidth/2);
    label.frame = CGRectMake(LatPixPosition + latOffset, LongPixPosition + yOffset, itemWidth , itemHeight );
    [UIView commitAnimations];
    
    UILabel *label2 = (UILabel *)[_viewConfiguratorStationItems viewWithTag: itemNr + 70000 ];
    [label2  setText: [NSString stringWithFormat:@"%@kg, Long: %.0fmm, Lat: %.0fmm", [arrayConfigItemWeight objectAtIndex: itemNr ], itemLong , itemLat   ]];
    label2.textColor = [UIColor lightGrayColor];
    label2 = (UILabel *)[_viewConfiguratorStationItems viewWithTag: itemNr + 75000 ];
    label2.textColor = [UIColor whiteColor];
    
    
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 60000];
    btn.hidden = NO;
    
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 40000];
    btn.hidden = NO;
    
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 80000];
    btn.hidden = YES;
    
    [self MainRoutine];
    
    
    
}

- (void)actionMoveEquipItem :(UIButton*)sender {
    
    
    _viewHelicopterInCenter.userInteractionEnabled = YES;
    
    //disable all other move buttons
    for(int i =0; i<arrayConfigIteminOut.count; i++) {
        UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 40000  ];
        btn.enabled = NO;
        btn.alpha = 0.3;
        
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 60000  ];
        btn.enabled = NO;
        btn.alpha = 0.3;
        
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 80000  ];
        btn.enabled = NO;
        btn.alpha = 0.3;
        
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 20000  ];
        btn.enabled = NO;
        btn.alpha = 0.3;
        
        
    }
    
    // add buttons for cancel and set
    int itemNr = sender.tag - 40000;
    currentEquipItemNumber = itemNr;
    float yGap = 40;
    
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    
    if (flagIsLandscape == 1) {
        btn.frame = CGRectMake(370,  (itemNr *yGap)  , 100, 35);
    }else{
        btn.frame = CGRectMake(340,  (itemNr *yGap)  , 70, 35);
        
    }
    
    
    [btn addTarget:self
            action:@selector(actionCancelEquipItem:)
  forControlEvents:UIControlEventTouchUpInside];
    btn.tag = itemNr + 41000;
    //NSLog(@"make btn.tag %d", btn.tag);
    [btn setTitle: @"CANCEL" forState: UIControlStateNormal];
    btn.backgroundColor = [UIColor orangeColor];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_viewConfiguratorStationItems addSubview:btn];
    
    
    btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    
    if (flagIsLandscape == 1) {
        btn.frame = CGRectMake(470,  (itemNr *yGap)  , 100, 35);
    }else{
        btn.frame = CGRectMake(410,  (itemNr *yGap)  , 70, 35);
        
    }
    
    
    [btn addTarget:self
            action:@selector(actionSetEquipItem:)
  forControlEvents:UIControlEventTouchUpInside];
    btn.tag = itemNr + 42000;
    [btn setTitle: @"SET" forState: UIControlStateNormal];
    btn.backgroundColor = [UIColor blueColor];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.enabled = NO;
    [_viewConfiguratorStationItems addSubview:btn];
    
    // bring item to front and make bigger
    UILabel *label = (UILabel *)[_viewEquipmentOnHeli viewWithTag: itemNr + 50000  ];
    label.frame = CGRectMake(label.frame.origin.x - 10, label.frame.origin.y - 10, 40, 40);
    label.backgroundColor = [UIColor blueColor];
    label.textColor = [UIColor whiteColor];
    [_viewEquipmentOnHeli bringSubviewToFront:label];
    
    
    UIView *panBox =[[UIView alloc] initWithFrame:CGRectMake(label.frame.origin.x - 30, label.frame.origin.y - 30, 100, 100) ];
    panBox.backgroundColor = [UIColor clearColor];
    
    UIImageView *panBoxBackground =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, panBox.frame.size.width, panBox.frame.size.height) ];
    [panBoxBackground setImage:[UIImage imageNamed:@"yellowBoxEquipMover.png"]];
    [panBox addSubview:panBoxBackground];
    
    panBox.tag = 60000;
    [_viewEquipmentOnHeli addSubview:panBox];
    
    label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5,80,20 )];
    label.font = [UIFont boldSystemFontOfSize:13.0];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = blueButtonColor;
    label.alpha = 0.9;
    label.text = @"Long/Lat";
    label.tag = 61000;
    
    [panBox addSubview:label];
    
    
    [_viewEquipmentOnHeli bringSubviewToFront:panBox];
    
    panRecognizerForEquipment = [[UIPanGestureRecognizer alloc]
                                 initWithTarget:self
                                 action:@selector(panRecognizerEquipmentAction:)];
    
    
    
    [_viewEquipmentOnHeli addGestureRecognizer:panRecognizerForEquipment];
    
    
    
    
    
}



- (void)panRecognizerEquipmentAction:(UIPanGestureRecognizer *)recognizer {
    
    //NSLog(@"move panBox" );
    
    
    
    UIView *panBox = (UIView *)[_viewEquipmentOnHeli viewWithTag: 60000 ];
    // move ghost
    CGPoint translation = [recognizer translationInView:self.view];
    panBox.center = CGPointMake(panBox.center.x + (translation.x ) , panBox.center.y + (translation.y ) );
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
    
    // compute lat and long
    
    float yOffset = 0;
    float latOffset = 0;
    
    float LongScale = (_viewMeasureRearSeats.center.y - _viewMeasureFrontSeats.center.y) / (LongArmRearSeat - LongArmFrontSeat) ;
    float LatScale  = (_viewMeasureLatRight.center.x  - _viewMeasureCenter.center.x)     / (LatArmRightSeat - LatArmLeftSeat) ;
    
    movedEquipLong = ((((panBox.center.y - yOffset ) -_viewSeatSize.layer.frame.size.height/2)  + (_viewSeatSize.layer.frame.size.height/2) - _viewMeasureFrontSeats.center.y ) / LongScale )+ LongArmFrontSeat ;
    
    movedEquiplat = ((((panBox.center.x - latOffset) -_viewSeatSize.layer.frame.size.width/2) + (_viewSeatSize.layer.frame.size.width/2) - _viewMeasureCenter.center.x ) / LatScale )+ LatArmLeftSeat ;
    
    //NSLog(@"LongArmGhost %.0f ", LongArmGhost);
    //NSLog(@"LatArmGhost %.0f ", LatArmGhost);
    
    
    // update long lat
    UILabel *label = (UILabel*)[_viewEquipmentOnHeli viewWithTag: 61000 ];
    
    
    if ([[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
        label.text = [NSString stringWithFormat:@"%.2f/%.2f",movedEquipLong, movedEquiplat];
    }else{
        label.text = [NSString stringWithFormat:@"%.0f / %.0f",movedEquipLong, movedEquiplat];
    }
    
    //enable set button
    
    UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: currentEquipItemNumber + 42000 ];
    btn.enabled = YES;
    
    flagEquipItemHasMoved = 1;
    
    
}



- (void)actionSetEquipItem :(UIButton*)sender {
    
    _viewHelicopterInCenter.userInteractionEnabled = NO;
    
    //enable all other move buttons
    for(int i =0; i<arrayConfigIteminOut.count; i++) {
        UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 40000  ];
        btn.enabled = YES;
        btn.alpha = 1.0;
        
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 60000  ];
        btn.enabled = YES;
        btn.alpha = 1.0;
        
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 80000  ];
        btn.enabled = YES;
        btn.alpha = 1.0;
        
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 20000  ];
        btn.enabled = YES;
        btn.alpha = 1.0;
        
    }
    
    
    
    int itemNr = sender.tag ;  // incl 42000
    
    
    UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr ];
    //btn.hidden = YES;
    [btn removeFromSuperview];
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr - 1000];
    [btn removeFromSuperview];
    
    
    itemNr = sender.tag - 42000 + 50000;
    //NSLog(@"cancel equip item %d", itemNr  );
    UILabel *label = (UILabel *)[_viewEquipmentOnHeli viewWithTag: itemNr  ];
    label.frame = CGRectMake(label.frame.origin.x + 10, label.frame.origin.y + 10, 20, 20);
    
    
    // remove panBox
    UIView *panBox = (UIView *)[_viewEquipmentOnHeli viewWithTag: 60000 ];
    [panBox removeFromSuperview];
    
    //mark as moved
    itemNr = sender.tag - 42000;
    [arrayConfigIteminOut replaceObjectAtIndex:itemNr withObject: @"MOVED"];
    [arrayConfigItemMoved replaceObjectAtIndex:itemNr withObject: [NSString stringWithFormat:@"%.0f:%.0f", movedEquipLong, movedEquiplat ] ];
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 20000  ];
    [btn setTitle: @"MOVED" forState: UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    btn.backgroundColor = [UIColor blueColor];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    [self computeSpecialEquipmentTotals];
    [self MainRoutine];
    //[self performSelector: @selector (MainRoutine) withObject:nil afterDelay: 1.0f];
    
    // move the item!
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1.0];
    float itemLong = 0;
    float itemLat  = 0;
    itemLong = movedEquipLong;
    itemLat  = movedEquiplat;
    float LongScale = (_viewMeasureRearSeats.center.y - _viewMeasureFrontSeats.center.y) / (LongArmRearSeat - LongArmFrontSeat) ;
    float LatPixLeftSeat    = _viewMeasureCenter.center.x;
    float LatPixRightSeat  = _viewMeasureLatRight.center.x;
    float LatScale = (LatPixRightSeat - LatPixLeftSeat) / (LatArmRightSeat - LatArmLeftSeat) ;
    //NSLog (@"LatArmRightSeat %f@ ", LatArmRightSeat);
    float itemWidth = 20;
    float itemHeight = 20;
    float LongPixPosition = 0;
    float LatPixPosition = 0;
    float yOffset = 0;
    float latOffset = 0;
    LongPixPosition =  (( (LongScale * (itemLong - LongArmFrontSeat)) + _viewMeasureFrontSeats.center.y  )  - (itemHeight/2))   ;
    LatPixPosition =   ( (LatScale *  (itemLat -  LatArmLeftSeat))   + LatPixLeftSeat      )  - (itemWidth/2);
    label.frame = CGRectMake(LatPixPosition + latOffset, LongPixPosition + yOffset, itemWidth , itemHeight );
    [UIView commitAnimations];
    
    label = (UILabel *)[_viewConfiguratorStationItems viewWithTag: itemNr + 70000 ];
    [label  setText: [NSString stringWithFormat:@"%@kg, Long: %.0fmm, Lat: %.0fmm", [arrayConfigItemWeight objectAtIndex: itemNr ], movedEquipLong , movedEquiplat   ]];
    label.textColor = lightBlueColor;
    label = (UILabel *)[_viewConfiguratorStationItems viewWithTag: itemNr + 75000 ];
    label.textColor = lightBlueColor;
    
    
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 60000];
    btn.hidden = YES;
    
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 40000];
    btn.hidden = YES;
    
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 80000];
    btn.hidden = NO;
    
    
    
}


- (void)actionSetEquipItemToAlternate :(UIButton*)sender {
    
    
    int itemNr = sender.tag  - 60000;  // incl 42000
    
    
    [arrayConfigIteminOut replaceObjectAtIndex:itemNr withObject:@"ALT"];
    
    UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 20000];
    [btn setTitle: @"ALT" forState: UIControlStateNormal];
    btn.backgroundColor = lightOrangeColor;
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    UILabel *label = (UILabel *)[_viewEquipmentOnHeli viewWithTag: itemNr + 50000 ];
    label.backgroundColor = lightOrangeColor;
    label.textColor = [UIColor blackColor];
    [_viewEquipmentOnHeli bringSubviewToFront:label];
    label.hidden = NO;
    
    // remove the ALT button
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 60000];
    btn.hidden = YES;
    
    // move the item! to the alternate postion
    float replaceArmLong = [[arrayConfigItemAltLong objectAtIndex:itemNr] floatValue];
    float replaceArmLat = [[arrayConfigItemAltLat objectAtIndex:itemNr] floatValue];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    float itemLong = 0;
    float itemLat  = 0;
    itemLong = replaceArmLong;
    itemLat  = replaceArmLat;
    float LongScale = (_viewMeasureRearSeats.center.y - _viewMeasureFrontSeats.center.y) / (LongArmRearSeat - LongArmFrontSeat) ;
    float LatPixLeftSeat    = _viewMeasureCenter.center.x;
    float LatPixRightSeat  = _viewMeasureLatRight.center.x;
    float LatScale = (LatPixRightSeat - LatPixLeftSeat) / (LatArmRightSeat - LatArmLeftSeat) ;
    //NSLog (@"LatArmRightSeat %f@ ", LatArmRightSeat);
    float itemWidth = 20;
    float itemHeight = 20;
    float LongPixPosition = 0;
    float LatPixPosition = 0;
    float yOffset = 0;
    float latOffset = 0;
    LongPixPosition =  (( (LongScale * (itemLong - LongArmFrontSeat)) + _viewMeasureFrontSeats.center.y  )  - (itemHeight/2))   ;
    LatPixPosition =   ( (LatScale *  (itemLat -  LatArmLeftSeat))   + LatPixLeftSeat      )  - (itemWidth/2);
    label.frame = CGRectMake(LatPixPosition + latOffset, LongPixPosition + yOffset, itemWidth , itemHeight );
    [UIView commitAnimations];
    
    label = (UILabel *)[_viewConfiguratorStationItems viewWithTag: itemNr + 70000 ];
    [label  setText: [NSString stringWithFormat:@"%@kg, Long: %.0fmm, Lat: %.0fmm", [arrayConfigItemWeight objectAtIndex: itemNr ], itemLong , itemLat   ]];
    label.textColor = lightOrangeColor;
    label = (UILabel *)[_viewConfiguratorStationItems viewWithTag: itemNr + 75000 ];
    label.textColor = lightOrangeColor;
    
    
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 60000];
    btn.hidden = YES;
    // show the MOVE button
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 40000];
    btn.hidden = YES;
    //hide restore
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 80000];
    btn.hidden = NO;
    
    
    [self MainRoutine];
    
    
}


- (void)actionCancelEquipItem :(UIButton*)sender {
    
    _viewHelicopterInCenter.userInteractionEnabled = NO;
    
    //enable all other move buttons
    for(int i =0; i<arrayConfigIteminOut.count; i++) {
        UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 40000  ];
        btn.enabled = YES;
        btn.alpha = 1.0;
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 60000  ];
        btn.enabled = YES;
        btn.alpha = 1.0;
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 80000  ];
        btn.enabled = YES;
        btn.alpha = 1.0;
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 20000  ];
        btn.enabled = YES;
        btn.alpha = 1.0;
        
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 41000  ];
        btn.hidden = YES;
        
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 42000  ];
        btn.hidden = YES;
        
    }
    
 
    int itemNr = sender.tag ;
    /*
    //NSLog(@"itemNr %d", itemNr);
    UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr ];
    //btn.hidden = YES;
    [btn removeFromSuperview];
    btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 1000];
    [btn removeFromSuperview];
    */
    
  
    itemNr = sender.tag - 41000 + 50000;
    //NSLog(@"cancel equip item %d", itemNr  );
    UILabel *label = (UILabel *)[_viewEquipmentOnHeli viewWithTag: itemNr  ];
    label.frame = CGRectMake(label.frame.origin.x + 10, label.frame.origin.y + 10, 20, 20);
    label.backgroundColor = [UIColor whiteColor];
    label.textColor = [UIColor blackColor];
    
    
    // remove panBox
    UIView *panBox = (UIView *)[_viewEquipmentOnHeli viewWithTag: 60000 ];
    [panBox removeFromSuperview];
    
    
}



- (void) actionAddItemToPackage :(UIButton*)sender {
    
    
    _inputAddEquipName.text = @"";
    _inputAddEquipWeight.text = @"0";
    _inputAddEquipArmLong.text = @"0";
    _inputAddEquipArmLat.text = @"0";
    
    buttonIDtransfer = sender.tag - 35000;
    _viewAddEquipmentItem.hidden = NO;    
    [_viewConfigurator bringSubviewToFront:_viewAddEquipmentItem];
    
    _viewAddEquipmentItem.frame = CGRectMake(_scrollViewConfiguratorItems.frame.origin.x, _scrollViewConfiguratorItems.frame.origin.y, 640, 1800);
     
}

- (IBAction)actionCancelInsertEquipItem:(id)sender {
      _viewAddEquipmentItem.hidden = YES; 
}

- (IBAction)actionAddEquipmentItem:(id)sender {
    [self.view endEditing:TRUE];  
    [self addItemToPackage:buttonIDtransfer];
}


- (void) addItemToPackage :(float)itemNumber {
    
     _viewAddEquipmentItem.hidden = YES;  
    
    if ([_inputAddEquipName.text isEqualToString:@""] ||[_inputAddEquipWeight.text isEqualToString:@""] ||[_inputAddEquipArmLong.text isEqualToString:@""]  ||[_inputAddEquipWeight.text isEqualToString:@"0"] ||[_inputAddEquipArmLong.text isEqualToString:@"0"] ) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Missing Data or Value. Please enter a value for weight and arm and also a name for the item. Equipment Item not added."
                                                                                 message:nil
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil]; 
        
        return;
    }
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Item added successfully."
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:actionOk];
    [self presentViewController:alertController animated:YES completion:nil]; 

    float itemNr = itemNumber;
    NSString *objectToInsert = @"";
    
    NSString *currentPackageName =  [arrayPackageName objectAtIndex:itemNr];
    //NSLog(@"arrayPackageName %@", [arrayPackageName objectAtIndex:sender.tag - 35000]);
    
    [arrayConfigItemName insertObject:_inputAddEquipName.text  atIndex:itemNr+1]; 
    [arrayConfigItemWeight insertObject:_inputAddEquipWeight.text atIndex:itemNr+1]; 
    [arrayConfigItemArmLong insertObject:_inputAddEquipArmLong.text atIndex:itemNr+1];
    NSString *equipMom  = [NSString stringWithFormat:@"%.0f", [_inputAddEquipName.text floatValue] *  [_inputAddEquipArmLong.text floatValue]]; 
    [arrayConfigItemMomLong insertObject:equipMom atIndex:itemNr+1];
    [arrayConfigItemArmLat insertObject:_inputAddEquipArmLat.text atIndex:itemNr+1];
    NSString *equipMomLat  = [NSString stringWithFormat:@"%.0f", [_inputAddEquipName.text floatValue] *  [_inputAddEquipArmLat.text floatValue]]; 
    [arrayConfigItemMomLat insertObject:equipMomLat atIndex:itemNr+1];
    [arrayConfigIteminOut insertObject:@"IN" atIndex:itemNr+1];
    [arrayConfigItemLocked insertObject:@"unlocked" atIndex:itemNr+1];
    [arrayConfigItemData insertObject:objectToInsert atIndex:itemNr+1];
    [arrayConfigItemMoved insertObject:objectToInsert atIndex:itemNr+1];
    [arrayConfigItemAltLong insertObject:objectToInsert atIndex:itemNr+1];
    [arrayConfigItemAltLat insertObject:objectToInsert atIndex:itemNr+1];
    [arrayConfigItemMovable insertObject:objectToInsert atIndex:itemNr+1];
    [arrayConfigItemTrigger insertObject:objectToInsert atIndex:itemNr+1];
    [arrayConfigItemItemR1 insertObject:objectToInsert atIndex:itemNr+1];
    [arrayConfigItemItemR2 insertObject:objectToInsert atIndex:itemNr+1];
    [arrayConfigItemItemR3 insertObject:objectToInsert atIndex:itemNr+1];
    [arrayPackageName insertObject:currentPackageName atIndex:itemNr+1];
    
    [self MainRoutine];   
    [self createSpecialEquipListItems];
    [self MainRoutine];
    [self SaveValues];
    
     
    
}

- (void)actionPackageInOut :(UIButton*)sender {
    
    float itemNr = sender.tag - 30000;
    //get package name
    NSString *packageNameToSet = [arrayPackageName objectAtIndex: itemNr ];
    //NSLog(@"package packageNameToSet >%@< ", packageNameToSet );    
    //NSLog(@"arrayPackageName %@ ", arrayPackageName );
    
    int triggerIsFirstItem = 0;
    for(int i =0; i<arrayConfigItemName.count; i++) {
        
        if ([[arrayPackageName objectAtIndex: i ] isEqualToString:packageNameToSet]) {    
            
            if ([[arrayConfigItemLocked objectAtIndex: i ] isEqualToString:@"locked"]) {
                //NSLog(@"continue i %d", i);
                continue;
            }               
            if (triggerIsFirstItem == 0) {
                triggerIsFirstItem = 1;             
                if ([[arrayConfigIteminOut objectAtIndex:i] isEqualToString:@"OUT"]) {
                    toggleItemsInOut = 1;                  
                }else{
                     toggleItemsInOut = 0;
                }                    
            }
            
            //NSLog(@"i %d", i);
            //NSLog(@"toggleItemsInOut %d ", toggleItemsInOut );            
            if (toggleItemsInOut == 0) {               
                [arrayConfigIteminOut replaceObjectAtIndex:i withObject: @"OUT"  ];
                UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 20000];
                [btn setTitle: @"OUT" forState: UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:16];
                btn.backgroundColor = [UIColor redColor];
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];        
                UILabel *label = (UILabel *)[_viewEquipmentOnHeli viewWithTag:  i + 50000 ];
                label.backgroundColor = [UIColor redColor];
                label.textColor = [UIColor whiteColor];        
                label = (UILabel *)[_viewConfiguratorStationItems viewWithTag: i + 70000 ];
                [label  setText: @""];
                label = (UILabel *)[_viewConfiguratorStationItems viewWithTag: i + 75000 ];
                label.textColor = [UIColor whiteColor];
                // remove the ALT button
                btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 60000];
                btn.hidden = YES;
                // remove the MOVE button
                btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 40000];
                btn.hidden = YES;
            }else{
                [arrayConfigIteminOut replaceObjectAtIndex:i withObject: @"IN"  ];
                UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 20000 ];
                [btn setTitle: @"IN" forState: UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:16];
                btn.backgroundColor = [UIColor greenColor];
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                
                UILabel *label = (UILabel *)[_viewEquipmentOnHeli viewWithTag: i + 50000 ];
                label.backgroundColor = [UIColor whiteColor];
                label.textColor = [UIColor blackColor];
                [_viewEquipmentOnHeli bringSubviewToFront:label];
                label.hidden = NO;        
                label = (UILabel *)[_viewConfiguratorStationItems viewWithTag: i + 70000 ];                
                if ([unitsWeight.text isEqualToString:@"kg"]) {            
                    if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
                        [label  setText: [NSString stringWithFormat:@"%@kg, Long: %@m, Lat: %@m", [arrayConfigItemWeight objectAtIndex: i ], [arrayConfigItemArmLong objectAtIndex: i ] , [arrayConfigItemArmLat objectAtIndex: i ]   ]];
                    }else{
                        [label  setText: [NSString stringWithFormat:@"%@kg, Long: %@mm, Lat: %@mm", [arrayConfigItemWeight objectAtIndex: i ], [arrayConfigItemArmLong objectAtIndex: i ] , [arrayConfigItemArmLat objectAtIndex: i ]   ]];
                    }
                }else{
                    [label  setText: [NSString stringWithFormat:@"%@lbs, Long: %@, Lat: %@", [arrayConfigItemWeight objectAtIndex: i ], [arrayConfigItemArmLong objectAtIndex: i ] , [arrayConfigItemArmLat objectAtIndex: i ]   ]];
                }                
                label.textColor = [UIColor lightGrayColor];
                label = (UILabel *)[_viewConfiguratorStationItems viewWithTag: i + 75000 ];
                label.textColor = [UIColor whiteColor];                
                // show the ALT button
                btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 60000];
                btn.hidden = NO;
                // show the MOVE button
                btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 40000];
                btn.hidden = NO;
                //hide restore
                btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 80000];
                btn.hidden = YES;                 
            }
        }
    }
    
    if (toggleItemsInOut == 0) {
        toggleItemsInOut = 1;
    }else{
        toggleItemsInOut = 0;
    }
    
    [self MainRoutine];
    
}


- (void)setEquipPack :(NSString*)packName status:(int)switchStatus {
    
    NSString *packageNameToSet = packName;
    
    //NSLog(@"setEquipPack packageNameToSet %@ ", packageNameToSet );
    //NSLog(@"switchStatus %d ", switchStatus );
    
    for(int i =0; i<arrayConfigItemName.count; i++) {
        
        if ([[arrayPackageName objectAtIndex: i ] isEqualToString:packageNameToSet]) {
            
            if (switchStatus == 0) {
                [arrayConfigIteminOut replaceObjectAtIndex:i withObject: @"OUT"  ];
                UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 20000 ];
                [btn setTitle: @"OUT" forState: UIControlStateNormal];
                btn.backgroundColor = [UIColor redColor];
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }else{
                [arrayConfigIteminOut replaceObjectAtIndex:i withObject: @"IN"  ];
                UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: i + 20000 ];
                [btn setTitle: @"IN" forState: UIControlStateNormal];
                btn.backgroundColor = [UIColor greenColor];
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            }
        }
    }
    
    if (toggleItemsInOut == 0) {
        toggleItemsInOut = 1;
    }else{
        toggleItemsInOut = 0;
    }
    
    [self MainRoutine];
    
}




- (void)actionSpecialEquipmentInOut:(UIButton*)sender {
    
    int itemNr = sender.tag - 20000;
    
    if ([[arrayConfigIteminOut objectAtIndex: itemNr ] isEqualToString:@"OUT"]) {
        
        [arrayConfigIteminOut replaceObjectAtIndex:itemNr withObject: @"IN"  ];
        UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 20000 ];
        [btn setTitle: @"IN" forState: UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:16];
        btn.backgroundColor = [UIColor greenColor];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                
        UILabel *label = (UILabel *)[_viewEquipmentOnHeli viewWithTag: itemNr + 50000 ];
        label.backgroundColor = [UIColor whiteColor];
        label.textColor = [UIColor blackColor];
        [_viewEquipmentOnHeli bringSubviewToFront:label];
        label.hidden = NO;        
        label = (UILabel *)[_viewConfiguratorStationItems viewWithTag: itemNr + 70000 ];
        
        if ([unitsWeight.text isEqualToString:@"kg"]) {            
            if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {
                [label  setText: [NSString stringWithFormat:@"%@kg, Long: %@m, Lat: %@m", [arrayConfigItemWeight objectAtIndex: itemNr ], [arrayConfigItemArmLong objectAtIndex: itemNr ] , [arrayConfigItemArmLat objectAtIndex: itemNr ]   ]];
            }else{
                [label  setText: [NSString stringWithFormat:@"%@kg, Long: %@mm, Lat: %@mm", [arrayConfigItemWeight objectAtIndex: itemNr ], [arrayConfigItemArmLong objectAtIndex: itemNr ] , [arrayConfigItemArmLat objectAtIndex: itemNr ]   ]];
            }
        }else{
            [label  setText: [NSString stringWithFormat:@"%@lbs, Long: %@, Lat: %@", [arrayConfigItemWeight objectAtIndex: itemNr ], [arrayConfigItemArmLong objectAtIndex: itemNr ] , [arrayConfigItemArmLat objectAtIndex: itemNr ]   ]];
        }
        
        label.textColor = [UIColor lightGrayColor];
        label = (UILabel *)[_viewConfiguratorStationItems viewWithTag: itemNr + 75000 ];
        label.textColor = [UIColor whiteColor];
        
        // show the ALT button
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 60000];
        btn.hidden = NO;
        // show the MOVE button
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 40000];
        btn.hidden = NO;
        //hide restore
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 80000];
        btn.hidden = YES;        
        /*
         //hide edit
         btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 95000];
         btn.hidden = YES;
         */
        
        [self MainRoutine];
        return;
        
    }
    
    if ([[arrayConfigIteminOut objectAtIndex: itemNr ] isEqualToString:@"IN"]) {
        [arrayConfigIteminOut replaceObjectAtIndex:itemNr withObject: @"OUT"  ];
        UIButton *btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 20000];
        [btn setTitle: @"OUT" forState: UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:16];
        btn.backgroundColor = [UIColor redColor];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];        
        UILabel *label = (UILabel *)[_viewEquipmentOnHeli viewWithTag:  itemNr + 50000 ];
        label.backgroundColor = [UIColor redColor];
        label.textColor = [UIColor whiteColor];        
        label = (UILabel *)[_viewConfiguratorStationItems viewWithTag: itemNr + 70000 ];
        [label  setText: @""];
        label = (UILabel *)[_viewConfiguratorStationItems viewWithTag: itemNr + 75000 ];
        label.textColor = [UIColor whiteColor];
        // remove the ALT button
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 60000];
        btn.hidden = YES;
        // remove the MOVE button
        btn = (UIButton *)[_viewConfiguratorStationItems viewWithTag: itemNr + 40000];
        btn.hidden = YES;
        [self MainRoutine];
        return;
        
    }
    
}


- (void) computeSpecialEquipmentTotals {
    
   //NSLog(@"computeSpecialEquipmentTotals");
    equipmentItemsOnBoard = 0;
    //NSLog(@"arrayConfigItemName %@", arrayConfigItemName);
    //NSLog(@"arrayConfigItemWeight %@", arrayConfigItemWeight);
    //NSLog(@"arrayConfigIteminOut %@", arrayConfigIteminOut);
    totalSpecialEquipWeight = 0;
    totalSpecialEquipMoment = 0;
    totalSpecialEquipMomentLat = 0;
    float specialEquipWeight = 0;
    float specialEquipMoment = 0;
    float specialEquipMomentLat = 0;
    //NSLog(@"arrayConfigItemName %@", arrayConfigItemName);
    
    float replaceArmLong = 0;
    float replaceArmLat = 0;
    
    for(int i =0; i<arrayConfigItemName.count; i++) {
        
        
        int multiplicator = 0;
        if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"ALT"] ) {
            //NSLog(@"1");
            multiplicator = 1;
            replaceArmLong = [[arrayConfigItemAltLong objectAtIndex:i] floatValue];
            replaceArmLat = [[arrayConfigItemAltLat objectAtIndex:i] floatValue];
            //NSLog(@"replaceArmLong %.0f", replaceArmLong);
            //NSLog(@"replaceArmLat %.0f", replaceArmLat);
        }
        
        if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"MOVED"]) {
            //NSLog(@"2");
            multiplicator = 1;
            NSString *text = [arrayConfigItemMoved objectAtIndex: i  ];
            NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@":"];
            NSArray *arrayComponents = [text componentsSeparatedByCharactersInSet:charSet1];
            replaceArmLong = [[arrayComponents objectAtIndex:0] floatValue];
            replaceArmLat = [[arrayComponents objectAtIndex:1] floatValue];
            
        }
        
        
        if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"IN"]) {
            multiplicator = 1;
            equipmentItemsOnBoard = equipmentItemsOnBoard + 1;
        }
        // check if item is triggered by anohter item
        if ( ![[arrayConfigItemTrigger objectAtIndex: i  ] isEqualToString:@""]     ) {
            NSString *triggered = [arrayConfigItemTrigger objectAtIndex: i  ];
            // get state of triggered item:
            NSInteger index = [arrayConfigItemName indexOfObject: triggered];
            
            if ([[arrayConfigIteminOut objectAtIndex: index ] isEqualToString:@"IN"] ) {
                //NSLog(@"TO OUT item >%@< with status >%@<  is triggered from item >%@< with status >%@< ", [arrayConfigItemName  objectAtIndex:i],  [arrayConfigIteminOut  objectAtIndex:i], [arrayConfigItemName  objectAtIndex:index] , [arrayConfigIteminOut  objectAtIndex:index] );
                [arrayConfigIteminOut replaceObjectAtIndex:i withObject:@"OUT"];
            }
            if ([[arrayConfigIteminOut objectAtIndex: index ] isEqualToString:@"OUT"] ) {
                //NSLog(@"TO IN item >%@< with status >%@<  is triggered from item >%@< with status >%@< ", [arrayConfigItemName  objectAtIndex:i],  [arrayConfigIteminOut  objectAtIndex:i], [arrayConfigItemName  objectAtIndex:index] , [arrayConfigIteminOut  objectAtIndex:index] );
                [arrayConfigIteminOut replaceObjectAtIndex:i withObject:@"IN"];
            }
        }
        
        specialEquipWeight =  [[arrayConfigItemWeight objectAtIndex: i ] floatValue] * multiplicator   ;
        //NSLog(@"specialEquipWeight %.0f", specialEquipWeight);
        
        if ([[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"ALT"] ||  [[arrayConfigIteminOut objectAtIndex: i ] isEqualToString:@"MOVED"]) {
            specialEquipMoment =  specialEquipWeight * replaceArmLong * multiplicator   ;
            specialEquipMomentLat =  specialEquipWeight * replaceArmLat * multiplicator   ;
            //NSLog(@"1 specialEquipMomentLat %.0f", specialEquipMomentLat);
        }else{
            specialEquipMoment =  [[arrayConfigItemMomLong objectAtIndex: i ] floatValue] * multiplicator   ;
            specialEquipMomentLat =  [[arrayConfigItemMomLat objectAtIndex: i ] floatValue] * multiplicator   ;
            //NSLog(@"2 specialEquipMomentLat %@ %.0f", [arrayConfigItemName objectAtIndex: i ] ,specialEquipMomentLat);
        }
        totalSpecialEquipWeight = totalSpecialEquipWeight + specialEquipWeight;
        totalSpecialEquipMoment = totalSpecialEquipMoment + specialEquipMoment;
        totalSpecialEquipMomentLat = totalSpecialEquipMomentLat + specialEquipMomentLat;
    }
    
    ///NSLog(@"totalSpecialEquipMomentLat %.0f", totalSpecialEquipMomentLat);
    
    _labelSEtotalWeight.text = [NSString stringWithFormat:@"%.1f",totalSpecialEquipWeight];
    _labelSEtotalMoment.text = [NSString stringWithFormat:@"%.0f",totalSpecialEquipMoment];
    _labelSEtotalMomentLat.text = [NSString stringWithFormat:@"%.0f",totalSpecialEquipMomentLat];
    _labelSEtotalArm.text = [NSString stringWithFormat:@"%.0f",totalSpecialEquipMoment / totalSpecialEquipWeight];
    _labelSEtotalArmLat.text = [NSString stringWithFormat:@"%.0f",totalSpecialEquipMomentLat / totalSpecialEquipWeight];
    _labelSEtotalWeight2.text = [NSString stringWithFormat:@"+ %.1f %@",totalSpecialEquipWeight, selectedUnitForItems];
    
    if (flagSpecialPHIFlightSettingPage == 1) {
         _labelSEtotalWeight2.text = [NSString stringWithFormat:@"%@ +%.0f %@", _labelEquipListName.text , totalSpecialEquipWeight, selectedUnitForItems];
    }      
  
    
    //modeEquipListOrInterior == 1 wenn equipment liste   == 2 wenn sitz liste
    
    
    
    if ([[_arrayName21 objectAtIndex: 5  ] isEqualToString:@"lbs"] & [selectedUnitForItems isEqualToString:@"kg"]) {
        //convert from original lbs to kg  and inches to mm
        _labelSEtotalWeight.text = [NSString stringWithFormat:@"%.1f",totalSpecialEquipWeight / 2.2046];
        _labelSEtotalMoment.text = [NSString stringWithFormat:@"%.0f",totalSpecialEquipMoment / 0.086795276];
        _labelSEtotalMomentLat.text = [NSString stringWithFormat:@"%.0f",totalSpecialEquipMomentLat / 0.086795276];
        _labelSEtotalArm.text = [NSString stringWithFormat:@"%.0f",[_labelSEtotalMoment.text floatValue] / [_labelSEtotalWeight.text floatValue]];
        _labelSEtotalArmLat.text = [NSString stringWithFormat:@"%.0f", [_labelSEtotalMomentLat.text floatValue] / [_labelSEtotalWeight.text floatValue]];
        _labelSEtotalWeight2.text = [NSString stringWithFormat:@"+ %.1f kg",totalSpecialEquipWeight / 2.2046];
     
    }
    if ([[_arrayName21 objectAtIndex: 5  ] isEqualToString:@"kg"] & [selectedUnitForItems isEqualToString:@"lbs"]) {
        //convert from original kg to lbs  and mm to inches
        _labelSEtotalWeight.text = [NSString stringWithFormat:@"%.1f",totalSpecialEquipWeight * 2.2046];
        _labelSEtotalMoment.text = [NSString stringWithFormat:@"%.0f",totalSpecialEquipMoment * 0.086795276];
        _labelSEtotalMomentLat.text = [NSString stringWithFormat:@"%.0f",totalSpecialEquipMomentLat * 0.086795276];
        _labelSEtotalArm.text = [NSString stringWithFormat:@"%.0f",[_labelSEtotalMoment.text floatValue] / [_labelSEtotalWeight.text floatValue]];
        _labelSEtotalArmLat.text = [NSString stringWithFormat:@"%.0f", [_labelSEtotalMomentLat.text floatValue] / [_labelSEtotalWeight.text floatValue]];
        _labelSEtotalWeight2.text = [NSString stringWithFormat:@"+ %.1f lbs",totalSpecialEquipWeight * 2.2046];
      
    }
    
    if (modeEquipListOrInterior == 2) {
        _labelSEtotalWeight.text = [NSString stringWithFormat:@"%.1f", [[_arrayName2 objectAtIndex:lineSeats]floatValue] * factorApplyToNativeWeightforItems];
        //_labelSEtotalWeight2.text = [NSString stringWithFormat:@"%.1f", [[_arrayName2 objectAtIndex:lineSeats]floatValue] * factorApplyToNativeWeightforItems];
        _labelSEtotalArm.text = [NSString stringWithFormat:@"%.1f", [[_arrayName3 objectAtIndex:lineSeats]floatValue] * factorApplyToNativeDistanceInchMM];
        _labelSEtotalMoment.text = [NSString stringWithFormat:@"%.1f", [[_arrayName4 objectAtIndex:lineSeats]floatValue] * factorApplyToNativeMoment];
        _labelSEtotalArmLat.text = [NSString stringWithFormat:@"%.1f", [[_arrayName5 objectAtIndex:lineSeats]floatValue] * factorApplyToNativeDistanceInchMM];
        _labelSEtotalMomentLat.text = [NSString stringWithFormat:@"%.1f", [[_arrayName6 objectAtIndex:lineSeats]floatValue] * factorApplyToNativeMoment];
        if ([selectedUnitForItems isEqualToString:@"lbs"]) {
            _labelSpecialEquipUnitMass.text = @"lbs";
            _labelSpecialEquipUnitMass2.text = @"lbs";
            _labelSpecialEquipUnitLong.text = @"lbs.In";
            _labelSpecialEquipUnitLong2.text = @"lbs.In";
            _labelSpecialEquipUnitLat.text = @"lbs.In";
            _labelSpecialEquipUnitLat2.text = @"lbs.In";
            
        }else{
            _labelSpecialEquipUnitMass.text = @"kg";
            _labelSpecialEquipUnitMass2.text = @"kg";
            _labelSpecialEquipUnitLong.text = @"kg.mm";
            _labelSpecialEquipUnitLong2.text = @"kg.mm";
            _labelSpecialEquipUnitLat.text = @"kg.mm";
            _labelSpecialEquipUnitLat2.text = @"kg.mm";
            
        }
      
        
    }
 
    
}




// pdf merger

// NSString *fileNameSuffix = [NSString stringWithFormat:@"Load Manifest %@, %@   ", vFlightRegistration.text  , _manifestTimeStamp.text ];

- (IBAction)sendToGoodReader:(UIButton*)sender {
    
    //NSLog(@"sendToGoodReader");
    
     [ScrollViewManifest scrollRectToVisible:CGRectMake(0, 0, 644, 635) animated:YES];    
    
    [self createPDFDataFromManifest];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *fileNameSuffix = [NSString stringWithFormat:@"LM %@_%@.pdf",   displayHeliRegistration.text, timeStampForPDF ];
    if (_labelDepartureTimeLocal.text.length > 3) {
        fileNameSuffix = [NSString stringWithFormat:@"LM %@_%@.pdf",   displayHeliRegistration.text, _labelDepartureTimeLocal.text ];
    } 
    
    //NSLog(@"fileNameSuffix  -%@- ", fileNameSuffix);
    
    NSString* fileName = [documentsDirectory stringByAppendingPathComponent:fileNameSuffix];
    [pdfData writeToFile:fileName atomically:YES];
    
    NSURL *url = [NSURL fileURLWithPath:fileName];
    
    //use the UIDocInteractionController API to get list of devices that support the file type
    docController = [UIDocumentInteractionController interactionControllerWithURL:url];
    
    
    //present a drop down list of the apps that support the file type, click an item in the list will open that app while passing in the file.
    
    // use this if view is where the button is
    //[docController presentOpenInMenuFromRect:[self.view convertRect:sender.frame fromView:sender.superview] inView:self.view animated:YES];
    
    //[docController presentOpenInMenuFromRect:[self.ScrollViewManifest convertRect:self.ScrollViewManifest.frame fromView:self.ScrollViewManifest.superview] inView:self.ScrollViewManifest animated:YES];
    
    //([[UIApplication sharedApplication] canOpenURL:fileurl] &&
    [docController presentOpenInMenuFromRect:CGRectZero inView:_viewManifestListo animated:YES];
    
}

- (void)createPDFDataFromManifest {
    
    //NSLog(@"createPDFDataFromManifest");
    
    _manifestPageNumber.text = @"";
    NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"];
    if (dedicatedCustomerData.length < 2) {
        dedicatedCustomerData = @"";
    }
    if ([dedicatedCustomerData rangeOfString:@"createExtraEquipmentPage"].location != NSNotFound  ) {
        if (equipmentItemsOnBoard > 0) {
            _manifestPageNumber.text = @"Page 1/2";
        }
    }
    
    _viewEquipmentListOverManifest.hidden = YES;
    int pixelWidth = ScrollViewManifest.contentSize.width*1.6;
    int pixelHeight = ScrollViewManifest.contentSize.height*0.8;  // set hight of pdf page here (cut off the bottom)
    
    pdfData = [NSMutableData data];
    
    UIGraphicsBeginPDFContextToData( pdfData, CGRectMake(0, 0, pixelWidth, pixelHeight),  nil );
    UIGraphicsBeginPDFPage();
    CGPoint savedContentOffset = ScrollViewManifest.contentOffset;
    CGRect savedFrame = ScrollViewManifest.frame;
    ScrollViewManifest.contentOffset = CGPointZero;
    ScrollViewManifest.frame = CGRectMake(0, 0, pixelWidth, pixelHeight);    
    [ScrollViewManifest.layer renderInContext: UIGraphicsGetCurrentContext()];    
    ScrollViewManifest.contentOffset = savedContentOffset;
    ScrollViewManifest.frame = savedFrame;
     
    
    if ([dedicatedCustomerData rangeOfString:@"createExtraEquipmentPage"].location != NSNotFound  ) {          
        if (equipmentItemsOnBoard > 0) {
            _manifestPageNumber.text = @"Page 2/2";
            [self createSpecialEquipListItemsForManifest];                
            _viewEquipmentListOverManifest.hidden = NO;
            [ScrollViewManifest bringSubviewToFront:_viewEquipmentListOverManifest];        
            UIGraphicsBeginPDFPage();
            ScrollViewManifest.contentOffset = CGPointZero;
            ScrollViewManifest.frame = CGRectMake(0, 0, pixelWidth, pixelHeight);    
            [ScrollViewManifest.layer renderInContext: UIGraphicsGetCurrentContext()];    
            ScrollViewManifest.contentOffset = savedContentOffset;
            ScrollViewManifest.frame = savedFrame; 
        }
              
    }
        
    UIGraphicsEndPDFContext();    
    _viewEquipmentListOverManifest.hidden = YES;
    
}

static UIDocumentInteractionController* docController;


- (void) animateFuelPathAndCheckCG {
    
 //NSLog(@"animateFuelPathAndCheckCG");
    
 
    
    if (flagMultipleFuelTanks >= 1) {        
        [self animateFuelPathAndCheckCGForMultipleTanks];
        return;
    }
    
    if (flagDoNotDrawCG == 1) {       
        //NSLog(@"retunring! do not draw");
        return;
    }
    
    //NSLog(@"doing animateFuelPathAndCheckCG");
    
    for(UIView *subview in [_viewFuelPathCG subviews]) {
        [subview removeFromSuperview];
    }
    
  
    
    float xCGpos = 0;
    float yCGpos = 0;
    float fuelPathSteps = 50;
    [self.viewFuelPathCG.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines
    
    float stepWeight = 0;
    float simulatedAircraftWeight = 0;
    float simulatedFuelMoment = 0;
    float simulatedTotalMoment = 0;
    
    float fuelUnitsInEnvelope1 = 0;
    float fuelUnitsInEnvelope2 = 0;
    float fuelUnitsOutsideEnvelopes = 0;
    float fuelUnitsOutsideMargin = 0;
    
    int flagIsInEnvelope = 0;
    
    float weightUnit = 0;
    
    mostFWDCGpoint = 99999;
    
    float merkerFuelVolume = fuelVolume;
    //NSLog(@"----- merkerFuelVolume %.3f", merkerFuelVolume );
    
    if (flagDoNotDrawCG == 2) {      
        merkerFuelVolume = robinsonTotalFuelForCG;
    }
    
    //NSLog(@"vTOW %.3f", vTOW );
    //NSLog(@"lZFW %.3f", lZFW );
    
    //NSLog(@"vTOW %.1f", vTOW );
    
    for (int i = 0; i < fuelPathSteps+1 ; i++) { /// make dots fuel
        
  
        
        stepWeight = i * ((vTOW - lZFW) / fuelPathSteps);
        weightUnit = (vTOW - lZFW) / fuelPathSteps ;
        
       
        
        // get fuel moment
        fuelVolume = stepWeight / [_inputSpecificFuelMassPerVolume.text floatValue];
        fuelWeight = stepWeight;
        
        //NSLog(@"fuelWeight %.3f", fuelWeight );
        //NSLog(@"lZFW %.3f", lZFW );
        //NSLog(@"lZFW + fuelWeight %.3f", lZFW + fuelWeight );
        
        if (flagDoNotDrawCG == 2) { 
             fuelMoment = (fuelVolume * [_inputSpecificFuelMassPerVolume.text floatValue]) * robinsonArmForCG;
        }else{
             [self interpolateFuelMomentsLongitudinal]; // here we get fuel moment
        }
        
        
       
      
        //NSLog(@"2 fuelMoment %.0f", fuelMoment);
        
        simulatedFuelMoment = fuelMoment;
        // compute CG
        simulatedTotalMoment = (lZFW * lZFWArm) + simulatedFuelMoment;
        simulatedAircraftWeight = lZFW  + stepWeight;

        
        
        //NSLog(@"lZFWArm %.0f", lZFWArm);
        
        if (i == fuelPathSteps - 1) {
            simulatedAircraftWeight = weightTOW;
            simulatedTotalMoment =weightTOW * CGLongTOW;
            
           
        }
        
        // get point coordinates
        float xCGval = simulatedTotalMoment / simulatedAircraftWeight;
        
         
       
        
        float yCGval = simulatedAircraftWeight;
        
        if (xCGval <= mostFWDCGpoint & yCGval >= weightLDW) {
            mostFWDCGpoint = xCGval;
            mostFWDweight = yCGval;
            //NSLog(@"changing mostFWDCGpoint %.0f ", mostFWDCGpoint );
        }
        
        float weightCheckStart = weightLDW;        
        
        if ([[_arrayName25 objectAtIndex:35] isEqualToString:@"ZF"]) {
            weightCheckStart = weightZFW;           
        }
        
        if ([[_arrayName25 objectAtIndex:35] isEqualToString:@"TO"]) {
            weightCheckStart = weightTOW-1;
           
        }
        
   
        
    
        if (simulatedAircraftWeight > weightCheckStart) {
            //NSLog(@"found ldw i %d", i);
            
            // check CG **************************************************************************************************
            [self checkCGwarningLongitudinal: xCGval transferWeightTOW:yCGval ];
            // check CG **************************************************************************************************
            
            if (CGwithinEnvelope1 == 1) {
                //NSLog(@"1");
                fuelUnitsInEnvelope1 = fuelUnitsInEnvelope1 + weightUnit;
                flagIsInEnvelope = 1;
            }
            if (CGwithinEnvelope2 == 1) {
                //NSLog(@"2");
                fuelUnitsInEnvelope2 = fuelUnitsInEnvelope2 + weightUnit;
                flagIsInEnvelope = 2;
            }
            
            
            
            
            // new! the second envlope erweitert den envlope!            
            if ( [[_arrayName23 objectAtIndex:25] isEqualToString:@"no"]) {
                
                if (CGwithinEnvelope1 == 0 ) {
                    //NSLog(@"3");
                    fuelUnitsOutsideEnvelopes = fuelUnitsOutsideEnvelopes + weightUnit;
                    flagIsInEnvelope = 0;
                }                
            }else{
                if (CGwithinEnvelope1 == 0 & CGwithinEnvelope2 == 0) {
                    //NSLog(@"3");
                    fuelUnitsOutsideEnvelopes = fuelUnitsOutsideEnvelopes + weightUnit;
                    flagIsInEnvelope = 0;
                }
                
            }
            
            
            
            
            
            if (CGwithinMargin == 0 ) {
                //NSLog(@"4");
                fuelUnitsOutsideMargin = fuelUnitsOutsideMargin + weightUnit;
            }
        }
        
  
        
        xCGpos = leftBorderOfMeasureBox + ( (xCGval-xAxisLeft) * xPixelFactor );
        yCGpos = topBorderOfMeasureBox  + (  (yAxisTop - yCGval) * yPixelFactor );
        
        if (isnan(xCGpos)) {
            xCGpos = 0;
        }
        if (isnan(yCGpos)) {
            yCGpos = 0;
        }
        
       
        
        float dotSize = 5;
        CAShapeLayer *circleLayer = [CAShapeLayer layer];
        [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];
        
        

        //NSLog(@"CGwithinEnvelope1 %d", CGwithinEnvelope1);
        //NSLog(@"CGwithinEnvelope2 %d", CGwithinEnvelope2);
        
        [circleLayer setPosition:CGPointMake( xCGpos, yCGpos)];
        
        
        
        UIBezierPath *pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)];
        [circleLayer setPath:[pathC CGPath]];
        [circleLayer setStrokeColor:[[UIColor clearColor] CGColor]];
        
    
       
        if (CGwithinEnvelope1 == 0 ) {
            [circleLayer setFillColor:[[UIColor redColor] CGColor]];
        }
        
 
        
        if (CGwithinEnvelope1 == 1 ) {
            [circleLayer setFillColor:[lightBlueColor CGColor]];
        }
        if (CGwithinEnvelope2 == 1 ) {
            [circleLayer setFillColor:[orangeSpecialColor CGColor]];
        }
        [circleLayer setLineWidth:0.0f];

        
        if (i > 1 & simulatedAircraftWeight > weightLDW) {
            [self.viewFuelPathCG.layer addSublayer:circleLayer];
        }
       
      
    }// end for next make path
    
    fuelVolume = merkerFuelVolume;
    
    flagDoNotDrawCG = 0;
    
    if ( [[_arrayName21 objectAtIndex:47] isEqualToString:@"Yellow"]) {
        shapeLayerCG1.strokeColor = [yellowSpecialColor CGColor];        
    }else{
        shapeLayerCG1.strokeColor = [GreenColor CGColor];
    }
    
    
    
    shapeLayerCGMargin.strokeColor = [verylightBlueColor CGColor];
   
    
    // envelope is always grey
    // if in envelope, envelope is colored    
    shapeLayerCG2.strokeColor = [[UIColor lightGrayColor] CGColor];
    if (fuelUnitsInEnvelope2 > 0 ) {           
        shapeLayerCG2.strokeColor = [orangeSpecialColor CGColor];
        //_labelCGinExtendedEnvelope.hidden = NO;
    }
    
    
    
    if (fuelUnitsOutsideEnvelopes > 0) {
        flagWarningCG = 1;
        shapeLayerCG1.strokeColor = [[UIColor redColor] CGColor];
        shapeLayerCG2.strokeColor = [[UIColor redColor] CGColor];
        flagWarningCG = 1;
       
    }
    
    if (flagWarningCG == 1 ) {
        counterAutoCheckFlagStatus = 1;
        warningCGoutsideEnvelope.hidden = NO;
        [self setACImage: 1];
    }
    
        

    
    
    float fuelAllowance = 0;
    float rampMass =  weightTOW;
    float takeoffWeight =  weightTOW-fuelAllowance;
    float maxRamp = 0;
     maxRamp = [[_arrayName21 objectAtIndex: 7] floatValue];
    
    //float maxTOW = [[_arrayName21 objectAtIndex: 9] floatValue];
    float maxLDW = 0;
    maxLDW = [[_arrayName21 objectAtIndex: 11] floatValue];

    
    
    if (takeoffWeight > MTOWfromEnvelope) {
        flagWarningWeight = 1;
    }
    
    if (rampMass   > maxRamp) {
        flagWarningWeight = 2;
    }
    
    if (weightLDW > maxLDW) {
        flagWarningWeight = 3;
    }
    
    
    // show hide warnings
    warningAS355Pax5.hidden = YES; warningCGoutsideEnvelope.hidden = YES; warningLatCGExceeded.hidden = YES;  warningWeightLimitExceeded.hidden = YES;
    
   
    
    
    
    if (flagWarningCG == 1 ) {
        counterAutoCheckFlagStatus = 1;
        warningCGoutsideEnvelope.hidden = NO;
        [self setACImage: 1];
        
    }
    
    if (flagWarningWeight == 1 ) {
        counterAutoCheckFlagStatus = 1;
        warningWeightLimitExceeded.hidden = NO;
        warningWeightLimitExceeded.text =@"MAX TOM EXCEEDED";
        [self setACImage: 1];
       
    }
    
    
    if (flagWarningWeight == 3 ) {
        counterAutoCheckFlagStatus = 1 ;
        warningWeightLimitExceeded.hidden = NO;
        warningWeightLimitExceeded.text =@"MAX LANDING MASS EXCEEDED";
        [self setACImage: 1];
       
    }
    
  
    
}


- (void) animateFuelPathAndCheckCGForMultipleTanks {
    
    //NSLog (@"animateFuelPathAndCheckCGForMultipleTanks ");
    
    for(UIView *subview in [_viewFuelPathCG subviews]) {
        [subview removeFromSuperview];
    }
   
    [self.viewFuelPathCG.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines
 

    int flagIsInEnvelope = 1;
 
    
    mostFWDCGpoint = 99999;
    [self checkCGwarningLongitudinal: CGLongTOW transferWeightTOW:weightTOW ];
    
    if (CGwithinEnvelope1 == 0) {
        flagIsInEnvelope = 0;
    }
   
    [self checkCGwarningLongitudinal: CGLongLDW transferWeightTOW:weightLDW ];
    if (CGwithinEnvelope1 == 0) {
        flagIsInEnvelope = 0;
    }
    
     //NSLog (@"flagIsInEnvelope %d", flagIsInEnvelope);
    
    if ( [[_arrayName21 objectAtIndex:47] isEqualToString:@"Yellow"]) {
        shapeLayerCG1.strokeColor = [yellowSpecialColor CGColor];
    }else{
        shapeLayerCG1.strokeColor = [GreenColor CGColor];
    }
    
    shapeLayerCGMargin.strokeColor = [verylightBlueColor CGColor];
    // hoist
    if ([[_arrayName2 objectAtIndex:lineHoistSystem] floatValue] > 0) {
        if ( [[_arrayName21 objectAtIndex:47] isEqualToString:@"Yellow"]) {
            shapeLayerCG2.strokeColor = [yellowSpecialColor CGColor];
        }else{
            shapeLayerCG2.strokeColor = [GreenColor CGColor];
        }
    }else{
        shapeLayerCG2.strokeColor = [[UIColor lightGrayColor] CGColor];
    }
    
    
    if (flagIsInEnvelope == 0 ) {
        counterAutoCheckFlagStatus = 1;
        warningCGoutsideEnvelope.hidden = NO;
        [self setACImage: 1];
    }
    
    float fuelAllowance = 0;
    float rampMass =  weightTOW;
    float takeoffWeight =  weightTOW-fuelAllowance;
    //float maxTOW = [[_arrayName21 objectAtIndex: 9] floatValue];
    float maxRamp = 0;
     maxRamp = [[_arrayName21 objectAtIndex: 7] floatValue];
    
    
    //float maxTOW = [[_arrayName21 objectAtIndex: 9] floatValue];
    float maxLDW = 0;
    maxLDW = [[_arrayName21 objectAtIndex: 11] floatValue];
    if (maxLDW < 1) {
        maxLDW = 999999;
    }
    
    if (takeoffWeight > MTOWfromEnvelope) {
        flagWarningWeight = 1;
    }
    
    if (rampMass   > maxRamp) {
        flagWarningWeight = 2;
    }
    
    
    //NSLog(@"weightLDW %.0f", weightLDW);
    
    //NSLog(@"maxLDW %.0f", maxLDW);
    
    if (weightLDW > maxLDW) {
        flagWarningWeight = 3;
    }
    
    
    // show hide warnings
    warningAS355Pax5.hidden = YES; warningCGoutsideEnvelope.hidden = YES; warningLatCGExceeded.hidden = YES;  warningWeightLimitExceeded.hidden = YES;
    
    
  
    
    
    if (flagIsInEnvelope == 0 ) {
        counterAutoCheckFlagStatus = 1;
        warningCGoutsideEnvelope.hidden = NO;
        [self setACImage: 1];
        
        shapeLayerCG1.strokeColor = [[UIColor redColor] CGColor];
        shapeLayerCG2.strokeColor = [[UIColor redColor] CGColor];
        
    }
    
    if (flagWarningWeight == 1 ) {
        counterAutoCheckFlagStatus = 1;
        warningWeightLimitExceeded.hidden = NO;
        warningWeightLimitExceeded.text =@"MAX TOM EXCEEDED";
        [self setACImage: 1];
        
    }
    
    if (flagWarningWeight == 3 ) {
        counterAutoCheckFlagStatus = 1 ;
        warningWeightLimitExceeded.hidden = NO;
        warningWeightLimitExceeded.text =@"MAX LANDING MASS EXCEEDED";
        [self setACImage: 1];
        
    }
    
    
}

- (void) animateFuelPathLateralAndCheckCG {
    
    //NSLog(@"[animateFuelPathLateralAndCheckCG");
    flagWarningCG = 0;
    
    if ( [[_arrayName21 objectAtIndex:13] isEqualToString:@"noLat"]) {
        return;
    }
    
    if (flagMultipleFuelTanks >= 1) {
        [self animateFuelPathLateralAndCheckCGForMultipleTanks];
        return;
    }
    
    
    
   
    
    float xCGpos = 0;
    float yCGpos = 0;
    float fuelPathSteps = 20;
    [self.viewFuelPathCGLat.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old dots
    
    float stepWeight = 0;
    float simulatedAircraftWeight = 0;
    float simulatedFuelMoment = 0;
    float simulatedTotalMoment = 0;
    
    float weightUnit = 0;
    
    for (int i = 0; i < fuelPathSteps ; i++) { /// make dots
        
        stepWeight = i * ((vTOW - lZFW) / fuelPathSteps);
        weightUnit = (vTOW - lZFW) / fuelPathSteps ;
        float maxTankWeight = tankCapacityVolume * [_inputSpecificFuelMassPerVolume.text floatValue];
        
        
        if (stepWeight >= maxTankWeight) {
            break;
            //uff, das hat ja mal den halben Tag gekostet, greetings from Wendy Way 1909
        }
        
        // get fuel moment lateral
        fuelVolume = stepWeight / [_inputSpecificFuelMassPerVolume.text floatValue];
        fuelWeight = stepWeight;
        [self interpolateFuelMomentsLateral]; // here we get fuel moment
        
         //NSLog(@"fuelMoment %.0f", fuelMoment);
        if (isnan(fuelMoment)) {
            fuelMoment = 0;
        }
        
        simulatedFuelMoment = fuelMoment;
        // compute CG
        simulatedTotalMoment = (lZFW * lZFWArmLat) + simulatedFuelMoment;
        simulatedAircraftWeight = lZFW  + stepWeight;
        // get point coordinates
        float xCGval = simulatedTotalMoment / simulatedAircraftWeight;
        float yCGval = simulatedAircraftWeight;
        
        CGPoint pointTakeoffCG = {xCGval, simulatedAircraftWeight};
        if (!CGPathContainsPoint(shapeLayerFreakViewCG1Lat.path, NULL, pointTakeoffCG, FALSE)) {
            
            if (![[_arrayName21 objectAtIndex:13] isEqualToString:@"noLat"]) {
                flagWarningCG = 1;
            }
        }
        
        
        
        // find landing weight
        //NSLog(@"i %d", i);
        xCGpos = leftBorderOfMeasureBoxLAT + ( (xCGval-xAxisLeftLAT) * xPixelFactorLAT );
        yCGpos = topBorderOfMeasureBoxLAT  + (  (yAxisTopLAT - yCGval) * yPixelFactorLAT );
        
        
        if (isnan(xCGpos)) {
            xCGpos = 0;
        }
        if (isnan(yCGpos)) {
            yCGpos = 0;
        }
        
        
        
        float dotSize = 5;
        CAShapeLayer *circleLayer = [CAShapeLayer layer];
        [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];
        [circleLayer setPosition:CGPointMake( xCGpos, yCGpos)];
        UIBezierPath *pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)];
        [circleLayer setPath:[pathC CGPath]];
        [circleLayer setStrokeColor:[[UIColor clearColor] CGColor]];
        [circleLayer setFillColor:[lightBlueColor CGColor]];
        [circleLayer setLineWidth:0.0f];
        
        if (i > 1 & simulatedAircraftWeight > weightLDW) {
            [self.viewFuelPathCGLat.layer addSublayer:circleLayer];
        }
        
       
        
    }// end for next make path
    
 
    
    // check takeoff
    CGPoint pointTakeoffCG = {CGLATTOW, weightTOW};
    if (!CGPathContainsPoint(shapeLayerFreakViewCG1Lat.path, NULL, pointTakeoffCG, FALSE)) {
        
        if ( ![[_arrayName21 objectAtIndex:13] isEqualToString:@"noLat"]) {
            flagWarningCG = 1;
        }
    }
    
    // check landing
    CGPoint pointLandingCG = {CGLATLDW, weightLDW};
    
    //NSLog(@"AC_Type %@", AC_Type);
    //NSLog(@"unitsWeight %@", unitsWeight.text);
    //NSLog(@"weightLDW %.2f", weightLDW);
    //NSLog(@"CGLATLDW %.2f", CGLATLDW);
    //NSLog(@"externalLoadAttached %.2f", externalLoadAttached);
    
    
    warningLatCGExceeded.text = @"LAT CG EXCEEDED";
    
    if ([AC_Type isEqualToString:@"H125"] & [unitsWeight.text isEqualToString:@"lbs"]) {
      
        if (weightLDW >= 4961) {
            
            if (CGLATLDW < -3.15 || CGLATLDW > 3.15 ) {
                flagWarningCG = 1;
                 warningLatCGExceeded.text = @"LAT CG LD EXCEEDED";
            }            
        }        
    }
    
    if ([AC_Type isEqualToString:@"H125"] & [unitsWeight.text isEqualToString:@"kg"]) {
      
        if ( weightLDW >= 2250) {
            
            if (CGLATLDW < -80 || CGLATLDW > 80 ) {
                flagWarningCG = 1;
                 warningLatCGExceeded.text = @"LAT CG LD EXCEEDED";
            }            
        }
        
    }
    
    
    
    
    if (!CGPathContainsPoint(shapeLayerFreakViewCG1Lat.path, NULL, pointLandingCG, FALSE)) {
        if (  ![[_arrayName21 objectAtIndex:13] isEqualToString:@"noLat"]) {
            flagWarningCG = 1;
        }
    }
    
    // show hide warnings
    warningLatCGExceeded.hidden = YES;
    
    if (  [[_arrayName21 objectAtIndex:47] isEqualToString:@"Yellow"]) {        
        shapeLayerCG1Lat.strokeColor = [yellowSpecialColor CGColor];        
    }else{
        shapeLayerCG1Lat.strokeColor = [GreenColor CGColor];
    }
    
    
    if (flagNoLatLimit == 1) {
        flagWarningCG = 0;
    }
    
    if (flagWarningCG == 1 ) {
        warningLatCGExceeded.hidden = NO;
        shapeLayerCG1Lat.strokeColor = [[UIColor redColor] CGColor];
        [self setACImage: 1];
    }
    
    return;
    
    
}

- (void) animateFuelPathLateralAndCheckCGForMultipleTanks {
    
    //NSLog(@"[animateFuelPathLateralAndCheckCG");
    
    flagWarningCG = 0;
    
    [self.viewFuelPathCGLat.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old dots
    
    
    // check takeoff
    CGPoint pointTakeoffCG = {CGLATTOW, weightTOW};
    if (!CGPathContainsPoint(shapeLayerFreakViewCG1Lat.path, NULL, pointTakeoffCG, FALSE)) {
        flagWarningCG = 1;
    }
    
    // check landing
    CGPoint pointLandingCG = {CGLATLDW, weightLDW};
    if (!CGPathContainsPoint(shapeLayerFreakViewCG1Lat.path, NULL, pointLandingCG, FALSE)) {
        flagWarningCG = 1;
    }
    
    // show hide warnings
    warningLatCGExceeded.hidden = YES;
    
    if ([[_arrayName21 objectAtIndex:47] isEqualToString:@"Yellow"]) {
        shapeLayerCG1Lat.strokeColor = [yellowSpecialColor CGColor];
    }else{
        shapeLayerCG1Lat.strokeColor = [GreenColor CGColor];
    }
    
    if (flagNoLatLimit == 1) {
        flagWarningCG = 0;
    }
    
    
    if (flagWarningCG == 1 ) {
        warningLatCGExceeded.hidden = NO;
        shapeLayerCG1Lat.strokeColor = [[UIColor redColor] CGColor];
        [self setACImage: 1];
    }
    
    return;
    
    
    
    
    
}

- (void) animateFuelPathLateralAndCheckCGH130 {
    
    //NSLog(@"[animateFuelPathLateralAndCheckCGH130");
    [self.viewFuelPathCGLat.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old dots
    
    flagWarningCG = 0;
    // check takeoff
    CGPoint pointTakeoffCG = {CGLongTOW, CGLATTOW};  // x then y
    if (!CGPathContainsPoint(shapeLayerFreakViewCG1Lat.path, NULL, pointTakeoffCG, FALSE)) {
        flagWarningCG = 1;
    }
    
    // check landing
    CGPoint pointLandingCG = {CGLongLDW, CGLATLDW};  // x then y
    if (!CGPathContainsPoint(shapeLayerFreakViewCG1Lat.path, NULL, pointLandingCG, FALSE)) {
        flagWarningCG = 1;
    }
    
    // show hide warnings
    warningLatCGExceeded.hidden = YES;
    
    
    if (  [[_arrayName21 objectAtIndex:47] isEqualToString:@"Yellow"]) {
        
        shapeLayerCG1Lat.strokeColor = [yellowSpecialColor CGColor];
        
    }else{
        shapeLayerCG1Lat.strokeColor = [GreenColor CGColor];
        
    }
    
    
    
    
    if (flagWarningCG == 1 ) {
        warningLatCGExceeded.hidden = NO;
        shapeLayerCG1Lat.strokeColor = [[UIColor redColor] CGColor];
        [self setACImage: 1];
    }
    
    return;
    
    
    
    
    
}






- (void) animateFuelPathManifest {
    
    //NSLog(@"animateFuelPath ");
    
    [self.viewFuelPathCGManifest.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines
    
    if (fuelVolume <1) {
        return;
    }
    if (flagCreateFuelPage == 1) {
      return;
    }
    
    float xCGpos = 0;
    float yCGpos = 0;
    float fuelPathSteps = 50;
    [self.viewFuelPathCGManifest.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines
    
    
    float stepWeight = 0;
    float simulatedAircraftWeight = 0;
    float simulatedFuelMoment = 0;
    float simulatedTotalMoment = 0;
    
    
    for (int i = 0; i < fuelPathSteps ; i++) { /// make dots
        stepWeight = i * ((vTOW- lZFW) / fuelPathSteps);
        // get fuel moment
        fuelVolume = stepWeight / [_inputSpecificFuelMassPerVolume.text floatValue];
        fuelWeight = stepWeight;
        //NSLog(@"semding from 2");
        [self interpolateFuelMomentsLongitudinal]; // here we get fuel moment
        
        simulatedFuelMoment = fuelMoment;
        // compute CG
        simulatedTotalMoment = (lZFW * lZFWArm) + simulatedFuelMoment;
        simulatedAircraftWeight = lZFW  + stepWeight;
        
        
        // get point coordinates
        float xCGval = simulatedTotalMoment / simulatedAircraftWeight;
        float yCGval = simulatedAircraftWeight;
        xCGpos = leftBorderOfMeasureBox2 + ( (xCGval-xAxisLeft2) * xPixelFactor2 );
        yCGpos = topBorderOfMeasureBox2  + (  (yAxisTop2 - yCGval) * yPixelFactor2 );
        
        float dotSize = 2.5;
        CAShapeLayer *circleLayer = [CAShapeLayer layer];
        [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];
        [circleLayer setPosition:CGPointMake( xCGpos, yCGpos)];
        
        // Create a circle path.
        UIBezierPath *pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)];
        // Set the path on the layer
        [circleLayer setPath:[pathC CGPath]];
        // Set the stroke color
        [circleLayer setStrokeColor:[[UIColor clearColor] CGColor]];
        
        //NSLog(@"flagMostFwdCGwarning   %.0f ", flagMostFwdCGwarning);
        [circleLayer setFillColor:[[UIColor blackColor] CGColor]];
        
        // Set the stroke line width
        [circleLayer setLineWidth:0.0f];
        
        if (i > 1 & simulatedAircraftWeight > weightLDW) {
            [self.viewFuelPathCGManifest.layer addSublayer:circleLayer];
        }
        
        
        
    }// end for next make path
    
    
    
    
    
    
}

    

- (void)panRecognizerAction:(UIPanGestureRecognizer *)recognizer {
    
    
    CGPoint loc = [recognizer locationInView:_viewInterior];
    
    NSMutableArray *longPoints1 = [[NSMutableArray alloc] init];
    NSMutableArray *latPoints1 = [[NSMutableArray alloc] init];
    
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        
        //NSLog(@"UIGestureRecognizerStateBegan");
        //NSLog(@"started originY %.0f", loc.y);
        
        
        stationName1      = @"";
        stationWeight1    = 0;
        stationArm1       = 0;
        stationMoment1    = 0;
        stationArmLat1    = 0;
        stationMomentLat1 = 0;
        
        
        stationName2      = @"";
        stationWeight2    = 0;
        stationArm2       = 0;
        stationMoment2    = 0;
        stationArmLat2    = 0;
        stationMomentLat2 = 0;
        
        // move ghost to start position
        
        ghostImage.center = CGPointMake(loc.x , loc.y  );
        [_viewInterior bringSubviewToFront:ghostImage];
        
        
        // find start long and lat
        
        float yOffset = 0;
        float latOffset = 0;
        
        float LongScale = (_viewMeasureRearSeats.center.y - _viewMeasureFrontSeats.center.y) / (LongArmRearSeat - LongArmFrontSeat) ;
        float LatScale  = (_viewMeasureLatRight.center.x  - _viewMeasureCenter.center.x)     / (LatArmRightSeat - LatArmLeftSeat) ;
        
        float LongArmGhost = ((((ghostImage.center.y - yOffset ) -_viewSeatSize.layer.frame.size.height/2)  + (_viewSeatSize.layer.frame.size.height/2) - _viewMeasureFrontSeats.center.y ) / LongScale )+ LongArmFrontSeat ;
        
        float LatArmGhost = ((((ghostImage.center.x - latOffset) -_viewSeatSize.layer.frame.size.width/2) + (_viewSeatSize.layer.frame.size.width/2) - _viewMeasureCenter.center.x ) / LatScale )+ LatArmLeftSeat ;
        
        
        float longLatTolerance = 180;
        
        int iTransfer = 0;
        
        
        
        //NSLog(@"---------------------------------------------------------");
        
        //NSLog(@"LongArmGhost %.0f", LongArmGhost);
        //NSLog(@"linePilot  %d", linePilot);
        
        
        
        
        for(int i=linePilot; i<listEnd; i++) {
            
            //NSLog(@"_arrayName1  %@", [_arrayName1 objectAtIndex:i]);
            
            
            if ([[_arrayName8 objectAtIndex:i]floatValue] == 0) {
                continue;
            }
            
            
            
            float itemLong = [[_arrayName3 objectAtIndex:i] floatValue] + [[_arrayName11 objectAtIndex:i] floatValue];
            float itemLat = [[_arrayName5 objectAtIndex:i] floatValue] + [[_arrayName13 objectAtIndex:i] floatValue];
            
            
            //NSLog(@"itemLong %.0f", itemLong);
            //NSLog(@"itemLat  %.0f", itemLat);
            
            
            if (itemLong > LongArmGhost - longLatTolerance  & itemLong < LongArmGhost + longLatTolerance     ) {
                
                //NSLog(@"ok, selbe reihe  %d",i);
                
                [longPoints1 addObject:[NSString stringWithFormat:@"%d",   i ]];
                
                if (LatArmGhost >= 0) { // search on right site only
                    
                    if ( itemLat < LatArmGhost + longLatTolerance  & itemLat > LatArmGhost - longLatTolerance){
                        
                        [latPoints1 addObject:[NSString stringWithFormat:@"%d",   i ]];
                        
                    }
                }
                
                
                
                if (LatArmGhost < 0) { // search on right site only
                    
                    if ( itemLat > LatArmGhost - longLatTolerance  & itemLat < LatArmGhost + longLatTolerance){
                        
                        //NSLog(@"match  %d",i);
                        
                        [latPoints1 addObject:[NSString stringWithFormat:@"%d",   i ]];
                        
                    }
                }
                
            }
            
        }
        
        //NSLog(@"longPoints1 %@", longPoints1);
        //NSLog(@"latPoints1 %@", latPoints1);
        
        //NSLog(@"longPoints.count %d", longPoints.count);
        //NSLog(@"latPoints.count %d", latPoints.count);
        
        
        
        if (latPoints1.count > 0) {
            
            for(int i=0; i<longPoints1.count; i++) {
                
                NSString *longP = [longPoints1 objectAtIndex:i];
                NSString *latP = [latPoints1 objectAtIndex:0];
                
                //NSLog(@"longP %@", longP);
                //NSLog(@"latP %@", latP);
                
                
                if ([latP isEqualToString:longP]) {
                    //NSLog(@"started longP1 %@", longP);
                    //NSLog(@"found latP   %@", latP);
                    
                    ghostImage.hidden = NO;
                    
                    iTransfer = [longP intValue];
                    foundMatch1 = 1;
                    matchItemID1 = iTransfer;
                    
                    stationName1      = [_arrayName7 objectAtIndex:iTransfer];
                    stationWeight1    = [[_arrayName2 objectAtIndex:iTransfer] floatValue];
                    stationArm1       = [[_arrayName3 objectAtIndex:iTransfer] floatValue];
                    stationMoment1    = [[_arrayName4 objectAtIndex:iTransfer] floatValue];
                    stationArmLat1    = [[_arrayName5 objectAtIndex:iTransfer] floatValue];
                    stationMomentLat1 = [[_arrayName6 objectAtIndex:iTransfer] floatValue];
                    
                    //NSLog(@"stationName1 %@", stationName1);
                    
                    //NSLog(@"start stationArm1 %.0f", stationArm1);
                    
                    
                    
                    break;
                    
                }else{
                    foundMatch1 = 0;
                    
                }
                
                
            }
        }
        
        
        
        
        
    }// end of touches began
    
    
    
    
    
    
    
    
    
    // move ghost
    CGPoint translation = [recognizer translationInView:self.view];
    ghostImage.center = CGPointMake(ghostImage.center.x + (translation.x ) , ghostImage.center.y + (translation.y ) );
    
    
    NSMutableArray *longPoints = [[NSMutableArray alloc] init];
    NSMutableArray *latPoints = [[NSMutableArray alloc] init];
    
    if (recognizer.state == UIGestureRecognizerStateChanged) {
        
        [[self.viewInterior viewWithTag:9999] removeFromSuperview];
        
        //NSLog(@"-");
        
        // find start long and lat
        
        float yOffset = 0;
        float latOffset = 0;
        
        float LongScale = (_viewMeasureRearSeats.center.y - _viewMeasureFrontSeats.center.y) / (LongArmRearSeat - LongArmFrontSeat) ;
        float LatScale  = (_viewMeasureLatRight.center.x  - _viewMeasureCenter.center.x)     / (LatArmRightSeat - LatArmLeftSeat) ;
        
        float LongArmGhost = ((((ghostImage.center.y - yOffset ) -_viewSeatSize.layer.frame.size.height/2)  + (_viewSeatSize.layer.frame.size.height/2) - _viewMeasureFrontSeats.center.y ) / LongScale )+ LongArmFrontSeat ;
        
        float LatArmGhost = ((((ghostImage.center.x - latOffset) -_viewSeatSize.layer.frame.size.width/2) + (_viewSeatSize.layer.frame.size.width/2) - _viewMeasureCenter.center.x ) / LatScale )+ LatArmLeftSeat ;
        
        //float longLatTolerance = (_viewSeatSize.frame.size.width / LatScale) - ((_viewSeatSize.frame.size.width / LatScale) * 0.05);
        
        
        float longLatTolerance = 180;
        //NSLog(@"LongArmGhost %.2f", LongArmGhost);
        //NSLog(@"LatArmGhost %.2f", LatArmGhost);
        
        
        
        int iTransfer = 0;
        
        for(int i=linePilot; i<listEnd; i++) {
            
            if ([[_arrayName8 objectAtIndex:i]floatValue] == 0) {
                continue;
            }
            
            
            float itemLong = [[_arrayName3 objectAtIndex:i] floatValue] + [[_arrayName11 objectAtIndex:i] floatValue];
            float itemLat = [[_arrayName5 objectAtIndex:i] floatValue] + [[_arrayName13 objectAtIndex:i] floatValue];
            
            
            if (itemLong > LongArmGhost - longLatTolerance  & itemLong < LongArmGhost + longLatTolerance     ) {
                
                //NSLog(@"ok, selbe reihe  %d",i);
                
                [longPoints addObject:[NSString stringWithFormat:@"%d",   i ]];
                
                if (LatArmGhost >= 0) { // search on right site only
                    
                    if ( itemLat < LatArmGhost + longLatTolerance  & itemLat > LatArmGhost - longLatTolerance){
                        
                        [latPoints addObject:[NSString stringWithFormat:@"%d",   i ]];
                        
                    }
                }
                
                
                
                if (LatArmGhost < 0) { // search on right site only
                    
                    if ( itemLat > LatArmGhost - longLatTolerance  & itemLat < LatArmGhost + longLatTolerance){
                        
                        //NSLog(@"match  %d",i);
                        
                        [latPoints addObject:[NSString stringWithFormat:@"%d",   i ]];
                        
                    }
                }
                
            }
            
        }
        
        //NSLog(@"longPoints %@", longPoints);
        //NSLog(@"latPoints %@", latPoints);
        
        //NSLog(@"longPoints.count %d", longPoints.count);
        //NSLog(@"latPoints.count %d", latPoints.count);
        
        
        
        if (latPoints.count > 0) {
            
            for(int i=0; i<longPoints.count; i++) {
                
                NSString *longP = [longPoints objectAtIndex:i];
                NSString *latP = [latPoints objectAtIndex:0];
                
                //NSLog(@"longP %@", longP);
                //NSLog(@"latP %@", latP);
                
                
                if ([latP isEqualToString:longP]) {
                    
                    
                    
                    //NSLog(@"found longP  %@", longP);
                    //NSLog(@"found latP   %@", latP);
                    
                    iTransfer = [longP intValue] ;
                    foundMatch2 = 1;
                    matchItemID2 = iTransfer;
                    
                    stationName2      = [_arrayName7 objectAtIndex:iTransfer];
                    stationWeight2    = [[_arrayName2 objectAtIndex:iTransfer] floatValue];
                    stationArm2       = [[_arrayName3 objectAtIndex:iTransfer] floatValue];
                    stationMoment2    = [[_arrayName4 objectAtIndex:iTransfer] floatValue];
                    stationArmLat2    = [[_arrayName5 objectAtIndex:iTransfer] floatValue];
                    stationMomentLat2 = [[_arrayName6 objectAtIndex:iTransfer] floatValue];
                    
                 
                    
                    if (ghostImage.hidden == NO) {
                        // make a temporary cover
                        UIImageView *stationImage = (UIImageView*)[_viewInterior viewWithTag: 1500 + iTransfer];
                        UIImageView *interiorItem =[[UIImageView alloc] initWithFrame:CGRectMake(stationImage.frame.origin.x, stationImage.frame.origin.y, stationImage.frame.size.width , stationImage.frame.size.height ) ];
                        interiorItem.image=[UIImage imageNamed: @"box generic yellow.png" ];
                        interiorItem.tag = 9999;
                        interiorItem.alpha =0.8;
                        [self.viewInterior addSubview:interiorItem];
                        
                    }
                    
                    
                    break;
                    
                    
                    
                    
                    
                }else{
                    
                    foundMatch2 = 0;
                    matchItemID2 = 0;
                }
                
                
            }
        }
        
        
        
        
        
        
        
        
    }
    
    
    
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        
        //NSLog(@"UIGestureRecognizerStateEnded");
        
        
        //NSLog(@"foundMatch1 ************************************  %d",foundMatch1);
        //NSLog(@"foundMatch2 ************************************  %d",foundMatch2);
        
        
        [[self.viewInterior viewWithTag:9999] removeFromSuperview];
        
        ghostImage.hidden = YES;
        
        if (foundMatch1 == 1 & foundMatch2 == 1) {
            
            //NSLog(@"matchItemID1 ************************************  %d",matchItemID1);
            //NSLog(@"matchItemID2 ************************************  %d",matchItemID2);
            
            foundMatch1 = 0;
            foundMatch2 = 0;
            
            //NSLog(@"found two matches!");
            
            
            //NSLog(@"stationName1       %@", stationName1 );
            //NSLog(@"stationWeight1     %.0f", stationWeight1 );
            //NSLog(@"stationArm1     %.0f", stationArm1 );
            //NSLog(@"stationMoment1     %.0f", stationMoment1 );
            //NSLog(@"stationArmLat1     %.0f", stationArmLat1 );
            //NSLog(@"stationMomentLat1     %.0f", stationMomentLat1 );
            
            //NSLog(@"aaaa stationName2       %@", stationName2 );
            //NSLog(@"stationWeight2     %.0f", stationWeight2 );
            //NSLog(@"stationArm2     %.0f", stationArm2 );
            //NSLog(@"stationMoment2     %.0f", stationMoment2 );
            //NSLog(@"stationArmLat2     %.0f", stationArmLat2 );
            //NSLog(@"stationMomentLat2     %.0f", stationMomentLat2 );
            
            
            // die Hunde von der ersten Position auf die zweiter Position
            
            [_arrayName7 replaceObjectAtIndex:matchItemID2 withObject: stationName1 ];
            
            [_arrayName2 replaceObjectAtIndex:matchItemID2 withObject: [ [NSString alloc] initWithFormat:@"%.1f", stationWeight1]];
            
            float computedNewMoment = stationWeight1 * stationArm2;
            
            [_arrayName4 replaceObjectAtIndex:matchItemID2 withObject: [ [NSString alloc] initWithFormat:@"%.1f", computedNewMoment]];
            
            float computedNewMomentLat = stationWeight1 * stationArmLat2;
            
            [_arrayName6 replaceObjectAtIndex:matchItemID2 withObject: [ [NSString alloc] initWithFormat:@"%.1f", computedNewMomentLat]];
            
            
            // update name label 1200
            
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200 + matchItemID2];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200 + matchItemID2];
            }
            
            [valueField  setText: stationName1  ];
            
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1000 + matchItemID2];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1000 + matchItemID2];
            }
            
            [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", stationWeight1]  ];
            
            // update slider
            
            UISlider *slider = (UISlider*)[_viewStationsSlider viewWithTag:  matchItemID2 ];
            if (!slider) {
                slider = (UISlider*)[_viewStationsSliderRight viewWithTag:  matchItemID2 ];
            }
            
            slider.value = stationWeight1;
            
            
            // dann die Hunde von der zweiten Position auf die erste Position
            
            
            [_arrayName7 replaceObjectAtIndex:matchItemID1 withObject: stationName2 ];
            
            [_arrayName2 replaceObjectAtIndex:matchItemID1 withObject: [ [NSString alloc] initWithFormat:@"%.1f", stationWeight2]];
            
            computedNewMoment = stationWeight2 * stationArm1;
            
            [_arrayName4 replaceObjectAtIndex:matchItemID1 withObject: [ [NSString alloc] initWithFormat:@"%.1f", computedNewMoment]];
            
            computedNewMomentLat = stationWeight2 * stationArmLat1;
            
            [_arrayName6 replaceObjectAtIndex:matchItemID1 withObject: [ [NSString alloc] initWithFormat:@"%.1f", computedNewMomentLat]];
            
            
            // update name label 1200
            
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200 + matchItemID1];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200 + matchItemID1];
            }
            
            [valueField  setText: stationName2  ];
            
            valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1000 + matchItemID1];
            if (valueField == nil) {
                valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1000 + matchItemID1];
            }
            
            [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", stationWeight2]  ];
            
            // update slider
            
            slider = (UISlider*)[_viewStationsSlider viewWithTag:  matchItemID1 ];
            if (!slider) {
                slider = (UISlider*)[_viewStationsSliderRight viewWithTag:  matchItemID1 ];
            }
            
            slider.value = stationWeight2;
            
            
            
            
            [self MainRoutine];
            
            
        }
        
        
        
    }
    
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
    
    
    
    
    
}



- (IBAction)actionLoadDispatchFlights:(id)sender {
    
    [self loadDispatcherFlightsFromServer];
}


- (void) loadDispatcherFlightsFromServer {
    
    //NSLog(@"loadDispatcherFlightsFromServer");
    
    //[self loadHelicoptersFromServerVoid];
    
    //send a request to server to get all locations of this customer
    
    NSString *url=serverpath;
    url = [url stringByAppendingString:@"get_dispatcherFlights.php?customer="];
    url = [url stringByAppendingString:customer];
    
    //NSLog(@"url %@",url);
    
    
    NSData* data = [NSData dataWithContentsOfURL:
                    [NSURL URLWithString: url]];
    __autoreleasing NSError* error = nil;
    
    
    //check if JSON data is valid
    
    if (error != nil || data == NULL) {
        
        //NSLog(@"%@",error);
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Error [2]"
                              message:@"Received data that is not valid or device is offline. Please check if this device is online."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        
    } else {
        
        id  result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        
        
        [dispatcherFlights removeAllObjects];
        
        NSArray *allItems = [result objectForKey:@"dispatcherData"];
        
        
        //put locations into global locations object array
        
        for (int i=0; i<allItems.count; ++i) {
            
            NSDictionary *item = [allItems objectAtIndex:i];
            NSString *TheFlightCode=[item objectForKey:@"flightCode"];
            NSString *TheFlightName=[item objectForKey:@"flightName"];
            
            //NSLog(@"flightName: %@",TheFlightName);
            //NSLog(@"flightStatus: %@",TheFlightStatus);
            
             [dispatcherFlights addObject:[[dispatcherFlight alloc] initWithFlightCode:TheFlightCode AndFlightName:TheFlightName]];
            
        }
        
        //create button for each location
        
        [self addDispatcherFlightButtons];
        
        
    }
    
    
}

- (void) addDispatcherFlightButtons {
    
    _buttonImportFlightData.enabled = NO;
    
    
    //we create one button per location dynamically in our scrollview
    
    int xCoord=0;
    int yCoord=0;
    int buttonWidth= _viewDispatcher_sview.frame.size.width;
    int buttonHeight=50;
    int buffer = 10;
    
    
    //we take the locations that are already in our locations array
    
    for(UIView *subview in [_viewDispatcher_sview subviews]) {
        [subview removeFromSuperview];
    }
    
    
    
    for(int i=0; i<dispatcherFlights.count; i++) {
                
        
        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        aButton.showsTouchWhenHighlighted = YES;
        aButton.frame     = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
        [aButton setTitle:[[dispatcherFlights objectAtIndex:i]flightName] forState:(UIControlStateNormal)];
        [aButton setTag:i+1];
        [aButton addTarget:self action:@selector(loadDispatchFlightDataFromServer:) forControlEvents:UIControlEventTouchUpInside];
        [_viewDispatcher_sview addSubview:aButton];
        
        aButton.tintColor = [UIColor blackColor];
        
        aButton.backgroundColor = [UIColor grayColor];
        
        aButton.titleLabel.font = [UIFont systemFontOfSize:14];
        
        
        
        
        yCoord += buttonHeight + buffer;
        
    }
    
    
    [_viewDispatcher_sview setContentSize:CGSizeMake(200, yCoord)];
    [_viewDispatcher_sview setScrollEnabled:YES];
    [_viewDispatcher_sview setNeedsDisplay];
    
}

- (void) loadDispatchFlightDataFromServer:(UIButton*)sender {
    
    //Check if server reachable
    
    //NSLog(@"sender.tag %d", sender.tag);
    
    for(int i=1; i<_viewDispatcher_sview.subviews.count+1; i++) {
        
        UIButton*btn  = (UIButton*)[_viewDispatcher_sview viewWithTag: i];
        
        btn.backgroundColor = [UIColor grayColor];
    }
    
    
    UIButton*btn  = (UIButton*)[_viewDispatcher_sview viewWithTag: sender.tag];
    
    btn.backgroundColor = [UIColor yellowColor];
    
    

    
    if (!([self is_online])) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Error"
                              message:@"Cannot reach server. Please check if this device is online."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        
    } else {
        
        
        //[self setDispatchLabelsToZero];
        
        // get location from button clicked
        
        NSString *flightName=@"";
        NSString *flightCode=@"";
        
        flightCode=[[dispatcherFlights objectAtIndex:sender.tag-1]flightCode];
        flightName=[[dispatcherFlights objectAtIndex:sender.tag-1]flightName];
        
        
        //NSLog(@" --------- loading  _labelFlightRefNumber = TheFlightName %@", flightName);
        //NSLog(@" --------- loading   = flightCode %@", flightCode);
        
        
        
        crew_lastFlight=flightCode;
        
        // send request to server
        
        NSString *url=serverpath;
        url = [url stringByAppendingString:@"get_dispatcherFlightData.php?customer="];
        url = [url stringByAppendingString:customer];
        url = [url stringByAppendingString:@"&flightCode="];
        url = [url stringByAppendingString:flightCode];
        
        
        
        
        
        NSData* data = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString: url]];
        __autoreleasing NSError* error = nil;
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        
        
        //NSLog(@"id result %@",result);
        
        //check if JSON data valid
        
        if (error != nil) {
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Error"
                                  message:@"No flight available/invalid data. Please make sure that a flight is entered in Fleet Control."
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            //NSLog(@"%@",error);
        } else {
            
            
            _buttonImportFlightData.enabled = YES;
            
            NSArray *allItems = [result objectForKey:@"dispatcherFlightData"];
            
            
            //NSLog(@"allItems  %@", allItems );
            
            
            int i=0;
            NSDictionary *item = [allItems objectAtIndex:i];
            
            //_legItem1.text=[item objectForKey:@"flightcustomer"];
            //_legItem2.text=[item objectForKey:@"flightdate"];
            
            //NSLog(@"flightcustomer  %@",[item objectForKey:@"flightcustomer"] );
            //NSLog(@"flightdate  %@",[item objectForKey:@"flightdate"] );
            //NSLog(@"contactperson  %@",[item objectForKey:@"contactperson"] );
            
            
            
            // get passengers
            
            NSString *allPassengersString = @"";
            
            NSArray *allPassengers = [item objectForKey:@"passengers"];
            
            [dispatcherPaxNames removeAllObjects];
            [dispatcherPaxWeight removeAllObjects];
            
            
            [dispatcherCrewNames removeAllObjects];
            [dispatcherCrewWeight removeAllObjects];
            
            [dispatcherCrewNames  addObject:[item objectForKey:@"pilot"] ];
            [dispatcherCrewWeight  addObject:[item objectForKey:@"pilotweight"] ];
            
            allPassengersString = [allPassengersString stringByAppendingString: @"Configuration: "  ];
            allPassengersString = [allPassengersString stringByAppendingString: @"\n"  ];
            allPassengersString = [allPassengersString stringByAppendingString: [item objectForKey:@"flightcustomer"]  ];
            allPassengersString = [allPassengersString stringByAppendingString: @"\n"  ];
            allPassengersString = [allPassengersString stringByAppendingString: @"\n"  ];
            allPassengersString = [allPassengersString stringByAppendingString: @"Pilot: "  ];
            allPassengersString = [allPassengersString stringByAppendingString: @"\n"  ];
            allPassengersString = [allPassengersString stringByAppendingString: [item objectForKey:@"pilot"]  ];
            allPassengersString = [allPassengersString stringByAppendingString: @", "  ];
            allPassengersString = [allPassengersString stringByAppendingString: [item objectForKey:@"pilotweight"]  ];
            allPassengersString = [allPassengersString stringByAppendingString: @"kg" ];
            allPassengersString = [allPassengersString stringByAppendingString: @"\n"  ];
            allPassengersString = [allPassengersString stringByAppendingString: @"\n"  ];
            allPassengersString = [allPassengersString stringByAppendingString: @"Passengers: "  ];
            allPassengersString = [allPassengersString stringByAppendingString: @"\n"  ];
            
            
            NSString *ref =[item objectForKey:@"ref"];
            //NSLog(@"ref  %@", ref );
            
            _vFlightIDName.text = ref;
            
         
            
            // get departure
            NSString *departure =[item objectForKey:@"location"];
            //NSLog(@"departure  %@", departure );
            
            vFlightDeparture.text = departure;
            
            // get route
            NSString *itin =[item objectForKey:@"itinerary"];
            vFlightDestination.text = itin;
            //NSLog(@"itin  %@", itin );
            
            
            // date
                        NSString *TOtime =[item objectForKey:@"pickuptime"];
            //NSLog(@"TOtime  %@", TOtime );
            
            NSString *TOdate=[item objectForKey:@"flightdate"];
            //NSLog(@"TOdate  %@", TOdate );
            
            if (TOdate.length > 1) {
                NSString *year = [TOdate substringWithRange:NSMakeRange(0, 4)];
                //NSLog(@"year  %@", year );
                
                NSString *month = [TOdate substringWithRange:NSMakeRange(5, 2)];
                //NSLog(@"month  %@", month );
                NSString *day = [TOdate substringWithRange:NSMakeRange(8, 2)];
                //NSLog(@"day  %@", day );
                NSString *dateNew =  [[NSString alloc] initWithFormat:@"%@-%@-%@", month, day, year];
                _labelDepartureTimeLocal.text = [[NSString alloc] initWithFormat:@"%@  %@", dateNew, TOtime];
            }
            
            // get pax names
            
            for(int i=0; i<allPassengers.count; i++) {
                
                NSDictionary *item = [allPassengers objectAtIndex:i];
                allPassengersString = [allPassengersString stringByAppendingString: [item objectForKey:@"passengerName"]  ];
                
                
                if ([[item objectForKey:@"passengerWeight"] length] > 1) {
                    allPassengersString = [allPassengersString stringByAppendingString: @", "  ];
                    allPassengersString = [allPassengersString stringByAppendingString: [item objectForKey:@"passengerWeight"]  ];
                    allPassengersString = [allPassengersString stringByAppendingString: @"kg" ];

                }
                
                               allPassengersString = [allPassengersString stringByAppendingString: @"\n"  ];
                [dispatcherPaxNames  addObject:[item objectForKey:@"passengerName"] ];
                [dispatcherPaxWeight addObject:[item objectForKey:@"passengerWeight"] ];
                
            }
            
            _passengerList.text = allPassengersString;
            
            
            
        }
    }
}


- (IBAction)actionPositionCrewAndPaxFromDispatch:(id)sender {
    
    [self positionCrewFromDispatch];
    
    [self positionPaxFromDispatch];
    
    displayWindow = 0;
    
    [self displayWindows];
    
    
    
}

- (IBAction)actionShowHideDispatch:(id)sender {
    
    guidanceDictionary[@"guidanceBtnCrew"] =  @"ok";
    guidanceDictionary[@"guidanceBtnDispatch"] =  @"ok";

    

    
    if (_viewDispatch.hidden == YES) {
        _viewDispatch.hidden = NO;
        
        [viewOne bringSubviewToFront:_viewDispatch];
        
        
        [self loadDispatcherFlightsFromServer];
        
       
        
    }else{
        
        _viewDispatch.hidden = YES;
        
        
    }
    
    
    [self MainRoutine];
    
}



- (void) positionCrewFromDispatch {
    
    
    //NSLog(@"dispatcherCrewNames2 %@", dispatcherCrewNames);
    
    int paxNumberinArray;
    
    
    for(int i=0; i<dispatcherCrewNames.count; i++) {
        
        paxNumberinArray = linePilot + i;
        
        //NSLog(@"[_arrayName2 objectAtIndex:paxNumberinArray] i = %d %@ ",paxNumberinArray,  [_arrayName2 objectAtIndex:paxNumberinArray]);
        
        
        [_arrayName7 replaceObjectAtIndex:paxNumberinArray withObject: [dispatcherCrewNames objectAtIndex:i] ];
        
        //NSLog(@"replacing  [_arrayName2 %@ with %@",[_arrayName2 objectAtIndex:paxNumberinArray] ,[dispatcherCrewPaxWeight objectAtIndex:i] );
        
        [_arrayName2 replaceObjectAtIndex:paxNumberinArray withObject: [dispatcherCrewWeight objectAtIndex:i]  ];
        
        float computedNewMoment = [[dispatcherCrewWeight objectAtIndex:i] floatValue] * [[_arrayName3 objectAtIndex:paxNumberinArray] floatValue];
        
        [_arrayName4 replaceObjectAtIndex:paxNumberinArray withObject: [ [NSString alloc] initWithFormat:@"%.1f", computedNewMoment]];
        
        float computedNewMomentLat = [[dispatcherCrewWeight objectAtIndex:i] floatValue] * [[_arrayName5 objectAtIndex:paxNumberinArray] floatValue];
        
        [_arrayName6 replaceObjectAtIndex:paxNumberinArray withObject: [ [NSString alloc] initWithFormat:@"%.1f", computedNewMomentLat]];
        
        
        // update name label 1200
        
        valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200 + paxNumberinArray];
        if (valueField == nil) {
           valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200 + paxNumberinArray];
        }
        
        [valueField  setText: [dispatcherCrewNames objectAtIndex:i]   ];
        
        valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1000 + paxNumberinArray];
        if (valueField == nil) {
            valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1000 + paxNumberinArray];
        }
        
        [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [[dispatcherCrewWeight objectAtIndex:i] floatValue]]   ];
        
        // update slider
        
        UISlider *slider = (UISlider*)[_viewStationsSlider viewWithTag:  paxNumberinArray ];
        if (!slider) {
            slider = (UISlider*)[_viewStationsSliderRight viewWithTag:  paxNumberinArray ];
        }
        
        slider.value = [[dispatcherCrewWeight objectAtIndex:i] floatValue] ;
        
        
       
        
    }
    
}





- (void) positionPaxFromDispatch {
 
    
    //NSLog(@"dispatcherPaxNames2 %@", dispatcherPaxNames);

    
    if ([[dispatcherPaxNames objectAtIndex:0] integerValue] > 0) {
        
        // do this if you want to load a specific number of pax entered in Fleet Control
        
        _inputPaxOnBoard.text = [[NSString alloc] initWithFormat:@"%.d", [[dispatcherPaxNames objectAtIndex:0] integerValue]];
        
        //NSLog(@"[[dispatcherPaxNames objectAtIndex:0] integerValue]  %d ", [[dispatcherPaxNames objectAtIndex:0] integerValue]);
        
        
        [self setPaxOnBoard];
        
        [self MainRoutine];
        
        
    }else{
        
        _inputPaxOnBoard.text = [[NSString alloc] initWithFormat:@"%.d", dispatcherPaxNames.count];
        
        int configStationsStart = 0;
        configStationsStart = [[_arrayName23 objectAtIndex:11] intValue];
            
        int desiredSeats = dispatcherPaxNames.count;
        int allocatedSeats = 0;
        
        //NSLog(@"desiredSeats %d", desiredSeats);
        
        int i = configStationsStart;
        
        do {
            
            //NSLog(@"i %d", i);
            
            if (i > desiredSeats + configStationsStart ) {
                
                //NSLog(@"i break %d", i);
                break;
            }

            
            // if seat is ON then allocate a person
            if ( [[_arrayName8 objectAtIndex:i] floatValue] == 1) {
                
                // check if there are still persons to allocate
                if (allocatedSeats < desiredSeats) {
                    
                    [_arrayName7 replaceObjectAtIndex:i withObject: [dispatcherPaxNames objectAtIndex:allocatedSeats] ];
                    [_arrayName2 replaceObjectAtIndex:i withObject: [dispatcherPaxWeight objectAtIndex:allocatedSeats]  ];
                    
                    float computedNewMoment = [[dispatcherPaxWeight objectAtIndex:allocatedSeats] floatValue] * [[_arrayName3 objectAtIndex:i] floatValue];
                    
                    [_arrayName4 replaceObjectAtIndex:i withObject: [ [NSString alloc] initWithFormat:@"%.1f", computedNewMoment]];
                    
                    float computedNewMomentLat = [[dispatcherPaxWeight objectAtIndex:allocatedSeats] floatValue] * [[_arrayName5 objectAtIndex:i] floatValue];
                    
                    [_arrayName6 replaceObjectAtIndex:i withObject: [ [NSString alloc] initWithFormat:@"%.1f", computedNewMomentLat]];
                    
                    
                    // update name label 1200
                    
                    valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1200 + i];
                    if (valueField == nil) {
                       valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1200 + i];
                    }
                    [valueField  setText: [dispatcherPaxNames objectAtIndex:allocatedSeats]   ];
                    
                    valueField = (UITextField*)[_viewStationsSlider viewWithTag: 1000 + i];
                    if (valueField == nil) {
                        valueField = (UITextField*)[_viewStationsSliderRight viewWithTag: 1000 + i];
                    }
                    
                    [valueField  setText: [ [NSString alloc] initWithFormat:@"%.0f", [[dispatcherPaxWeight objectAtIndex:allocatedSeats] floatValue]]   ];
                    
                    // update slider
                    
                    UISlider *slider = (UISlider*)[_viewStationsSlider viewWithTag:  i ];
                    if (!slider) {
                        slider = (UISlider*)[_viewStationsSliderRight viewWithTag:  i ];
                    }
                    
                    slider.value = [[dispatcherPaxWeight objectAtIndex:allocatedSeats] floatValue] ;
                    
                    
                    allocatedSeats = allocatedSeats + 1;
                    
                }
                
                
            }
            
            
            i = i +1;
            
        
            
                
            
            
            
            //NSLog(@"allocatedSeats %d", allocatedSeats);

           
        }while( allocatedSeats < desiredSeats );
        
        
        
        
        
        
        
        
        
    }
    
    
    
}




- (IBAction)actionResetApp:(id)sender {
    

    
    alertFlag = 666;
    
    
    UIAlertView *alert = [[UIAlertView alloc]
                          
                          initWithTitle:@"App Reset"
                          
                          message:@"This will reset the app. All settings and flights will be deleted. Initial data will be loaded. \n\nREQUIRES INTERNET CONNECTION!!!"
                          
                          delegate:self
                          
                          cancelButtonTitle:@"CANCEL"
                          
                          
                          
                          otherButtonTitles:@"RESET!", nil];
    
    [alert show];
    
    
    
  
}






// flight manager

- (void) createFlightButtons {
    
    _scrollViewTopDisplayButton.hidden = YES;
    //_viewLegButtons.hidden = YES;    
    //NSLog(@"createFlightButtons ");    
    // how many flights do we have?    
    //int numberOfFlights = allFlightsDictionary.count;
    //NSLog(@"numberOfFlights %d ", numberOfFlights);
    //NSLog(@"numberOfLegs Flight 1 %d ", [[allFlightsDictionary objectForKey: @"1"] count] -1  );
    //NSLog(@"numberOfLegs Flight 2 %d ", [[allFlightsDictionary objectForKey: @"2"] count] -1 );    
    //NSLog(@"createFlightButtons arrayFlights %@", arrayFlights);
    //we create one button per location dynamically in our scrollview
    
    
    if (flagIsLandscape == 1) {
        _scrollViewFlightButtons.frame = CGRectMake(0, 211, 1024, 539);
    }else{
         _scrollViewFlightButtons.frame = CGRectMake(0, 211, 768, 539);
    }
    
    int xCoord=0;
    int yCoord=2;
    int buttonWidth= _scrollViewFlightButtons.frame.size.width;
    int buttonHeight=80;
    int buffer = 30;
        
    for(UIView *subview in [_scrollViewFlightButtons subviews]) {
        [subview removeFromSuperview];
    }
    
    
    int currentFlightID = [vFlightID intValue];
    flagLockReset = 0;    
    for (int i = allFlightsMasterArray.count-1; i >= 1; i--) {
        //for (int i = 1; i <allFlightsMasterArray.count; i++) {        
        int legsForThisFlight = [[allFlightsMasterArray objectAtIndex:i] count] -1  ;        
        int allLegsForThisFLightOK = 1;        
        for (int a = 0; a <legsForThisFlight; a++) {            
            int guidanceCheckValue = [[[[allFlightsMasterArray objectAtIndex: i] objectAtIndex: a+1 ] objectForKey:@"guidanceLegCheckOK"] floatValue]; // trick to get values from within            
            if (guidanceCheckValue != 1) {
                allLegsForThisFLightOK = 0;
            }
        }
        
        UIView *flightBox =[[UIView alloc] initWithFrame:CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight) ];        
        flightBox.backgroundColor = verydarkGrayColor;        
        [_scrollViewFlightButtons addSubview:flightBox];
                
        // flight number
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xCoord, yCoord,70,buttonHeight )];
        label.font = [UIFont boldSystemFontOfSize:16.0];
        label.textAlignment = NSTextAlignmentCenter;
      
        label.text = [ [NSString alloc] initWithFormat:@"%d",i   ];
        
        if (currentFlightID == i ) {
            label.textColor = [UIColor whiteColor];
            label.backgroundColor = blueButtonColor;
             }else{
            label.textColor = [UIColor blackColor];
            label.backgroundColor = [UIColor darkGrayColor];
        }
        label.alpha = 0.9;
        [_scrollViewFlightButtons addSubview:label];        
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(xCoord + 90, yCoord + 4,440,30 )];
        label.font = [UIFont boldSystemFontOfSize:16.0];
        if (currentFlightID == i ) {
            label.textColor = [UIColor whiteColor];
        }else{
            label.textColor = [UIColor lightGrayColor];
        }
        label.textAlignment = NSTextAlignmentLeft;
        label.text = [ [NSString alloc] initWithFormat:@"Flight ID: %@  --> %@, %@", [[[allFlightsMasterArray objectAtIndex: i] objectAtIndex: 1 ] objectForKey:@"_vFlightIDName"], [[[allFlightsMasterArray objectAtIndex: i] objectAtIndex: 1 ] objectForKey:@"vFlightRegistration"] , [[[allFlightsMasterArray objectAtIndex: i] objectAtIndex: 1 ] objectForKey:@"_legAC_Type"]]; // get from within legs
        label.backgroundColor = [UIColor clearColor];
        label.alpha = 0.9;
        [_scrollViewFlightButtons addSubview:label];        
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(xCoord + 90, yCoord + 27,640,30 )];
        label.font = [UIFont boldSystemFontOfSize:16.0];
        if (currentFlightID == i ) {
            label.textColor = [UIColor whiteColor];
        }else{
            label.textColor = [UIColor lightGrayColor];
        }
        label.textAlignment = NSTextAlignmentLeft;
        label.text = [ [NSString alloc] initWithFormat:@"Date: %@", [[[allFlightsMasterArray objectAtIndex: i] objectAtIndex: 1 ] objectForKey:@"_labelDepartureTimeLocal"] ]; // get from within legs
        label.backgroundColor = [UIColor clearColor];
        label.alpha = 0.9;       
        
        NSString *trialCheckLoaded = [[[allFlightsMasterArray objectAtIndex: i] objectAtIndex: 1 ] objectForKey:@"trialCheck"];        
        if ([trialCheckLoaded isEqualToString:@"isATrial"]) {
            label.text = @"Trial Aircraft - NOT FOR FLIGHT PLANNING!";
            label.textColor = [UIColor yellowColor];
        }        
        //NSLog(@"trialCheck %@", trialCheck);        
        [_scrollViewFlightButtons addSubview:label];
        
       if (_segmentFlightLegMode.selectedSegmentIndex == 1) {           
           label = [[UILabel alloc] initWithFrame:CGRectMake(xCoord + 90, yCoord + 50,240,30 )];
           label.font = [UIFont boldSystemFontOfSize:16.0];
           label.textAlignment = NSTextAlignmentLeft;
           
           label.backgroundColor = [UIColor clearColor];
           label.alpha = 0.9;
           
           
           if (_switchGuidance.on == YES){
               
               if (allLegsForThisFLightOK == 1) {
                   label.textColor = GreenColor;
                   label.text = [ [NSString alloc] initWithFormat:@"Legs: %lu, completed", [[allFlightsMasterArray objectAtIndex:i] count] -1  ]; // this is how many legs we have per flight
               }else{
                   label.textColor = yellowSpecialColor;
                   label.text = [ [NSString alloc] initWithFormat:@"Legs: %lu, not completed", [[allFlightsMasterArray objectAtIndex:i] count] -1  ]; // this is how many legs we have per flight
               }               
           }else{               
               label.textColor = [UIColor lightGrayColor];
               label.text = [ [NSString alloc] initWithFormat:@"Legs: %lu", [[allFlightsMasterArray objectAtIndex:i] count] -1  ]; // this is how many legs we have per flight
           }
              
           [_scrollViewFlightButtons addSubview:label];
           
       }
        
        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        aButton.showsTouchWhenHighlighted = YES;
        aButton.frame     = CGRectMake(_scrollViewFlightButtons.frame.size.width - 220, yCoord,138,buttonHeight );
        [aButton setTitle: @"Copy Flight" forState:(UIControlStateNormal)];
        [aButton setTag:i+100];
        [aButton addTarget:self action:@selector(actionCopyFlightButton:) forControlEvents:UIControlEventTouchUpInside];
        aButton.tintColor = [UIColor blackColor];
        aButton.backgroundColor = [UIColor grayColor];
        aButton.titleLabel.font = [UIFont systemFontOfSize:15];
        aButton.alpha = 0.9;
        [_scrollViewFlightButtons addSubview:aButton];
 
        
        aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        aButton.showsTouchWhenHighlighted = YES;
        aButton.frame     = CGRectMake(_scrollViewFlightButtons.frame.size.width - 80, yCoord,80,buttonHeight );
        [aButton setTitle: @"Delete" forState:(UIControlStateNormal)];
        [aButton setTag:i+100];
        [aButton addTarget:self action:@selector(actionDeleteFlightButton:) forControlEvents:UIControlEventTouchUpInside];
        aButton.tintColor = [UIColor blackColor];
        aButton.backgroundColor = [UIColor grayColor];
        aButton.titleLabel.font = [UIFont systemFontOfSize:15];
        aButton.alpha = 0.9;
        [_scrollViewFlightButtons addSubview:aButton];
        aButton.titleLabel.font = [UIFont systemFontOfSize:15];
              
        //in backend lock reset if not sent
        if ([[_arrayName23 objectAtIndex:46] isEqualToString:@"yes"]) {
            // lock reset if mail was not sent      
            [self LoadValues];
            if (flagLoadManifestSentForThisFlight == 0) {
                flagLockReset = 1;
                //NSLog(@"flagLockReset = 1 ");
                UIImageView *mailSentSymbol;
                if (flagIsLandscape == 1) {
                    mailSentSymbol =[[UIImageView alloc] initWithFrame:CGRectMake(_scrollViewFlightButtons.frame.size.width - 500, yCoord + 20,40,40   ) ];
                }else{
                    mailSentSymbol =[[UIImageView alloc] initWithFrame:CGRectMake(_scrollViewFlightButtons.frame.size.width - 475, yCoord + 49,30,30   ) ];
                }
                
                UIImage *newImage = [UIImage imageNamed: @"emailNotSentSymbol.png" ];
                [mailSentSymbol setImage:newImage ];
                [_scrollViewFlightButtons addSubview:mailSentSymbol];                
            }else{ 
                UIImageView *mailSentSymbol;
                if (flagIsLandscape == 1) {
                   mailSentSymbol =[[UIImageView alloc] initWithFrame:CGRectMake(_scrollViewFlightButtons.frame.size.width - 500, yCoord + 20,40,40   ) ];                    
                }else{
                   mailSentSymbol =[[UIImageView alloc] initWithFrame:CGRectMake(_scrollViewFlightButtons.frame.size.width - 475, yCoord + 49,30,30   ) ];
                }
                UIImage *newImage = [UIImage imageNamed: @"emailSentSymbol.png" ];
                [mailSentSymbol setImage:newImage ];
                [_scrollViewFlightButtons addSubview:mailSentSymbol];
            }            
            [_scrollViewFlightButtons addSubview:aButton];
        }else{            
            flagLockReset = 0;
        }
        aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        aButton.showsTouchWhenHighlighted = YES;
        aButton.frame     = CGRectMake(_scrollViewFlightButtons.frame.size.width - 440, yCoord,218,buttonHeight );        
        [aButton setTag:i+300];        
        [aButton setTitle: @"Open Flight" forState:(UIControlStateNormal)];
        
        if (i == [vFlightID integerValue]) {
            [aButton addTarget:self action:@selector(actionLoadFlightButtonWhenActive:) forControlEvents:UIControlEventTouchUpInside];
        }else{
            [aButton addTarget:self action:@selector(actionLoadFlightButton:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        aButton.tintColor = [UIColor whiteColor];
        aButton.backgroundColor = blueButtonColor;
        aButton.titleLabel.font = [UIFont systemFontOfSize:15];
        //aButton.alpha = 0.9;
        [_scrollViewFlightButtons addSubview:aButton];
                
        if (currentFlightID == i ) {            
            UIView *activeFrame =[[UIView alloc] initWithFrame:CGRectMake(xCoord, yCoord - 2,buttonWidth,buttonHeight+4) ];
            activeFrame.backgroundColor = [UIColor whiteColor];
            [_scrollViewFlightButtons addSubview:activeFrame];
            [_scrollViewFlightButtons sendSubviewToBack:activeFrame];
            
        }
        // continue
        yCoord += buttonHeight + buffer;
        
    }
    [_scrollViewFlightButtons setContentSize:CGSizeMake(200, yCoord)];
    [_scrollViewFlightButtons setScrollEnabled:YES];
    [_scrollViewFlightButtons setNeedsDisplay];
    
}


- (IBAction)actionLoadFlightButtonWhenActive:(id)sender{
    
    
    
    
    displayWindow = 0;
    [self displayWindows];
    
    [self MainRoutine];
    
   
}


- (IBAction)actionLoadFlightButton:(id)sender{
    
    
    [self SaveValues];
    
    UIButton *btn = (UIButton*)sender;
    //NSLog(@"actionLoadFlightButton btn.tag %d ", btn.tag-300);
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    //NSLog(@"loading flight  %d ", btn.tag-300);
    
    [defaults  setObject: [ [NSString alloc] initWithFormat:@"%d", btn.tag-300 ]   forKey:@"vFlightID"];
    
    vLegID = @"1";
    
    [self LoadValues];
    
    [self createFlightButtons];
    
    displayWindow = 0;
    [self displayWindows];
    
    [self MainRoutine];
    
    
}




- (IBAction)actionCopyFlightButton :(id)sender {
    
    // this works
    //NSLog(@"actionCopyFlightButton");
    flagCopyFlight = 1;
    [calculatePerformanceClass_ loadFixedWingSliders];
    [self SaveValues];
    UIButton *btn = (UIButton*)sender;
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    vFlightID = [ [NSString alloc] initWithFormat:@"%lu", btn.tag-100 ];
    [defaults  setObject: vFlightID   forKey:@"vFlightID"];
    
    [self LoadValues];
    
    NSMutableArray *tempArrayCustomStations = [[NSMutableArray alloc] init]; 
    NSString *internalFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];    
    tempArrayCustomStations = [[[NSUserDefaults standardUserDefaults] objectForKey:[[NSString alloc] initWithFormat:@"%@%@", internalFlightID, @"arrayCustomStations" ]] mutableCopy];    
    //NSLog(@"loaded tempArrayCustomStations %@ ", tempArrayCustomStations);
    
    //NSLog(@"new vFlightID %@ ", vFlightID);
    //NSLog(@"new vFlightID %@ ", internalFlightID);
    
    triggerSetDefaultsForPerformanceCharts = 0;
    triggerCopySliderSettingsWithFlightID = @"";
    triggerCopySliderSettingsWithFlightID = internalFlightID;
    //NSLog(@"setting triggerCopySliderSettingsWithFlightID %@", triggerCopySliderSettingsWithFlightID);
    
    
    vFlightID =  [ [NSString alloc] initWithFormat:@"%lu", (unsigned long)allFlightsMasterArray.count];
    [defaults  setObject: vFlightID   forKey:@"vFlightID"];
    vLegID = @"1";
    [allFlightsMasterArray addObject:@"-"];
    [self addInternalFlightNumber];

    internalFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"]; 
    [[NSUserDefaults standardUserDefaults]  setObject: tempArrayCustomStations  forKey:[ [NSString alloc] initWithFormat:@"%@%@", internalFlightID, @"arrayCustomStations" ]];
    
    
    //NSLog(@"!saving vFlightID %@ ", vFlightID);
    
    [self SaveValues]; // unter neuem Namen alles speichern
    
    // ********************
    
    if (_switchGuidance.on == YES) {
        
        int numberOfLegsThisFlight = [[flightSettingsDictionary  objectForKey:@"numberOfLegsThisFlight"] floatValue];
        for(int i=1; i<numberOfLegsThisFlight+1; i++) {
            //NSLog(@"legs i %d",  i);
            vLegID = [NSString stringWithFormat:@"%d",  i  ];
            NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
            [defaults  setObject:vLegID                     forKey:@"vLegID"];
            
            [self LoadValues];
            [self MainRoutine];
            //NSLog(@"_vHOMSA %@",  _vHOMSA.text);
            [self guidanceResetLegDataAll];
            [self MainRoutine];
            flagLoadManifestSentForThisFlight = 0;
            [self SaveValues];
        }
        
        
    }
    
    
    vLegID = [NSString stringWithFormat:@"%d",  1  ];
    [defaults  setObject:vLegID                     forKey:@"vLegID"];
    
    [self LoadValues];
    
     [calculatePerformanceClass_ saveFixedWingSliders];
    
    loadedSignatureImage = nil;
    [scrollSig removeFromSuperview];
    signatureImageData = nil;
    
    //[self createFlightButtons];
    [self MainRoutine];
    
    //[self createFlightButtons];
    
    
    displayWindow = 0 ;
    [self displayWindows];
    
     [self SaveValues];
    flagCopyFlight = 0;
    
}

- (IBAction)actionCopyCurrentFlight:(id)sender {
    
    
    // this works
    //NSLog(@"actionCopyFlightButton");
    flagCopyFlight = 1;
    [calculatePerformanceClass_ loadFixedWingSliders];
    [self SaveValues];
    [self LoadValues];
    
    
    NSMutableArray *tempArrayCustomStations = [[NSMutableArray alloc] init]; 
    NSString *internalFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];    
    tempArrayCustomStations = [[[NSUserDefaults standardUserDefaults] objectForKey:[[NSString alloc] initWithFormat:@"%@%@", internalFlightID, @"arrayCustomStations" ]] mutableCopy];    
    
    triggerSetDefaultsForPerformanceCharts = 0;
    triggerCopySliderSettingsWithFlightID = @"";
    triggerCopySliderSettingsWithFlightID = internalFlightID;
    //NSLog(@"setting triggerCopySliderSettingsWithFlightID %@", triggerCopySliderSettingsWithFlightID);
    
    
    vFlightID =  [ [NSString alloc] initWithFormat:@"%lu", (unsigned long)allFlightsMasterArray.count];
    [[NSUserDefaults standardUserDefaults]  setObject: vFlightID   forKey:@"vFlightID"];
    vLegID = @"1";
    [allFlightsMasterArray addObject:@"-"];
    [self addInternalFlightNumber];
    
    internalFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"]; 
    [[NSUserDefaults standardUserDefaults]  setObject: tempArrayCustomStations  forKey:[ [NSString alloc] initWithFormat:@"%@%@", internalFlightID, @"arrayCustomStations" ]];
    
    [self SaveValues]; // unter neuem Namen alles speichern
   
    // ********************
    
    if (_switchGuidance.on == YES) {        
        int numberOfLegsThisFlight = [[flightSettingsDictionary  objectForKey:@"numberOfLegsThisFlight"] floatValue];
        for(int i=1; i<numberOfLegsThisFlight+1; i++) {
            //NSLog(@"legs i %d",  i);
            vLegID = [NSString stringWithFormat:@"%d",  i  ];
            NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
            [defaults  setObject:vLegID                     forKey:@"vLegID"];
            
            [self LoadValues];
            [self MainRoutine];
            //NSLog(@"_vHOMSA %@",  _vHOMSA.text);
            [self guidanceResetLegDataAll];
            [self MainRoutine];
            flagLoadManifestSentForThisFlight = 0;
            [self SaveValues];
        }
        
        
    }
    
    vLegID = [NSString stringWithFormat:@"%d",  1  ];
    [[NSUserDefaults standardUserDefaults]   setObject:vLegID                     forKey:@"vLegID"];
    

    [self LoadValues];
    
    //set new time
    
    [self setDatePickToNow];
    flagSetPickerTimeForFields = 1;
    [self setDateFromPicker];
    
    loadedSignatureImage = nil;
    [scrollSig removeFromSuperview];
    signatureImageData = nil;
    
    [calculatePerformanceClass_ saveFixedWingSliders];
    
 
    [self MainRoutine];
 
    displayWindow = 0 ;
    [self displayWindows];
  
     [self SaveValues];
   
    
    flagCopyFlight = 0;
}







- (IBAction)actionDeleteFlightButton:(id)sender{
    
    UIButton *btn = (UIButton*)sender;
    
    buttonIDtransfer = btn.tag;
    
    
    
    if (flagLockReset == 1) {
        
        alertFlag = 1003;
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Flight Data not sent!"
                              message:@"This flight was not sent via email yet. Please make sure you have sent data befor you delete the flight! "
                              delegate:self
                              cancelButtonTitle:@"Cancel"
                              otherButtonTitles:@"Delete", nil];
        [alert show];
        
    }else{        
        alertFlag = 1003;
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Delete Flight"
                              message:@"Please Confirm"
                              delegate:self
                              cancelButtonTitle:@"Cancel"
                              otherButtonTitles:@"Delete", nil];
        [alert show];
    }
    
    /*

    
    if (flagSpecialPHIFlightSettingPage == 1) {       
        float legsForThisFlight = [[allFlightsMasterArray objectAtIndex:buttonIDtransfer-100] count] -1  ; 
        int allLegsForThisFLightOK = 1;        
        for (int a = 0; a <legsForThisFlight; a++) {            
            int guidanceCheckValue = [[[[allFlightsMasterArray objectAtIndex: buttonIDtransfer-100] objectAtIndex: a+1 ] objectForKey:@"guidanceLegCheckOK"] floatValue]; 
            if (guidanceCheckValue != 1) {
                allLegsForThisFLightOK = 0;
            }
        }
        
        
        if (allLegsForThisFLightOK == 1) {
            alertFlag = 1003;
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Delete Flight"
                                  message:@"Please Confirm"
                                  delegate:self
                                  cancelButtonTitle:@"Cancel"
                                  otherButtonTitles:@"Delete", nil];
            [alert show];
        }else{
            alertFlag = 1003;
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Flight Data not sent!"
                                  message:@"This flight was not uploaded. Please open the 'Flight Summary' page and upload data for this flight."
                                  delegate:self
                                  cancelButtonTitle:@"Cancel"
                                  otherButtonTitles:@"Delete", nil];
            [alert show];
            
        }
     
        
    }else{
        
        
        
        
    }
    
   */
    
   

    
    
    
   
}




- (void) deleteAllFlightsWithoutFleetData {
    
    //NSLog(@"deleteAllFlightsWithoutFleetData "  );
    
    
    [self SaveValues];      
    for(int a=1; a<allFlightsMasterArray.count; a++) {        
        //NSLog(@"a %d", a  );        
        NSString *ACtypeInQuestion = [[[allFlightsMasterArray objectAtIndex: a] objectAtIndex: 1 ] objectForKey:@"_legAC_Type"]; 
         //NSLog(@"ACtypeInQuestions %@", ACtypeInQuestion  );
        if (![arrayMyFleetACTypes containsObject: ACtypeInQuestion]) {
            //NSLog(@"need to delete this %@", ACtypeInQuestion  );
            [allFlightsMasterArray removeObjectAtIndex: a ];            
            //NSLog(@"allFlightsMasterArray.count %d", allFlightsMasterArray.count );
            a--;
            continue;
        }        
    }    
    // look for new flight
    if ( [vFlightID intValue] >= (allFlightsMasterArray.count-1)  ) {
        vFlightID =  [ [NSString alloc] initWithFormat:@"%lu", allFlightsMasterArray.count-1];
    }    
    if ( [vFlightID intValue] == 0  ) {        
        flagMakeNewFlgtNow = 1;
        _viewSelectHelicopter.hidden = NO; [viewOne bringSubviewToFront:_viewSelectHelicopter];        
    }else{        
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        [defaults  setObject: allFlightsMasterArray  forKey:@"allFlightsMasterArray"];
      
        [defaults  setObject: vFlightID                                     forKey:@"vFlightID"];
        
        vLegID = @"1";
        [self LoadValues];
        [self createFlightButtons];
        [self MainRoutine];
    }
 
}


- (void) deleteFlightFromManager {
    
    [self SaveValues];    
    //NSLog(@"actionDeleteFlightButton btn.tag %d ", btn.tag-100);    
    [allFlightsMasterArray removeObjectAtIndex: buttonIDtransfer -100 ]; 
    // look for new flight    
    if ( [vFlightID intValue] >= (allFlightsMasterArray.count-1)  ) {
        vFlightID =  [ [NSString alloc] initWithFormat:@"%lu", allFlightsMasterArray.count-1];
    }    
    if ( [vFlightID intValue] == 0  ) { 
        NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];    
        if ([customerFolderName isEqualToString:@"noAccount"] ) {         
            _viewSelectHelicopter.hidden = NO; [viewOne bringSubviewToFront:_viewSelectHelicopter];
            _viewFleetManager.hidden = NO;
            [viewOne bringSubviewToFront:_viewFleetManager];        
            NSNotification *myNotification = [NSNotification notificationWithName:@"notificationViewAircraftManager"
                                                                           object:self //object is usually the object posting the notification
                                                                         userInfo:nil]; //userInfo is an optional dictionary        
            //Post it to the default notification center
            [[NSNotificationCenter defaultCenter] postNotification:myNotification];   
            
        }else{
            
            flagMakeNewFlgtNow = 1;
            _viewSelectHelicopter.hidden = NO; [viewOne bringSubviewToFront:_viewSelectHelicopter];            
            if (flagSpecialPHIFlightSettingPage == 1) {
                _buttonCreateNewPHIFlight.hidden = NO;
                _buttonPHIcancelCreateFlight.hidden = NO;
            }
        }
    }else{        
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        [defaults  setObject: allFlightsMasterArray  forKey:@"allFlightsMasterArray"];
    
        [defaults  setObject: vFlightID                                     forKey:@"vFlightID"];        
        vLegID = @"1";
        [self LoadValues];
        [self createFlightButtons];
        [self MainRoutine];
    }    
}


- (IBAction)actionDeleteActiveLeg:(id)sender {
    
    
    if (allLegsPerFlightArray.count <= 2) {
        
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"One Leg Only"
                              message:@"The active flight has only one leg, therefore this leg can not be deleted. To delete the actve flight, open the Flight Manager."
                              delegate:self
                              
                              cancelButtonTitle:@"OK"
                              
                              
                              
                              otherButtonTitles: nil];
        [alert show];
        
        
    }else{
        
        alertFlag = 1001;
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Delete Active Leg"
                              message:@"Please Confirm"
                              delegate:self
                              
                              cancelButtonTitle:@"Cancel"
                              
                              
                              
                              otherButtonTitles:@"Delete", nil];
        [alert show];
        
    }
    
   

   
    
}

- (void) deleteActiveLeg {
    
    
    [self SaveValues];
    
    int numberOfLegsThisFlight = [[flightSettingsDictionary  objectForKey:@"numberOfLegsThisFlight"] floatValue];
    
    //NSLog(@"numberOfLegsThisFlight  %d ", numberOfLegsThisFlight );
    
    //NSLog(@"allLegsPerFlightArray.count   %d ", allLegsPerFlightArray.count  );
    
    if (allLegsPerFlightArray.count <= 2) {
        return;
    }
    
    [allLegsPerFlightArray removeObjectAtIndex: [vLegID integerValue] ];
    
    
    if ( [vLegID intValue] >= (allLegsPerFlightArray.count-1)  ) {
        
        vLegID =  [ [NSString alloc] initWithFormat:@"%u", allLegsPerFlightArray.count-1];
        
    }
    
    //NSLog(@"new vLegID %d", [vLegID integerValue]);
    
    flightSettingsDictionary[@"numberOfLegsThisFlight"] = [NSString stringWithFormat:@"%d", numberOfLegsThisFlight-1 ];
    
    [allFlightsMasterArray replaceObjectAtIndex:[vFlightID integerValue] withObject:allLegsPerFlightArray];
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    [defaults  setObject: allFlightsMasterArray  forKey:@"allFlightsMasterArray"];

    [defaults  setObject: vFlightID                                     forKey:@"vFlightID"];
    
    [self LoadValues];
    
    [self MainRoutine];

   
    if (flagSpecialPHIFlightSettingPage == 1) {
        _viewLegData.hidden = NO; 
        [viewOne bringSubviewToFront:_viewLegData];
    }
    
}

- (IBAction)actionAddFlight:(id)sender {
   
    _buttonCreateNewPHIFlight.hidden = NO;
    _buttonPHIcancelCreateFlight.hidden = NO;
    
    NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
    if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
    if ([userExtraCheck rangeOfString:@"flightSchoolPackage"].location != NSNotFound  ) { 
        
        _viewSelectHelicopter.hidden = NO; [viewOne bringSubviewToFront:_viewSelectHelicopter];
        _viewFleetManager.hidden = NO;
        [viewOne bringSubviewToFront:_viewFleetManager];        
        NSNotification *myNotification = [NSNotification notificationWithName:@"notificationViewAircraftManager"
                                                                       object:self //object is usually the object posting the notification
                                                                     userInfo:nil]; //userInfo is an optional dictionary        
        //Post it to the default notification center
        [[NSNotificationCenter defaultCenter] postNotification:myNotification];     
    }else{
        
        //NSLog(@"actionAddFlight");
        NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];    
        if ([customerFolderName isEqualToString:@"noAccount"] ) {  
            _viewSelectHelicopter.hidden = NO; [viewOne bringSubviewToFront:_viewSelectHelicopter];
            _viewFleetManager.hidden = NO;
            [viewOne bringSubviewToFront:_viewFleetManager];        
            NSNotification *myNotification = [NSNotification notificationWithName:@"notificationViewAircraftManager"
                                                                           object:self //object is usually the object posting the notification
                                                                         userInfo:nil]; //userInfo is an optional dictionary        
            //Post it to the default notification center
            [[NSNotificationCenter defaultCenter] postNotification:myNotification]; 
            
            
        }else{   
          
            _viewSelectHelicopter.hidden = NO; [viewOne bringSubviewToFront:_viewSelectHelicopter];
            flagMakeNewFlgtNow = 1;
               [self checkForUpdates_HelicopterSilent];
            if (flagSpecialPHIFlightSettingPage == 1) {
               
                
                //insane1
                flagMakeNewFlgtNow = 1;
                [self SaveValues];
                [self LoadValues];
                [self createNewFlight];
                flagMakeNewFlgtNow = 0;
                
                _inputPHIOverrideACtype.text = @"";
                UIImage *btnImg = [UIImage imageNamed:@"lock - locked-01.png"];
                [_buttonUnlockBEWOverride setBackgroundImage:btnImg forState:UIControlStateNormal];
                _inputPHIOverrideRegistration.enabled = NO; _inputPHIOverrideRegistration.backgroundColor = [UIColor lightGrayColor];
                _inputPHIOverrideBEW.enabled = NO; _inputPHIOverrideBEW.backgroundColor = [UIColor lightGrayColor];
                _inputPHIOverrideMoment.enabled = NO; _inputPHIOverrideMoment.backgroundColor = [UIColor lightGrayColor];
                _inputPHIOverrideFuelFlow.enabled = NO; _inputPHIOverrideFuelFlow.backgroundColor = [UIColor lightGrayColor];
                _inputPHIOverrideMomentLat.enabled = NO; _inputPHIOverrideMomentLat.backgroundColor = [UIColor lightGrayColor];
                _inputPHIOverrideSledWeight.enabled = NO; _inputPHIOverrideSledWeight.backgroundColor = [UIColor lightGrayColor];
                _buttonPHIchangeBackToOriginalFormC.hidden = YES;
                 [self checkOverrideInputs];
                [self MainRoutine];
                
            }
        }
    }
        
   
    
}



- (void)createNewFlight {
    
    // here we just create a new flight number, we do not know the new aircraft yet
    
    //NSLog(@"createNewFlight ");
    justCreatedNewFlight = 1;
          
    loadedSignatureImage = nil;
    loadedSignature2Image = nil;
    [scrollSig removeFromSuperview];
    [scroll2Sig removeFromSuperview];
    signatureImageData = nil;
    signature2ImageData = nil;
    
    flagLoadManifestSentForThisFlight = 0;
    
    [calculatePerformanceClass_ resetInputObstacleHeight ];
   
    flagUsingAlternateEquipment = 0;
    
    flagMakeNewFlgtNow = 0;
    
    //NSLog(@"createNewFlight allFlightsMasterArray count %d ", allFlightsMasterArray.count);
    
    vFlightID =  [ [NSString alloc] initWithFormat:@"%lu", (unsigned long)allFlightsMasterArray.count];
    
    
    //NSLog(@"allFlightsMasterArray.count %lu", (unsigned long)allFlightsMasterArray.count);
    
    
     //NSLog(@"createNewFlight vFlightID %@", vFlightID);
    
    vLegID = @"1";
    
    [allFlightsMasterArray addObject:@"-"];
    [self addInternalFlightNumber];
    
   
    //NSLog(@"createNewFlight  vFlightID:%@  vLegID:  %@", vFlightID, vLegID);
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    [defaults  setObject: vFlightID  forKey:@"vFlightID"];
    
    
    [self resetFlightSettings];  // set configuration and load array listo
    
     
    
    flagResetAllLegs = 1;
   
    [self SaveValues]; // unter neuem Namen alles speichern
    
    
    
    [self createFlightButtons];
    
    

    
}

- (void) addInternalFlightNumber {
    
     internalFlightRandomNumber = arc4random()% 9999999;
    
    internalFlightID = [NSString stringWithFormat:@"%.0f", internalFlightRandomNumber ];
    
    [[NSUserDefaults standardUserDefaults]  setObject: internalFlightID   forKey:@"InternalFlightID"];
    //NSLog(@"creating internalFlightID %@", internalFlightID);
 
   
}




- (IBAction)actionAddLegToActiveFlight:(id)sender {
    
    alertFlag = 1002;
    
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Add Leg"
                          message:@"Please Confirm"
                          delegate:self
                          
                          cancelButtonTitle:@"Cancel"
                          
                          
                          
                          otherButtonTitles:@"Add Leg", nil];
    [alert show];

    
  
    
}

- (void) addLegToActiveFlight {
    
    
    
    float previousTotalFuelVolume = _sliderFuelMain1.value;
    float fuelUsedForLegVolume = 0;
    
    if ([fuelEnterMode isEqualToString:@"volume"]) { 
        fuelUsedForLegVolume = [inputFuelFlowOverride.text floatValue] * (legFlightTimeMinutes/60);
    }else{ 
        fuelUsedForLegVolume = ([inputFuelFlowOverride.text floatValue] * (legFlightTimeMinutes/60)) / [_inputSpecificFuelMassPerVolume.text floatValue];
    }
    
    
    [self SaveValues];    
    [self LoadValues];
    
    loadedSignatureImage = nil;
    loadedSignature2Image = nil;
    [scrollSig removeFromSuperview];
    [scroll2Sig removeFromSuperview];
    signatureImageData = nil;
    signature2ImageData = nil;
        
    vLegID =  [ [NSString alloc] initWithFormat:@"%lu", (unsigned long)allLegsPerFlightArray.count]; // next leg ID
    
    //NSLog(@"add leg for flight %d and  vLegID -%@- ", [vFlightID integerValue], vLegID);
    [allLegsPerFlightArray addObject:@"-"];        
     
    
    _vFlightTimeMinInput.text = @"0";
    
    [self guidanceResetLegDataOnly];
    [self checkGuidance];    
    [self SaveValues]; // unter neuem Namen alles speichern    
    [self LoadValues];    
    [self createFlightButtons]; 
      
    if (flagSpecialPHIFlightSettingPage == 1) {
        _viewLegData.hidden = NO; 
        [viewOne bringSubviewToFront:_viewLegData];
    }
    
    
    NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"];    
    if (dedicatedCustomerData.length < 2) {
        dedicatedCustomerData = @"";
    } 
    
     
    if ([dedicatedCustomerData rangeOfString:@"legAutoFuel"].location != NSNotFound  ) { 
        _sliderFuelMain1.value = previousTotalFuelVolume - fuelUsedForLegVolume;
        if (_sliderFuelLanding.value >= _sliderFuelMain1.value ) {
            _sliderFuelLanding.value = _sliderFuelMain1.value - (_sliderFuelMain1.value * 0.05);
        }
        //NSLog(@"new _sliderFuelMain1.value %f", _sliderFuelMain1.value);
    }

    
    
    
}

- (IBAction)actionChangeAircraft:(id)sender {
   
    if (flagSpecialPHIFlightSettingPage == 1) {
        _inputPHIOverrideRegistration.text = vFlightRegistration.text;
        _viewSelectHelicopter.hidden = NO; 
        [viewOne bringSubviewToFront:_viewSelectHelicopter];
        _viewPHIstartScreen.hidden = NO;
        _viewSelectACWindow.hidden = YES;
        UIImage *btnImg = [UIImage imageNamed:@"lock - locked-01.png"];
        [_buttonUnlockBEWOverride setBackgroundImage:btnImg forState:UIControlStateNormal];
        _inputPHIOverrideRegistration.enabled = NO; _inputPHIOverrideRegistration.backgroundColor = [UIColor lightGrayColor];
        _inputPHIOverrideBEW.enabled = NO; _inputPHIOverrideBEW.backgroundColor = [UIColor lightGrayColor];
        _inputPHIOverrideMoment.enabled = NO; _inputPHIOverrideMoment.backgroundColor = [UIColor lightGrayColor];
        _inputPHIOverrideFuelFlow.enabled = NO; _inputPHIOverrideFuelFlow.backgroundColor = [UIColor lightGrayColor];
        _inputPHIOverrideMomentLat.enabled = NO; _inputPHIOverrideMomentLat.backgroundColor = [UIColor lightGrayColor];
        _inputPHIOverrideSledWeight.enabled = NO; _inputPHIOverrideSledWeight.backgroundColor = [UIColor lightGrayColor];
        [_viewSelectHelicopter bringSubviewToFront:_viewPHIstartScreen];
        _buttonSaveUpdateACdata.hidden = NO;
        _buttonCreateNewPHIFlight.hidden = YES;
        _buttonPHIcancelCreateFlight.hidden = YES;
        
        [self checkOverrideInputs]; 
        
    }else{
        NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];    
        if ([customerFolderName isEqualToString:@"noAccount"] ) {          
            
            if (_viewFleetManager.hidden == YES) {
                _viewFleetManager.hidden = NO;
                [viewOne bringSubviewToFront:_viewFleetManager];        
                NSNotification *myNotification = [NSNotification notificationWithName:@"notificationViewAircraftManager"
                                                                               object:self //object is usually the object posting the notification
                                                                             userInfo:nil]; //userInfo is an optional dictionary            
                //Post it to the default notification center
                [[NSNotificationCenter defaultCenter] postNotification:myNotification];            
            }else{
                _viewFleetManager.hidden = YES;
            }         
            
        }else{        
            //NSLog(@"actionChangeAircraft");
            
            NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"];
            if (dedicatedCustomerData.length < 2) {
                dedicatedCustomerData = @"";
            }
            _buttonShowHideEquipmentListPage.hidden = YES;
            if ([dedicatedCustomerData rangeOfString:@"allowToChangeCallsign"].location != NSNotFound  ) { 
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"This will allow to change the aircraft. All other settings remain the same."
                                                                                         message:nil
                                                                                  preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
                [alertController addAction:actionOk];
                [self presentViewController:alertController animated:YES completion:nil];
                flagMakeNewFlgtNow = 0;
                flagChangeCallsign = 1;
                _viewSelectHelicopter.hidden = NO; [viewOne bringSubviewToFront:_viewSelectHelicopter];
                flagShowOnlySameACType = 1; 
                [self addHelicopterButtons];
            }else{               
                alertFlag = 1010;                    
                UIAlertView *alert = [[UIAlertView alloc]
                                      initWithTitle:@"Change Registration. Data Reset!"
                                      message:@"This will allow to change the aircraft. The current environmental settings, crew data and configuration will be reset to default values."
                                      delegate:self
                                      cancelButtonTitle:@"Cancel" 
                                      
                                      otherButtonTitles:@"OK", nil];
                [alert show];
            }
        }
    }
    
    
}


- (IBAction)buttonActionSummaryManifest:(id)sender {
    
     displayWindow = 14;
    
    [self displayWindows];    

}


- (void) createSummaryLabels {
    
    
    [self SaveValues];
    [self LoadValues];
    
    for(UIView *subview in [_viewSummaryLegs subviews]) {
        [subview removeFromSuperview];
    }
    
   
    //NSLog(@"allFlightsMasterArray %@", allFlightsMasterArray);
    
    
    float yTop = 10;    
    float addLines = 0;    
    float xLeft = 15;    
    float yGap = 40;    
    float lineGap = 18;    
    float boxHeight = 310;    
    float boxWidth = 935;    
    float itemsInRow = 5;    
    float xGap = boxWidth / itemsInRow;
    
    int currentFlightID = [vFlightID intValue];    
    
    // basic data    
    [self createDateSummary];
    _sDate.text = summaryDateStamp;
    
    
    // data per leg    
    int numberOfLegsThisFlight =  [[allFlightsMasterArray objectAtIndex:currentFlightID] count] -1  ; // this is how many legs we have per fligh
        
    // note current flight    
    //load leg data for this flight    
    int totalStartsEng1 = 0;
    int totalStartsEng2 = 0;
    int totalRIN = 0;    
    int totalFlightTimeMinutes = 0;
    
    NSArray* legLabels = [[NSArray alloc] init];
    
    NSMutableDictionary *PHIdictionaryAllLegs = [[NSMutableDictionary alloc] init]; 
    
    _optionalButtonUploadSummary.hidden = YES;
    if (flagSpecialPHIFlightSettingPage == 1) { 
        _optionalButtonUploadSummary.hidden = NO;
        [_viewSummaryLowerButtons bringSubviewToFront:_optionalButtonUploadSummary];
    }
    
    
    for (int legID = 1; legID < numberOfLegsThisFlight+1 ; legID++) {
        
        NSMutableDictionary *tempLegSettingsDictionary = [[NSMutableDictionary alloc] init];
        tempLegSettingsDictionary = [allLegsPerFlightArray objectAtIndex: legID ]; 
        
              
         //NSLog(@"allLegsPerFlightArray  %@", [allLegsPerFlightArray objectAtIndex:legID]); 
        
        //NSLog(@"tempLegSettingsDictionary %@", tempLegSettingsDictionary);        
              
        //we have custom data for leg labels extra 7
        if ([[_arrayName25 objectAtIndex:47]length] > 10) {
            //NSLog(@"[_arrayName25 objectAtIndex:47] %@", [_arrayName25 objectAtIndex:47]);             
            NSMutableArray *templegLabelsArray = [[NSMutableArray alloc] init];
            [templegLabelsArray addObject:@""];
            NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"@"];
            NSArray *components = [[_arrayName25 objectAtIndex:47] componentsSeparatedByCharactersInSet:charSet];                            
            //NSLog(@"1components %@ ", components);                            
            for(int i =0; i<components.count; i++) {
                
                NSString *legLabelItem = [components objectAtIndex:i];
                NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@";"];
                NSArray *legLabelItemcomponents = [legLabelItem componentsSeparatedByCharactersInSet:charSet];  
                //NSLog(@"legLabelItemcomponents %@", legLabelItemcomponents);
                if ([[legLabelItemcomponents objectAtIndex:0]isEqualToString:@"Leg Box Height"]) {
                    boxHeight = [[legLabelItemcomponents objectAtIndex:1] floatValue];
                    continue;
                }
                NSString *textLegLabel =  [[NSString alloc] initWithFormat:@"@%@,%@$",[legLabelItemcomponents objectAtIndex:0],[legLabelItemcomponents objectAtIndex:1] ];
                //NSLog(@"textLegLabel %@", textLegLabel); 
                [templegLabelsArray addObject:textLegLabel];
                
            }
            legLabels = templegLabelsArray;
        }else{            
            //key        
            legLabels              = @[@"",                                        
                                       @"@Leg Number,legID$",                                            
                                       @"@PIC,PICofLeg$",
                                       @"@SIC,SICofLeg$",
                                       @"@MSA [MSL ft],1 customItem$",
                                       @"@_FROM,vFlightDeparture$",
                                       @"@TO,vFlightDestination$",
                                       @"@Departure Date/Time,_labelDepartureTimeLocal$",
                                       @"@Landing Date/Time,_labellandingtimeLocal$",
                                       @"@Leg Time [h:min],_labelGuidanceLegTime$",
                                       @"@_Fuel On Board,_labelGuidanceFuel$",                                            
                                       @"@Takeoff Mass [lbs],vTOW$",                                          
                                       @"@C.G.,labelCGTakeoff$",
                                       @"@MTOW [lbs],MTOW$", 
                                       @"@Starts E1,_vEngineStarts1$",                                             
                                       @"@_Remarks,_vFlightRemarks$",
                                       @"@2Passengers On Board,_labelPaxOnBoard$",
                                       ];
            
            
        }
        
        
        // create leg line        
        UIImageView *line =[[UIImageView alloc] initWithFrame:CGRectMake(0, (((legID+addLines)-1) *boxHeight)+ boxHeight-3 ,boxWidth, 2) ];
        line.backgroundColor = [UIColor blackColor];
        [_viewSummaryLegs addSubview: line];
        
        
        //@"@_Remarks,_vFlightRemarks$",
        
      
        float counterX = -1;        
        float counterY = 0;
        // get basic data from leg 1
        
        
        if (legID == 1) {            
            _sFlightID.text = [tempLegSettingsDictionary objectForKey: @"_vFlightIDName"  ];            
            _sACtype.text = [tempLegSettingsDictionary objectForKey: @"_legAC_Type"  ];            
            _sRegistration.text = [tempLegSettingsDictionary objectForKey: @"vFlightRegistration"  ];  
            _sBEW.text = [tempLegSettingsDictionary objectForKey: @"vBEW"  ];   
            
            _sBEW.text = [NSString stringWithFormat:@"%@ %@", [tempLegSettingsDictionary objectForKey: @"vBEW"], [tempLegSettingsDictionary objectForKey: @"selectedUnitForItems"]];
            
            if (flagSpecialPHIFlightSettingPage == 1) {
                _sCallsign.text = [tempLegSettingsDictionary objectForKey: @"_dropDownAvailablePHIEquipLists"  ];
                _sBase.text = [tempLegSettingsDictionary objectForKey: @"_inputPHIOverrideBase"  ];                
            
                //NSLog(@"random %@",  [legSettingsDictionary objectForKey: @"internalFlightRandomNumber"] );
                
                [PHIdictionaryAllLegs setObject:[legSettingsDictionary objectForKey: @"internalFlightRandomNumber"] forKey:@"Random Internal Flight ID"];
                [PHIdictionaryAllLegs setObject:_sRegistration.text forKey:@"AC Registration"];  
                [PHIdictionaryAllLegs setObject:_sCallsign.text forKey:@"Callsign"];
                [PHIdictionaryAllLegs setObject:_sFlightID.text forKey:@"Flight ID"];
                [PHIdictionaryAllLegs setObject:_sACtype.text forKey:@"AC Type"];                             
                [PHIdictionaryAllLegs setObject:_sBase.text forKey:@"Base"];                
                [PHIdictionaryAllLegs setObject:_sBEW.text forKey:@"BEW"];
            }
                   
        }
        
        totalFlightTimeMinutes = totalFlightTimeMinutes +  [[tempLegSettingsDictionary objectForKey: @"legFlightTimeMinutes"]integerValue ];
        
        //NSLog(@"totalFlightTimeMinutes %d ", totalFlightTimeMinutes);
        
        int minuteDifference = totalFlightTimeMinutes;
        int hours = minuteDifference / 60;
        int minutes = minuteDifference - (hours * 60);
        NSString *flightTime=  [ [NSString alloc] initWithFormat:@"%.d", minuteDifference ];
        if (minutes >= 10)                  { flightTime =  [ [NSString alloc] initWithFormat:@"0%.dh:%.dmin", hours, minutes ];}
        if (minutes <= 9  & minutes > 0)    { flightTime =  [ [NSString alloc] initWithFormat:@"0%.dh:0%.dmin", hours, minutes ];}
        if (minutes <= 0)                   { flightTime =  [ [NSString alloc] initWithFormat:@"0%.dh:00min", hours ];}
      
        _sTotalFlightTime.text = flightTime;
       
        // create all leg labels
        
        _sHeadlineStart1.hidden = YES; _sHeadlineStart2.hidden = YES; _sHeadlineRIN.hidden = YES;
        _sTotalStartsEng1.hidden = YES; _sTotalStartsEng2.hidden = YES; _sTotalRIN.hidden = YES;
        
        NSMutableDictionary *PHIdictionaryOneLeg = [[NSMutableDictionary alloc] init]; 
      

        
        for (int labelID = 1; labelID < legLabels.count ; labelID++) {            
            
            NSString *string= [legLabels objectAtIndex: labelID ];            
            NSRange searchFromRange = [string rangeOfString:@"@"];
            NSRange searchToRange = [string rangeOfString:@","];
            NSString *itemName = [string substringWithRange:NSMakeRange(searchFromRange.location+searchFromRange.length, searchToRange.location-searchFromRange.location-searchFromRange.length)];
                        
            float lineWidthAdd = 0;
            int factorLineHeight = 1;
            int liftLine = 0;
            
            // carriage return with _ in front of line
            if (itemName.length >1) {
                NSString *testIfCarriageReturn = [itemName substringToIndex:1];
                
                if ([testIfCarriageReturn isEqualToString:@"_"]) {
                    itemName = [itemName substringFromIndex:1];
                    counterY = counterY + 1;
                    counterX = -1;
                    
                }
                
                if ([testIfCarriageReturn isEqualToString:@"2"]) {
                    itemName = [itemName substringFromIndex:1];
                    counterY = counterY + 1;
                    counterX = -1;
                    lineWidthAdd = 700;
                    //factorLineHeight = 2;
                    
                    //liftLine = 7;
                }
                
            }
                        
            searchFromRange = [string rangeOfString:@","];
            searchToRange = [string rangeOfString:@"$"];
            NSString *itemID = [string substringWithRange:NSMakeRange(searchFromRange.location+searchFromRange.length, searchToRange.location-searchFromRange.location-searchFromRange.length)];
            
            // get totals            
            if ([itemName isEqualToString:@"Starts E1"]) {
                _sHeadlineStart1.hidden = NO;
                _sTotalStartsEng1.hidden = NO;
                totalStartsEng1 = totalStartsEng1 + [[tempLegSettingsDictionary objectForKey: itemID    ]floatValue ];
            }
            
            if ([itemName isEqualToString:@"Starts E2"]) {
                _sHeadlineStart2.hidden = NO;
                _sTotalStartsEng2.hidden = NO;
                totalStartsEng2 = totalStartsEng2 + [[tempLegSettingsDictionary objectForKey: itemID    ]floatValue ];
            }
            if ([itemName isEqualToString:@"RIN"]) {
                _sHeadlineRIN.hidden = NO;
                _sTotalRIN.hidden = NO;
                totalRIN = totalRIN + [[tempLegSettingsDictionary objectForKey: itemID    ]floatValue ];
            }          
            
            _sTotalStartsEng1.text = [NSString stringWithFormat:@"%d",totalStartsEng1 ];
            _sTotalStartsEng2.text = [NSString stringWithFormat:@"%d",totalStartsEng2 ];
            _sTotalRIN.text = [NSString stringWithFormat:@"%d",totalRIN ];
            //NSLog(@"itemID -%@-", itemID);
            
            counterX = counterX + 1;            
            if (counterX == itemsInRow) {
                counterX = 0;                
                counterY = counterY + 1;
            }
            
            UILabel *legLabel = [[UILabel alloc] initWithFrame:CGRectMake(xLeft + (counterX * xGap) , yTop + ((legID-1) *boxHeight) + (counterY * yGap )  , xGap, 30)];
            legLabel.font = [UIFont systemFontOfSize:15];
            legLabel.textAlignment = NSTextAlignmentLeft;
            legLabel.textColor = [UIColor darkGrayColor];
            //legLabel.backgroundColor = [UIColor redColor];            
            [legLabel  setText: itemName  ];            
            [_viewSummaryLegs addSubview: legLabel];
            
            legLabel = [[UILabel alloc] initWithFrame:CGRectMake(xLeft + (counterX * xGap) , yTop + ((legID-1) *boxHeight) + (counterY * yGap ) +  lineGap - liftLine, xGap + lineWidthAdd, 30 * factorLineHeight )];
            legLabel.font = [UIFont boldSystemFontOfSize:15];
            legLabel.textAlignment = NSTextAlignmentLeft;
            legLabel.textColor = [UIColor blackColor];
            legLabel.adjustsFontSizeToFitWidth = YES;   // trick to shrink fonts  
            if (factorLineHeight > 1) {
                legLabel.font = [UIFont boldSystemFontOfSize:13];                
                legLabel.numberOfLines = 2;
            }            
            [legLabel  setText: [tempLegSettingsDictionary objectForKey: itemID]];  
           
            if ([itemID rangeOfString:@"customItem"].location != NSNotFound     ) {
                NSMutableArray *tempArrayCustomFltData = [[NSMutableArray alloc] init];
                tempArrayCustomFltData = [tempLegSettingsDictionary objectForKey:@"arrayCustomFlightDataElements"];                
                [legLabel  setText:  [tempArrayCustomFltData objectAtIndex:[itemID intValue]-1]];  
            }
            
            [_viewSummaryLegs addSubview: legLabel];
            
            if (flagSpecialPHIFlightSettingPage == 1) { 
                
                  //[PHIdictionaryAllLegs setObject:_arrayName1 forKey:@"Total Starts E1"];                 
            
                 [PHIdictionaryAllLegs setObject:_sTotalStartsEng1.text forKey:@"Total Starts E1"];
                 [PHIdictionaryAllLegs setObject:_sTotalStartsEng2.text forKey:@"Total Starts E2"];
                 [PHIdictionaryAllLegs setObject:_sTotalRIN.text forKey:@"Total RIN"];
                 [PHIdictionaryAllLegs setObject:_sTotalFlightTime.text forKey:@"Total Flight Time"];    
                
                //NSLog(@"tempLegSettingsDictionary %@", tempLegSettingsDictionary);
                
                
                
                NSString *keyValue = [tempLegSettingsDictionary objectForKey: itemID  ];                
                if ([keyValue rangeOfString:@"customItem"].location != NSNotFound     ) {
                    NSMutableArray *tempArrayCustomFltData = [[NSMutableArray alloc] init];
                    tempArrayCustomFltData = [tempLegSettingsDictionary objectForKey:@"arrayCustomFlightDataElements"];                
                    keyValue = [tempArrayCustomFltData objectAtIndex:[itemID intValue]-1];  
                    //NSLog(@"setting !!!  itemID %@ keyValue %@", itemID, keyValue);
                }
                
                if (keyValue.length <1) {
                    keyValue = @"noData";
                }
                //NSLog(@"itemID %@ keyValue %@", itemID, keyValue);
                
                        
                [PHIdictionaryOneLeg setObject: [tempLegSettingsDictionary objectForKey: @"arrayConfigItemName" ] forKey:@"arrayConfigItemName"];
                [PHIdictionaryOneLeg setObject: [tempLegSettingsDictionary objectForKey: @"arrayConfigItemWeight" ] forKey:@"arrayConfigItemWeight"];
                [PHIdictionaryOneLeg setObject: [tempLegSettingsDictionary objectForKey: @"arrayConfigItemArmLong" ] forKey:@"arrayConfigItemArmLong"];
                [PHIdictionaryOneLeg setObject: [tempLegSettingsDictionary objectForKey: @"arrayConfigItemMomLong" ] forKey:@"arrayConfigItemMomLong"];
                [PHIdictionaryOneLeg setObject: [tempLegSettingsDictionary objectForKey: @"arrayConfigItemArmLat" ] forKey:@"arrayConfigItemArmLat"];
                [PHIdictionaryOneLeg setObject: [tempLegSettingsDictionary objectForKey: @"arrayConfigItemMomLat" ] forKey:@"arrayConfigItemMomLat"];
                [PHIdictionaryOneLeg setObject: [tempLegSettingsDictionary objectForKey: @"arrayConfigIteminOut" ] forKey:@"arrayConfigIteminOut"];
                
                
                [PHIdictionaryOneLeg setObject: keyValue forKey:itemName];
                [PHIdictionaryOneLeg setObject:_arrayName1 forKey:@"_arrayName1"];
                [PHIdictionaryOneLeg setObject:_arrayName2 forKey:@"_arrayName2"];
                [PHIdictionaryOneLeg setObject:_arrayName3 forKey:@"_arrayName3"];
                [PHIdictionaryOneLeg setObject:_arrayName4 forKey:@"_arrayName4"];
                [PHIdictionaryOneLeg setObject:_arrayName5 forKey:@"_arrayName5"];
                [PHIdictionaryOneLeg setObject:_arrayName6 forKey:@"_arrayName6"];
                [PHIdictionaryOneLeg setObject:_arrayName7 forKey:@"_arrayName7"];
                [PHIdictionaryOneLeg setObject:_arrayName8 forKey:@"_arrayName8"];
                [PHIdictionaryOneLeg setObject:_arrayName9 forKey:@"_arrayName9"];
                [PHIdictionaryOneLeg setObject:_arrayName10 forKey:@"_arrayName10"];                
                [PHIdictionaryOneLeg setObject:_arrayName11 forKey:@"_arrayName11"];
                [PHIdictionaryOneLeg setObject:_arrayName12 forKey:@"_arrayName12"];
                [PHIdictionaryOneLeg setObject:_arrayName13 forKey:@"_arrayName13"];
                [PHIdictionaryOneLeg setObject:_arrayName14 forKey:@"_arrayName14"];
                [PHIdictionaryOneLeg setObject:_arrayName15 forKey:@"_arrayName15"];
                [PHIdictionaryOneLeg setObject:_arrayName16 forKey:@"_arrayName16"];
                [PHIdictionaryOneLeg setObject:_arrayName17 forKey:@"_arrayName17"];
                [PHIdictionaryOneLeg setObject:_arrayName18 forKey:@"_arrayName18"];
                [PHIdictionaryOneLeg setObject:_arrayName19 forKey:@"_arrayName19"];
                /*
                [PHIdictionaryOneLeg setObject:_arrayName20 forKey:@"_arrayName20"];
                [PHIdictionaryOneLeg setObject:_arrayName21 forKey:@"_arrayName21"];
                [PHIdictionaryOneLeg setObject:_arrayName22 forKey:@"_arrayName22"];
                [PHIdictionaryOneLeg setObject:_arrayName23 forKey:@"_arrayName23"];
                [PHIdictionaryOneLeg setObject:_arrayName24 forKey:@"_arrayName24"];
                [PHIdictionaryOneLeg setObject:_arrayName25 forKey:@"_arrayName25"];
                 */
                 
            }
            
            NSString *legName = [NSString stringWithFormat:@"leg %d",legID ];
            [PHIdictionaryAllLegs setObject:PHIdictionaryOneLeg forKey:legName];
            
        }// end next all labels
        
              
        // create vertical line        
        UIImageView *verticalLine =[[UIImageView alloc] initWithFrame:CGRectMake(-3, 0 ,3, (boxHeight *( numberOfLegsThisFlight  +addLines) -1 ) ) ];
        verticalLine.backgroundColor = [UIColor blackColor];
        [_viewSummaryLegs addSubview: verticalLine];        
        
        verticalLine =[[UIImageView alloc] initWithFrame:CGRectMake(935, 0 ,3, (boxHeight * ( numberOfLegsThisFlight +addLines) -1 ) ) ];
        verticalLine.backgroundColor = [UIColor blackColor];
        [_viewSummaryLegs addSubview: verticalLine];
        
        summaryBoxHeight = (boxHeight *( numberOfLegsThisFlight +addLines));        
        _viewSummaryLegs.frame = CGRectMake(63, 288, 935, summaryBoxHeight    );        
        [_scrollViewSummaryManifest setContentSize:CGSizeMake(1024, _viewSummaryLegs.frame.size.height + 800)];        
        
    }
    
      //NSLog(@"PHIdictionaryAllLegs %@", PHIdictionaryAllLegs);
    if (flagSpecialPHIFlightSettingPage == 1) {  
        
        NSError *error;        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:PHIdictionaryAllLegs // Here you can pass array or dictionary
                                                           options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                             error:&error];    
        jsonString = @"";
        if (jsonData) {
            jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            //This is your JSON String
            //NSUTF8StringEncoding encodes special characters using an escaping scheme
        } else {
            //NSLog(@"Got an error: %@", error);
            jsonString = @"";
        }
        //NSLog(@"Your JSON String is %@", jsonString);

        
        
    }
    
}




- (IBAction)actionRunMainRoutine:(id)sender {
    
    [self setBasicsForConfiguration];
    
    [self MainRoutine];
    
}






    
    
- (IBAction)actionSetFuel:(id)sender {
    
    triggerFuelAnimation = 1;
    
    guidanceDictionary[@"guidanceBtnFuelPanel"] =  @"ok";
    if (flagFuelVisisble == 0) {
        flagFuelVisisble = 1;
    }else{
        flagFuelVisisble = 0;
    }
    [self setFuelPanelandLegDataViews];
     [self MainRoutine];
}



- (IBAction)actionSegmentSeatLoadOptions:(id)sender {
    
  
    
    
    [self createListoItemsSlidersAndInterior];
    
    [self MainRoutine];
    
    
}


- (IBAction)actionSegmentNamesOnSeats:(id)sender {
    
    previousConfiguration = 999;
    [self createListoItemsSlidersAndInterior];
    [self MainRoutine];
    
}



- (IBAction)actionSegmentSwapMode:(id)sender {
    
 
    
    
    if (_segmentSwapMode.selectedSegmentIndex == 1) {
        panRecognizerForGhost.enabled = YES;
    }else{
        panRecognizerForGhost.enabled = NO;
    }
    
}



- (void) addLegButtons {
   
    for(UIView *subview in [_viewLegButtons subviews]) {
        [subview removeFromSuperview];
    }
    
    if (_segmentFlightLegMode.selectedSegmentIndex == 0) {
        return;
    }
    
   
   
    
    //NSLog(@"addLegButtons");
    
    int numberOfLegsThisFlight = [[flightSettingsDictionary  objectForKey:@"numberOfLegsThisFlight"] floatValue];
    //NSLog(@"numberOfLegsThisFlight %d ", numberOfLegsThisFlight);
    
    int currentGuidanceCheck = guidanceLegCheckOK;  // this is for the active leg
     //NSLog(@"currentGuidanceCheck %d", currentGuidanceCheck);    
    
    
    if (numberOfLegsThisFlight < 2) {
        UIImage *btnImage = [UIImage imageNamed:@"button_no_select"];
        [_buttonPreviousLeg  setBackgroundImage:btnImage forState:UIControlStateNormal];
    }
    
    UIImage *btnBlueOK = [UIImage imageNamed:@"button blue top92x52.png"];
    UIImage *btnNotAvail = [UIImage imageNamed:@"button_no_select"];
    
    [_buttonNextLeg  setBackgroundImage:btnBlueOK forState:UIControlStateNormal];
    [_buttonPreviousLeg  setBackgroundImage:btnBlueOK forState:UIControlStateNormal];
    [_buttonAddLeg  setBackgroundImage:btnBlueOK forState:UIControlStateNormal];
    [_buttonDeleteActiveLeg  setBackgroundImage:btnBlueOK forState:UIControlStateNormal];
    
    
    //NSLog(@"numberOfLegsThisFlight %d", numberOfLegsThisFlight);    
    //NSLog(@"[vLegID integerValue] %ld", (long)[vLegID integerValue]);
    
    if (numberOfLegsThisFlight == [vLegID integerValue]) {
        [_buttonNextLeg  setBackgroundImage:btnNotAvail forState:UIControlStateNormal];
    }
    
    if (numberOfLegsThisFlight <= 1) {
         [_buttonDeleteActiveLeg  setBackgroundImage:btnNotAvail forState:UIControlStateNormal];
    }
    
    
    if ([vLegID integerValue] == 1) {
        [_buttonPreviousLeg  setBackgroundImage:btnNotAvail forState:UIControlStateNormal];
       
    }
    
     if (guidanceLegCheckOK == 0) {
          [_buttonAddLeg  setBackgroundImage:btnNotAvail forState:UIControlStateNormal];
         
     }
    
    
    
    
 
    
    float buttonWidth = 0;
    float xGap = 0;
    float buttonHeight = 0;
    float yGap = 0;
    float overlap =0;
    
    if (flagIsLandscape == 1) {
        buttonWidth = 125;
        buttonHeight = 52;
        xGap = buttonWidth;
        overlap =2;
        yGap = 0;
    }else{
        xGap = 0;
        buttonWidth = 125;
        buttonHeight = 55;
        overlap = 0;
        yGap = buttonHeight;
    }
    
    UIButton* btn = (UIButton*)[_viewSelectorButtons viewWithTag: 222 ];
    UIImage *btnImage = [UIImage imageNamed:@"button blue top184x52"];
    [btn  setBackgroundImage:btnImage forState:UIControlStateNormal];
    
    for(int i=0; i<numberOfLegsThisFlight; i++) {
        
       
        UIButton *perfButton = [UIButton buttonWithType:UIButtonTypeCustom];
        perfButton.frame     = CGRectMake( i * xGap - i * overlap , 2 + i * yGap, buttonWidth, buttonHeight );
        perfButton.tag = i;
        [perfButton addTarget:self action:@selector(actionLegButton:) forControlEvents:UIControlEventTouchUpInside];
        
        UIImage *bg = [UIImage imageNamed:@"button grey top184x52.png"];
        UIImage *bb = [UIImage imageNamed:@"bb.png"];
        UIImage *byel = [UIImage imageNamed:@"button_yellow_leg.png"];
        UIImage *bgreen = [UIImage imageNamed:@"button_green.png"];
        int guidanceCheckValue = [[ [allLegsPerFlightArray objectAtIndex: i+1 ] objectForKey:@"guidanceLegCheckOK"] integerValue]; // trick to get the info from within leg arrays **********
               
        int showLegStripe = 0;
              
        //NSLog(@"_switchGuidance.on %d", _switchGuidance.on);              
        //NSLog(@"1");    
        if (i +1 == [vLegID integerValue]) {
            showLegStripe = 1;
            [perfButton setBackgroundImage:byel forState:UIControlStateNormal];
            //NSLog(@"2");
            if (guidanceCheckValue == 1 & _switchGuidance.on == YES) {
                //NSLog(@"3");
                [perfButton setBackgroundImage:bgreen forState:UIControlStateNormal];
                //UIButton* btn = (UIButton*)[_viewSelectorButtons viewWithTag: 222 ];
                //UIImage *btnImage = [UIImage imageNamed:@"button_green.png"];
                //[btn  setBackgroundImage:btnImage forState:UIControlStateNormal];
            }
            
            if (currentGuidanceCheck == 1 & _switchGuidance.on == YES) {
                //NSLog(@"4");
                [perfButton setBackgroundImage:bgreen forState:UIControlStateNormal];
                //UIButton* btn = (UIButton*)[_viewSelectorButtons viewWithTag: 222 ];
                //UIImage *btnImage = [UIImage imageNamed:@"button_green.png"];
                //[btn  setBackgroundImage:btnImage forState:UIControlStateNormal];
            }
            
            if (currentGuidanceCheck == 0 & _switchGuidance.on == YES) {
                //NSLog(@"5");
                [perfButton setBackgroundImage:byel forState:UIControlStateNormal];
                //UIButton* btn = (UIButton*)[_viewSelectorButtons viewWithTag: 222 ];
                //UIImage *btnImage = [UIImage imageNamed:@"button_yellow_leg.png"];
                //[btn  setBackgroundImage:btnImage forState:UIControlStateNormal];
            }
            
            if ( _switchGuidance.on == NO) {
                //NSLog(@"6");
                [perfButton setBackgroundImage:bb forState:UIControlStateNormal];
            }
            
            
        }else{
            //NSLog(@"7");
            if (guidanceCheckValue == 1 & _switchGuidance.on == YES) {
                //NSLog(@"8");
                [perfButton setBackgroundImage:bgreen forState:UIControlStateNormal];
            }else{
                //NSLog(@"9");
                [perfButton setBackgroundImage:byel forState:UIControlStateNormal];
            }
            if ( _switchGuidance.on == NO) {
                //NSLog(@"10");
                [perfButton setBackgroundImage:bg forState:UIControlStateNormal];
            }
        }
       
        [perfButton setBackgroundImage:bg forState:UIControlStateHighlighted];
        [_viewLegButtons addSubview:perfButton];
        
        UILabel *label = [[UILabel alloc] init];
        label.frame       = CGRectMake( i * xGap - i * overlap , 0 + i * yGap, buttonWidth, buttonHeight );
        [label setFont:[UIFont systemFontOfSize:17]];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        label.text = [NSString stringWithFormat:@"Leg: %d",i+1];
        [_viewLegButtons addSubview:label];
        
        if (showLegStripe == 1) {
            //legStripe
            UIView *legStripe = [[UIView alloc] init];
            legStripe.tag = 888;
            legStripe.backgroundColor = [UIColor whiteColor];
            legStripe.frame     = CGRectMake( i * xGap - i * overlap , 0 + i * yGap + buttonHeight - 6, buttonWidth, 6 );
            legStripe.hidden = NO;
            [_viewLegButtons addSubview:legStripe];
        }
    }
}




- (IBAction)actionLegButton:(id)sender{
    
    int flagFlightSettingsOpen =0;
    if (_viewLegData.hidden == NO) {
        flagFlightSettingsOpen =1;
    }
    
    [self SaveValues];
    
     UIButton *btn = (UIButton*)sender;
    vLegID = [NSString stringWithFormat:@"%d",  btn.tag +1  ];
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    [defaults  setObject:vLegID                     forKey:@"vLegID"];
    [self LoadValues];
    [self MainRoutine];
    [self calculateListo];
    
    if (flagFlightSettingsOpen == 1) {
        _viewLegData.hidden = NO;
    }
    
}


- (IBAction)actionShowHidePerformance:(id)sender {
   
}


- (void) guidanceResetTotal {
    
    guidanceDictionary[@"guidanceBtnSetConfiguration"] =  @"nok";
    guidanceDictionary[@"guidanceBtnSetEquipment"] =  @"nok";
    guidanceDictionary[@"guidanceBtnPerformance"] =  @"nok";
    guidanceDictionary[@"guidanceBtnCrew"] =  @"nok";
    guidanceDictionary[@"guidanceBtnDispatch"] =  @"nok";
    guidanceDictionary[@"guidanceBtnFuelPanel"] =  @"nok";
    
    guidanceDictionary[@"guidanceFlightID"] =  @"nok";
    
    return;

    
}

- (void) guidanceResetLegDataOnly {
    
     //NSLog(@"guidanceResetLegDataOnly"); 
    
    _labelDepartureTimeLocal.text = @"";
    _labelDepartureTimeGMT.text = @"";
    _labellandingtimeLocal.text = @"";
    
    vFlightDeparture.text = vFlightDestination.text;
    vFlightDestination.text = @"";
    
    _vEngineStarts1.text = @"";
    _vEngineStarts2.text = @"";
    _vRIN.text = @"";
    _vFlightRemarks.text = @"";

    
    guidanceDictionary[@"guidanceBtnPerformance"] =  @"nok";
    guidanceDictionary[@"guidanceBtnCrew"] =  @"ok";
    guidanceDictionary[@"guidanceBtnDispatch"] =  @"ok";
    guidanceDictionary[@"guidanceBtnFuelPanel"] =  @"nok";

    
    if ([[_arrayName23 objectAtIndex:40] rangeOfString:@"newVersion"].location != NSNotFound ) { 
        
        for (int i = 0; i < [[_viewCustomFlightDataElements subviews] count]/2; i++) {            
            int customGuidanceItemID = 17 + i;
            UITextField *viewElement = (UITextField*)[_viewCustomFlightDataElements viewWithTag: customGuidanceItemID ];  
            NSString *customGuidanceText = viewElement.text;
            //NSLog(@"reset %d = %@", customGuidanceItemID, customGuidanceText);   
            [viewElement setText:@""];
        }
        
    }
    
    return;
    
    
}



- (void) guidanceResetLegDataAll {
    
    //NSLog(@"guidanceResetLegDataAll"); 
          
          
    _labelDepartureTimeLocal.text = @"";
    _labelDepartureTimeGMT.text = @"";
    _labellandingtimeLocal.text = @"";
    
    vFlightDeparture.text = @"";
    vFlightDestination.text = @"";
    vFlightDestination.text = @"";
    
    _vEngineStarts1.text = @"";
    _vEngineStarts2.text = @"";
    _vRIN.text = @"";
    _vFlightRemarks.text = @"";
    
    
    guidanceDictionary[@"guidanceBtnPerformance"] =  @"ok";
    guidanceDictionary[@"guidanceBtnCrew"] =  @"ok";
    guidanceDictionary[@"guidanceBtnDispatch"] =  @"ok";
    guidanceDictionary[@"guidanceBtnFuelPanel"] =  @"nok";
    
    if ([[_arrayName23 objectAtIndex:40] rangeOfString:@"newVersion"].location != NSNotFound ) { 
        
        for (int i = 0; i < [[_viewCustomFlightDataElements subviews] count]/2; i++) {            
            int customGuidanceItemID = 17 + i;
            UITextField *viewElement = (UITextField*)[_viewCustomFlightDataElements viewWithTag: customGuidanceItemID ];  
            NSString *customGuidanceText = viewElement.text;
            //NSLog(@"reset %d = %@", customGuidanceItemID, customGuidanceText);   
            [viewElement setText:@""];
        }

        
        
        
    }
    
    
    return;
    
    
}


- (void) setGuidanceNeutral {
    
    
    _labelFlightLegID.backgroundColor = [UIColor lightGrayColor];
    _labelFlightLegID.textColor = [UIColor blackColor];
    
    [_inputPaxOnBoard setBackgroundColor: [UIColor lightGrayColor] ];
    
    [_vFlightIDName setBackgroundColor: [UIColor lightGrayColor] ];
    
    [_vEngineStarts1 setBackgroundColor: [UIColor lightGrayColor] ];
    [_vEngineStarts2 setBackgroundColor: [UIColor lightGrayColor] ];
    [_vRIN setBackgroundColor: [UIColor lightGrayColor] ];
    [_vFlightRemarks setBackgroundColor: [UIColor lightGrayColor] ];
    
    [_labelDepartureTimeLocal setBackgroundColor: [UIColor lightGrayColor] ];
    [_labellandingtimeLocal setBackgroundColor: [UIColor lightGrayColor] ];
    
    [vFlightDeparture setBackgroundColor: [UIColor lightGrayColor] ];
    [vFlightDestination setBackgroundColor: [UIColor lightGrayColor] ];
    
    [_vCockpitSeatLeft setBackgroundColor: [UIColor lightGrayColor] ];
    [_vCockpitSeatRight setBackgroundColor: [UIColor lightGrayColor] ];
    
    
    [_vCockpitSeatLeft setBackgroundColor: [UIColor lightGrayColor] ];
   
    
    UIImage *blueBUtton = [UIImage imageNamed:@"button generic blue.png"];
    
    [_guidanceBtnSetConfiguration setBackgroundImage:blueBUtton forState:UIControlStateNormal];    
    [_guidanceBtnSetConfiguration setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    [_guidanceBtnSetEquipment setBackgroundImage:blueBUtton forState:UIControlStateNormal];
    [_guidanceBtnSetEquipment setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    [_guidanceBtnPerformance setBackgroundImage:blueBUtton forState:UIControlStateNormal];
    [_guidanceBtnPerformance setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    [_guidanceBtnCrew setBackgroundImage:blueBUtton forState:UIControlStateNormal];
    [_guidanceBtnCrew setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    
    [_guidanceBtnDispatch setBackgroundImage:blueBUtton forState:UIControlStateNormal];
    [_guidanceBtnDispatch setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    [_guidanceBtnFuelPanel setBackgroundImage:blueBUtton forState:UIControlStateNormal];
    [_guidanceBtnFuelPanel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    
    _labelGuidanceOAT.text =  [ [NSString alloc] initWithFormat:@"OAT: %.0fºC", OAT ];
    _labelGuidancePA.text =  [ [NSString alloc] initWithFormat:@"PA: %.0f""", Hp ];
    
    _labelGuidanceFuel.text =  [ [NSString alloc] initWithFormat:@"%@ %@", _labelSliderFuelMain.text, _labelFuelUnitMainTank.text];
    
    
    
}


- (void) checkGuidance {
    
    
    if (_switchGuidance.on == NO) {        
        [self setGuidanceNeutral];        
        return;
    }
    
   
    //NSLog(@"checkGuidance ");
   
    //NSLog(@"previousCheckResult %d", previousCheckResult);    
    
    UIImage *yellowButton = [UIImage imageNamed:@"button strong yellow.png"];    
    UIImage *greenButton = [UIImage imageNamed:@"button strong green.png"];
    
    guidanceLegCheckOK = 1;    
    //NSLog(@"itemsGuidance %@", itemsGuidance);
                    
    
    if ([[itemsGuidance objectAtIndex:0] isEqualToString:@"1"]) {        
        if ( _vFlightIDName.text.length < 1) {
            [_vFlightIDName setBackgroundColor: yellowSpecialColor]; guidanceLegCheckOK = 0;
        }else{
            [_vFlightIDName setBackgroundColor: GreenColor];
           }
    }  
    
 
 
   
    if ( [[itemsGuidance objectAtIndex:1] isEqualToString:@"1"]) {        
        if ([[guidanceDictionary objectForKey:@"guidanceBtnSetConfiguration"] isEqualToString:@"nok"]) {            
            [_guidanceBtnSetConfiguration setBackgroundImage:yellowButton forState:UIControlStateNormal]; guidanceLegCheckOK = 0;
            [_guidanceBtnSetConfiguration setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }else{
            [_guidanceBtnSetConfiguration setBackgroundImage:greenButton forState:UIControlStateNormal];
            [_guidanceBtnSetConfiguration setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
    
 
    if ([[itemsGuidance objectAtIndex:2] isEqualToString:@"1"]) {        
        if ([[guidanceDictionary objectForKey:@"guidanceBtnSetEquipment"] isEqualToString:@"nok"]) {
            [_guidanceBtnSetEquipment setBackgroundImage:yellowButton forState:UIControlStateNormal]; guidanceLegCheckOK = 0;
            [_guidanceBtnSetEquipment setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }else{
            [_guidanceBtnSetEquipment setBackgroundImage:greenButton forState:UIControlStateNormal];
            [_guidanceBtnSetEquipment setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
        
    }    
  
    if ( [[itemsGuidance objectAtIndex:3] isEqualToString:@"1"]) {       
        
        if ([[guidanceDictionary objectForKey:@"guidanceBtnDispatch"] isEqualToString:@"nok"]) {
            [_guidanceBtnDispatch setBackgroundImage:yellowButton forState:UIControlStateNormal]; guidanceLegCheckOK = 0;
            [_guidanceBtnDispatch setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }else{
            [_guidanceBtnDispatch setBackgroundImage:greenButton forState:UIControlStateNormal];
            [_guidanceBtnDispatch setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    
    }
    
     
    if ( [[itemsGuidance objectAtIndex:4] isEqualToString:@"1"]) {
        
        
        if ( _inputPaxOnBoard.text.length < 1) {
            [_inputPaxOnBoard setBackgroundColor: yellowSpecialColor]; guidanceLegCheckOK = 0;
        }else{
            [_inputPaxOnBoard setBackgroundColor: GreenColor];
        }
        
    }
   
    if ( [[itemsGuidance objectAtIndex:5] isEqualToString:@"1"]) {
        
        if ([[guidanceDictionary objectForKey:@"guidanceBtnPerformance"] isEqualToString:@"nok"]) {
            [_guidanceBtnPerformance setBackgroundImage:yellowButton forState:UIControlStateNormal]; guidanceLegCheckOK = 0;
            [_guidanceBtnPerformance setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }else{
            [_guidanceBtnPerformance setBackgroundImage:greenButton forState:UIControlStateNormal];
            [_guidanceBtnPerformance setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
    
    if ( [[itemsGuidance objectAtIndex:6] isEqualToString:@"1"]) {
        
        if ([[guidanceDictionary objectForKey:@"guidanceBtnFuelPanel"] isEqualToString:@"nok"]) {
            
            [_guidanceBtnFuelPanel setBackgroundImage:yellowButton forState:UIControlStateNormal]; guidanceLegCheckOK = 0;
            [_guidanceBtnFuelPanel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }else{
            [_guidanceBtnFuelPanel setBackgroundImage:greenButton forState:UIControlStateNormal];
            [_guidanceBtnFuelPanel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
    
    
     
    if ([[itemsGuidance objectAtIndex:7] isEqualToString:@"1"]) {
        
        if ( vFlightDeparture.text.length < 1) {
            [vFlightDeparture setBackgroundColor: yellowSpecialColor]; guidanceLegCheckOK = 0;
        }else{
            [vFlightDeparture setBackgroundColor: GreenColor];
        }
        
        
        if ( vFlightDestination.text.length < 1) {
            [vFlightDestination setBackgroundColor: yellowSpecialColor]; guidanceLegCheckOK = 0;
        }else{
            [vFlightDestination setBackgroundColor: GreenColor];
        }
    }

    
    
    if ([[itemsGuidance objectAtIndex:8] isEqualToString:@"1"]) {
        
        if ( _labelDepartureTimeLocal.text.length < 1) {            
            [_labelDepartureTimeLocal setBackgroundColor: yellowSpecialColor]; guidanceLegCheckOK = 0;
        }else{
            [_labelDepartureTimeLocal setBackgroundColor: GreenColor];
        }
        
       
    }
    
    if ([[itemsGuidance objectAtIndex:9] isEqualToString:@"1"]) {
        
       
        
        if ( _labellandingtimeLocal.text.length < 1) {
            [_labellandingtimeLocal setBackgroundColor: yellowSpecialColor]; guidanceLegCheckOK = 0;
        }else{
            [_labellandingtimeLocal setBackgroundColor: GreenColor];
        }
    }
    
  
   
    if ([[itemsGuidance objectAtIndex:10] isEqualToString:@"1"]) {
        
        if ([[guidanceDictionary objectForKey:@"guidanceBtnCrew"] isEqualToString:@"nok"]) {
            
            [_guidanceBtnCrew setBackgroundImage:yellowButton forState:UIControlStateNormal]; guidanceLegCheckOK = 0;
            [_guidanceBtnCrew setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }else{
            
            [_guidanceBtnCrew setBackgroundImage:greenButton forState:UIControlStateNormal];
            [_guidanceBtnCrew setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            
        }
        
        
    }
    
    
    if ([[_arrayName23 objectAtIndex:40] rangeOfString:@"newVersion"].location != NSNotFound ) {        
        
        for (int i = 0; i < [[_viewCustomFlightDataElements subviews] count]/2; i++) {            
            int customGuidanceItemID = 17 + i;
            UITextField *viewElement = (UITextField*)[_viewCustomFlightDataElements viewWithTag: customGuidanceItemID ]; 
            NSString *customGuidanceText = viewElement.text;
            //NSLog(@"%d = %@", customGuidanceItemID, customGuidanceText);            
            if ([[itemsGuidance objectAtIndex:customGuidanceItemID] isEqualToString:@"1"]) {                
                if ( customGuidanceText.length < 1) {
                    //[viewElement.text setBackgroundColor: yellowSpecialColor]; 
                    viewElement.backgroundColor = yellowSpecialColor;   
                    guidanceLegCheckOK = 0;
                }else{
                     viewElement.backgroundColor =GreenColor;
                }                
            }
        }
    }

    
    
    
    
     _labelGuidanceOAT.text =  [ [NSString alloc] initWithFormat:@"OAT: %.0fºC", OAT ];
     _labelGuidancePA.text =  [ [NSString alloc] initWithFormat:@"PA: %.0f""", Hp ];
    
     _labelGuidanceFuel.text =  [ [NSString alloc] initWithFormat:@"%@ %@", _labelSliderFuelMain.text, _labelFuelUnitMainTank.text];
    
    if (flagSpecialPHIFlightSettingPage == 1) {
        _labelGuidanceFuel.text =  [ [NSString alloc] initWithFormat:@"%@lb / %.0fGal", _labelSliderFuelMain.text, [_labelSliderFuelMain.text floatValue] / [_inputSpecificFuelMassPerVolume.text floatValue]  ] ;
        _labelGuidanceFuel.adjustsFontSizeToFitWidth = YES;   
    }
    
    
    if (guidanceLegCheckOK == 1) {
        _labelFlightLegID.backgroundColor = GreenColor;
        _labelFlightLegID.textColor = [UIColor blackColor];
        
    }else{
        _labelFlightLegID.backgroundColor = yellowSpecialColor;
        _labelFlightLegID.textColor = [UIColor blackColor];
        
    }
    
 
    
     [self addLegButtons];
    
}





- (IBAction)buttonActionLoadDispatcherFlights:(id)sender {
    
    [self loadDispatcherFlightsFromServer];
    
}
- (IBAction)switchAction:(id)sender {
    
    [self MainRoutine];

    
    
}
- (IBAction)actionCockpitSeatRight:(id)sender {
    
  
    
    
}

- (IBAction)actionCockpitSeatLeft:(id)sender {
    
    
    
   
}

- (IBAction)actionCockpitSeatSwap:(id)sender {
    
    NSString *previousLeft = _vCockpitSeatLeft.text;
    
    _vCockpitSeatLeft.text = _vCockpitSeatRight.text;
    
    _vCockpitSeatRight.text = previousLeft;
    
     [self MainRoutine];
    
    
}



- (void) calcLegTime {
    
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat: [_arrayName23 objectAtIndex: 38] ];
    
    
    int totalFlightTimeMinutes = 0;
    
    
    NSDate *startDate = [dateFormatter dateFromString: _labelDepartureTimeLocal.text  ];
    
    NSDate *endDate   = [dateFormatter dateFromString: _labellandingtimeLocal.text ];
    
    int minuteDifference = [endDate timeIntervalSinceDate:startDate] / 60.0;
    
    totalFlightTimeMinutes = totalFlightTimeMinutes + minuteDifference;
    
    legFlightTimeMinutes = totalFlightTimeMinutes;
    
    int hours = minuteDifference / 60;
    
    int minutes = minuteDifference - (hours * 60);
    
    
    
    
    NSString *flightTimeLeg =  [ [NSString alloc] initWithFormat:@"%.d", minuteDifference ];
    
    if (minutes >= 10)                  { flightTimeLeg =  [ [NSString alloc] initWithFormat:@"0%.d:%.d", hours, minutes ];  }
    
    if (minutes <= 9  & minutes > 0)    { flightTimeLeg =  [ [NSString alloc] initWithFormat:@"0%.d:0%.d", hours, minutes ];  }
    
    if (minutes <= 0)                   { flightTimeLeg =  [ [NSString alloc] initWithFormat:@"0%.d:00", hours ];}
    
    _labelGuidanceLegTime.text = flightTimeLeg;
    
    
    //NSLog(@"1 legFlightTimeMinutes %d", legFlightTimeMinutes);
    
    
   
    
    
}




- (IBAction)actionMoveTextfieldUp:(UITextField*)sender {
    
    return;
    /*
    if (flagIsLandscape == 0) {
        return;
    }    
    //NSLog(@"sender %d", sender.tag) ;
    
    float scrollViewOffsetPixel = _scrollViewLegData.contentOffset.y;    
    //NSLog(@"scrollViewOffsetPixel %f", scrollViewOffsetPixel);    
    
    float yLiftPixel = 0;    
    if (sender.tag == 1) { // MSA field        
        yLiftPixel = 339;        
    }    
    if (sender.tag == 2) { // MSA field        
        yLiftPixel = 639;        
    }    
    //NSLog(@"yLiftPixel %f", yLiftPixel) ;
    if (yLiftPixel < scrollViewOffsetPixel ) {
        yLiftPixel = scrollViewOffsetPixel;
    }    
    [_scrollViewLegData setContentOffset:CGPointMake(0, yLiftPixel) animated:YES];
    */
  

}

- (void) setConfigWindow {
    
    //NSLog(@"configMode %d", configMode);
    
    if (configMode == 0) {
        configMode = 1;
        _labelConfigurationName2.hidden= YES;
        _labelSEtotalWeight2.hidden = YES;
        _viewEquipmentOnHeli.userInteractionEnabled = YES;
        _scrollViewHeliCenter.userInteractionEnabled = NO;
        _viewLegData.hidden = YES;
        _viewPilotList.hidden = YES;
        
      
        float yGap = 40;
        
        if (flagIsLandscape == 1) {
            _viewHelicopterInCenter.userInteractionEnabled = NO;
            _viewConfigurator.frame  = CGRectMake( 0, 65, 1024, 1111 );
            _scrollViewConfiguratorItems.frame = CGRectMake( 450, 57, 570, 637 ) ;
            _viewConfiguratorStationItems.frame = CGRectMake(0, 0, 1024, arrayConfigItemName.count * yGap + 250);
            _buttonCloseInteriorConfigurator.frame = CGRectMake( 955, 5, 50, 50 ) ;
            [_scrollViewConfiguratorItems setContentSize:CGSizeMake(_scrollViewConfiguratorItems.frame.size.width, _viewConfiguratorStationItems.frame.size.height)];
            _viewConfiguratorTotals.frame  = CGRectMake( 0, 635, 1024, 60 );
            _viewCGLong.frame  = CGRectMake( 280, 140, 150, 150 );
            _viewCGlat.frame  = CGRectMake( 280, 380, 150, 100 );
        }else{
            _viewHelicopterInCenter.userInteractionEnabled = NO;
            _viewConfigurator.frame  = CGRectMake( 0, 65, 1024, 1411 );
            _scrollViewConfiguratorItems.frame = CGRectMake( 290, 57, 570, 1024 ) ;
            _viewConfiguratorStationItems.frame = CGRectMake(0, 0, 1024, arrayConfigItemName.count * yGap + 250);
            _buttonCloseInteriorConfigurator.frame = CGRectMake( 705, 5, 50, 50 ) ;
            [_scrollViewConfiguratorItems setContentSize:CGSizeMake(_scrollViewConfiguratorItems.frame.size.width, _viewConfiguratorStationItems.frame.size.height)];
            _trennerBottom.hidden = YES;
            _trennerVerticalBottom.hidden  = YES;
            _viewConfiguratorTotals.frame  = CGRectMake( -255, 890, 1024, 60 );
            _viewCGLong.frame  = CGRectMake( 62, 690, 150, 120 );
            _viewCGlat.frame  = CGRectMake( 62, 840, 150, 80 );
        }
        
        //NSLog(@"modeEquipListOrInterior %d", modeEquipListOrInterior);
        
        if (modeEquipListOrInterior == 3) {
             _viewCustomStationList.frame = CGRectMake(20, 77, 559, 1900);
            _viewConfiguratorStationItems.frame = CGRectMake(0, 0, 559, 1900);
            if (flagIsLandscape == 1) {        
                _scrollViewConfiguratorItems.frame = CGRectMake( 450, 57, 570, 637 ) ;       
                [_scrollViewConfiguratorItems setContentSize:CGSizeMake(_viewCustomStationList.frame.size.width, arrayCustomStations.count * 210)];
                
            }else{                
                _scrollViewConfiguratorItems.frame = CGRectMake( 202, 57, 570, 1024 ) ; 
                [_scrollViewConfiguratorItems setContentSize:CGSizeMake(_viewCustomStationList.frame.size.width, arrayCustomStations.count * 210)];
                            }

        }
        
        [self setHeliTopView];
       
        _viewEquipmentOnHeli.hidden = NO;
        _viewConfigurator.hidden = NO;
        _viewConfigurations.hidden = YES;
        _viewTrennerTop.hidden = YES;
        
        [viewMain bringSubviewToFront:_viewConfigurator];
        [viewMain bringSubviewToFront:_viewHelicopterInCenter];
        [viewMain bringSubviewToFront:_viewCGLong];
        [viewMain bringSubviewToFront:_viewCGlat];
        _viewHeliCenterLabels.userInteractionEnabled = NO;
        
      
        _viewLowerButtons.hidden = YES;
        _scrollViewTopDisplayButton.hidden = YES;
        _viewLegButtons.hidden = YES;
  
        _viewMeasureCGenvelope.frame  = CGRectMake( 0, 0, _viewCGLong.frame.size.width, _viewCGLong.frame.size.height );
        _viewCGenvelopeFrame.frame  = CGRectMake( 0, 0, _viewCGLong.frame.size.width, _viewCGLong.frame.size.height );
        _viewMeasureCGenvelope_LAT.frame  = CGRectMake( 0, 0, _viewCGlat.frame.size.width, _viewCGlat.frame.size.height );
        _viewFuelPathCG.frame  = CGRectMake( 0, 0, _viewCGLong.frame.size.width, _viewCGLong.frame.size.height );
        _viewFuelPathCGLat.frame  = CGRectMake( 0, 0, _viewCGlat.frame.size.width, _viewCGlat.frame.size.height );
        
      
        [self createListoItemsSlidersAndInterior];
        [self MainRoutine];
        
        if (modeEquipListOrInterior == 1) {
            [self createSpecialEquipListItems];
        }else if (modeEquipListOrInterior == 2) {
            [self createInteriorConfiguratorItems];
        }else{
             [self createAddStationPage];
        }
        
       
        if ( [[_arrayName23 objectAtIndex:32] isEqualToString:@"yes"]) { 
            _labelSpecialEquipConfigName.text = arrayConfigurations[configuration]; 
            if (flagSpecialPHIFlightSettingPage == 1) {
                _viewPHIEquipmentListSelection.hidden = YES;  
                if (modeEquipListOrInterior == 1) {
                    _viewPHIEquipmentListSelection.hidden = NO;  
                }
            }
        }
        
    }else{
        
        _labelConfigurationName2.hidden= NO;
        _labelSEtotalWeight2.hidden = NO;
        _viewEquipmentOnHeli.userInteractionEnabled = NO;
        _scrollViewHeliCenter.userInteractionEnabled = YES;
        for(UIView *subview in [_viewEquipmentOnHeli subviews]) {
            [subview removeFromSuperview];
        }
        _viewEquipmentOnHeli.hidden = YES;
        _viewHeliCenterLabels.userInteractionEnabled = YES;
        
        [self setHeliTopView];        
        if (flagIsLandscape) {
            [self sortForLandscape];
        }else{
             [self sortForPortrait];
        }
        
        if (flagReopenFlightSettings == 1) {
            flagReopenFlightSettings = 0;
            _viewLegData.hidden = NO;
            _viewConfigurations.hidden = YES;
            _viewPilotList.hidden = YES;
            [viewOne bringSubviewToFront:_viewLegData];
        }
    }
    
   
    
    

}


- (IBAction)actionShowEquiplistViewFromFlightSettings:(id)sender {
    
    flagReopenFlightSettings = 1;
    [self showEquiplistView];
}
- (IBAction)actionShowEquiplistView:(id)sender {
    
    [self showEquiplistView];
}
- (void) showEquiplistView {

    _viewConfiguratorStationItems.hidden = NO;
       guidanceDictionary[@"guidanceBtnSetEquipment"] =  @"ok";    
       modeEquipListOrInterior = 1;    
       [self setConfigWindow];    
       [self setCGenvelope];    
       [self MainRoutine];    
       viewEnvironment.hidden = YES;
       _viewUniversalExtras.hidden = YES;
       _viewLegData.hidden = YES;
}

- (IBAction)actionShowConfiguratorView:(id)sender {
    
    //NSLog(@"actionShowConfiguratorView");
    
    NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
    if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
    if ([userExtraCheck rangeOfString:@"allowCustomStationsButNotEditConfig"].location != NSNotFound  ) {  
        
        modeEquipListOrInterior = 3;    
        [self setConfigWindow];    
        [self setCGenvelope]; 
        [self createCustomStationList];  
        [self MainRoutine];
      
        
    }else{
        modeEquipListOrInterior = 2;    
        [self setConfigWindow];    
        [self setCGenvelope];    
        [self MainRoutine];
        
    }
          
   
    
    
    
}





- (void)actionTapAndHold:(UILongPressGestureRecognizer*)gesture {    
    //NSLog(@"1 actionTapAndHold ");
    if ( gesture.state == UIGestureRecognizerStateBegan ) {        
        //NSLog(@"btnHOLDidTransfer %d", btnHOLDidTransfer);        
        rideAlongSeat = btnHOLDidTransfer + 1300;
        [self setRideAlongValues];
    }    
}

- (void) setRideAlongValues {
      if (_viewPilotList.hidden == YES) {            
        //NSLog (@"rideAlongSeat %.0f ", rideAlongSeat);
        //NSLog (@"lineFreeLoad %.0f ", lineFreeLoad);                 
        _inputSeatWeight.text = [ [NSString alloc] initWithFormat:@"%.0f", [[_arrayName2 objectAtIndex: rideAlongSeat - 1300] floatValue] * factorApplyToNativeWeightforItems  ];     
        _inputSeatMaxWeight.text = [ [NSString alloc] initWithFormat:@"%.0f", [[_arrayName9 objectAtIndex: rideAlongSeat - 1300] floatValue] * factorApplyToNativeWeightforItems  ];
        _inputInstalledWeight.text = [ [NSString alloc] initWithFormat:@"%.0f", [[_arrayName17 objectAtIndex: rideAlongSeat - 1300] floatValue] * factorApplyToNativeWeightforItems  ];
                    
        _inputSeatArmLong.text = [ [NSString alloc] initWithFormat:@"%.0f", [[_arrayName3 objectAtIndex: rideAlongSeat - 1300] floatValue] * factorApplyToNativeDistanceInchMM ];
        _inputSeatArmLat.text = [ [NSString alloc] initWithFormat:@"%.0f", [[_arrayName5 objectAtIndex: rideAlongSeat - 1300] floatValue] * factorApplyToNativeDistanceInchMM]; 
              
        //NSLog( @"labelText %@", labelText);        
        _viewStationOptions.hidden = YES;
        _viewPilotList.hidden = NO; [viewOne bringSubviewToFront:_viewPilotList]; [viewOne bringSubviewToFront:viewTopTop];
                
        if ([[_arrayName14 objectAtIndex:rideAlongSeat - 1300]isEqualToString:@"-"] ) {
             _inputSeatName.text = [_arrayName7 objectAtIndex: rideAlongSeat - 1300];  
        }else{
             _inputSeatName.text = [_arrayName12 objectAtIndex: rideAlongSeat - 1300];            
        }
        previousSeatName = _inputSeatName.text;
        
        [_viewPilotList bringSubviewToFront:_viewSeatOptions]; _viewSeatOptions.hidden = NO;
          
          
          if ([[_arrayName9 objectAtIndex: rideAlongSeat - 1300] rangeOfString:@"fix"].location != NSNotFound  ) {
              _inputSeatMaxWeight.enabled = NO;  
              _inputSeatMaxWeight.backgroundColor = [UIColor darkGrayColor];
              
              
          }else{
              _inputSeatMaxWeight.enabled = YES;  
              _inputSeatMaxWeight.backgroundColor = [UIColor whiteColor];
          }
         
          
          NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
          if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
          
          //NSLog (@"rideAlongSeat userExtraCheck %@ ", userExtraCheck);
          
          NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];    
        
          
         
              
          if ([[_arrayName18 objectAtIndex:rideAlongSeat - 1300] isEqualToString:@"free"] || [userExtraCheck rangeOfString:@"allowAllStationsFree"].location != NSNotFound  || [customerFolderName isEqualToString:@"noAccount"] ) {
              _inputSeatArmLong.enabled = YES;              
              _inputSeatArmLat.enabled = YES;
              _inputSeatArmLong.backgroundColor = [UIColor whiteColor];
              _inputSeatArmLat.backgroundColor = [UIColor whiteColor];
          } else{
              _inputSeatArmLong.enabled = NO;
              _inputSeatArmLat.enabled = NO;
              _inputSeatArmLong.backgroundColor = [UIColor darkGrayColor];
              _inputSeatArmLat.backgroundColor = [UIColor darkGrayColor];
          }
          
    }else{
        _viewPilotList.hidden = YES;
    }
    
}


- (IBAction)actionSelectStationAlternate:(id)sender {
    
    // switch off the current station, switch on alternate
    // then re-create
    
    [_arrayName8 replaceObjectAtIndex:btnHOLDidTransfer withObject:@"0"];
    [_arrayName8 replaceObjectAtIndex:altenateLine withObject:@"1"];
    
    
    previousConfiguration = 999;
    
    
    
    int oldLine = btnHOLDidTransfer;
    int newLine = altenateLine;
    btnHOLDidTransfer = altenateLine;
    _labelSelectedStationName.text = [_arrayName1 objectAtIndex:btnHOLDidTransfer];
    _labelSelectedStationArmLong.text = [NSString stringWithFormat:@"%.0f mm",   [[_arrayName3 objectAtIndex:btnHOLDidTransfer]floatValue]   ];
    _labelSelectedStationArmLat.text = [NSString stringWithFormat:@"%.0f mm",   [[_arrayName5 objectAtIndex:btnHOLDidTransfer]floatValue]   ];
    altenateLine = [[_arrayName24 objectAtIndex:btnHOLDidTransfer]integerValue];
    _labelSelectedStationNameAlternate.text = [_arrayName1 objectAtIndex:altenateLine];
    _labelSelectedStationArmLongAlternate.text = [NSString stringWithFormat:@"%.0f mm",   [[_arrayName3 objectAtIndex:altenateLine]floatValue]   ];
    _labelSelectedStationArmLatAlternate.text = [NSString stringWithFormat:@"%.0f mm",   [[_arrayName5 objectAtIndex:altenateLine]floatValue]   ];
    
    
    //now move pax data from old to new station
    
    [_arrayName7 replaceObjectAtIndex:newLine withObject: [_arrayName7 objectAtIndex:oldLine] ];
    [_arrayName2 replaceObjectAtIndex:newLine withObject: [_arrayName2 objectAtIndex:oldLine] ];
    
    
    [self createListoItemsSlidersAndInterior];
    [self MainRoutine];
    [self MainRoutine];
    
    
    
}

-(void)actionTapOnStationHOLD:(id)sender{
    
    UIButton *btn = (UIButton*)sender;
    //NSLog(@"actionTapOnStationHold %d", btn.tag);
    btnHOLDidTransfer = btn.tag  - 1600;
    
    
}



-(void)actionTapOnStationStandby:(id)sender{
    
    //NSLog(@"actionTapOnStationStandby ");
    
    UIButton *btn = (UIButton*)sender;
    //NSLog(@"actionTapOnStationStandby %d", btn.tag);
    btnHOLDidTransfer = btn.tag  - 1600;
    
    _viewPilotList.hidden = NO;
    _inputSeatName.text = [_arrayName7 objectAtIndex:btnHOLDidTransfer  ]; _inputSeatWeight.text = [_arrayName2 objectAtIndex:btnHOLDidTransfer ];
    _viewSeatOptions.hidden = NO;
    [viewOne bringSubviewToFront:_viewPilotList];
    [_viewPilotList bringSubviewToFront:_viewSeatOptions];
    
    _viewStationOptionsList.hidden = NO;
    
    //[self setConfigWindow];
    
    [self createSeatOptionItems];

    
    
}

-(void)actionDoorOnOff:(id)sender{
    
    //NSLog(@"actionDoorOnOff ");
    
    UIButton *btn = (UIButton*)sender;
    //NSLog(@"actionTapOnStationStandby %d", btn.tag);
    btnHOLDidTransfer = btn.tag  - 1700;
    
    if ([[_arrayName8 objectAtIndex: btnHOLDidTransfer] floatValue] == 0) {
        [_arrayName8 replaceObjectAtIndex:btnHOLDidTransfer withObject:@"1"];
    }else{
        [_arrayName8 replaceObjectAtIndex:btnHOLDidTransfer withObject:@"0"];        
    }
    
    [self MainRoutine];
    
    
}




- (IBAction)actionCloseStationOptions:(id)sender {
    
    _viewStationOptionsList.hidden = YES;
    _viewPilotList.hidden = YES;
    
}


- (void) createSeatOptionItems {
    
    _stationTypeField.items   =  @[ @"Seat", @"Baggage", @"Standby"];
    
    _labelStationNameLong.text = [_arrayName1 objectAtIndex: btnHOLDidTransfer];
    
    if ([[_arrayName8 objectAtIndex: btnHOLDidTransfer] floatValue] == 0) {
        _segmentStationItemInOUT.selectedSegmentIndex = 0;
    }else{
        _segmentStationItemInOUT.selectedSegmentIndex = 1;
    }
    
    _inputStationInstallationWeight.text = [_arrayName17 objectAtIndex: btnHOLDidTransfer];
  
    
}


- (IBAction)actionStationInOutSingle:(id)sender {
    
    NSString *replacementItem;
    
    if ([_stationTypeField.text isEqualToString:@"Seat"]) {
        replacementItem = @"seat";
        
        _inputStationInstallationWeight.text = @"12";
    }
    if ([_stationTypeField.text isEqualToString:@"Baggage"]) {
        replacementItem = @"baggageBox";
        _inputStationInstallationWeight.text = @"5";
    }
    if ([_stationTypeField.text isEqualToString:@"Standby"]) {
        replacementItem = @"dashedBox";
    }
  
    
   
    if (_segmentStationItemInOUT.selectedSegmentIndex == 0) {
        [_arrayName8 replaceObjectAtIndex:btnHOLDidTransfer withObject:@"0"];
    }else{
        [_arrayName8 replaceObjectAtIndex:btnHOLDidTransfer withObject:@"1"];
    }    
    [_arrayName10 replaceObjectAtIndex:btnHOLDidTransfer withObject:replacementItem];    
    previousConfiguration = 999;
    [self createListoItemsSlidersAndInterior];
    [self MainRoutine];
    [self createSeatOptionItems];    
    
}

- (void) createAddStationPage {
 
    _viewConfiguratorStationItems.hidden = YES;
    _viewAddStation.hidden = NO;
    [_scrollViewConfiguratorItems bringSubviewToFront:_viewAddStation];
    _viewHelicopterInCenter.frame = CGRectMake(_viewHelicopterInCenter.frame.origin.x, _viewHelicopterInCenter.frame.origin.y, 400, _viewHelicopterInCenter.frame.size.height);
}

- (void) createInteriorConfiguratorItems {
    
    [_buttonOpenCustomStations setTitle:@"Edit Custom Stations" forState:UIControlStateNormal];    
    _viewConfiguratorStationItems.hidden = NO;
    _viewAddStation.hidden = YES;
    [_scrollViewConfiguratorItems bringSubviewToFront:_viewConfiguratorStationItems];    
    for(UIView *subview in [_viewConfiguratorStationItems subviews]) {
        [subview removeFromSuperview];
    }    
     _viewHelicopterInCenter.frame = CGRectMake(_viewHelicopterInCenter.frame.origin.x, _viewHelicopterInCenter.frame.origin.y, 400, _viewHelicopterInCenter.frame.size.height);    
    float yStart = 20;
    float xPos1 = 30;
    float yGap = 40;    
    int itemCount = -1;    
    int configStationsStart = [[_arrayName23 objectAtIndex:11] intValue];
    int configStationsEnd = [[_arrayName23 objectAtIndex:13] intValue];
    NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
    if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
        
    NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];    
    if ([customerFolderName isEqualToString:@"noAccount"]  || [customerFolderName isEqualToString:@"Tester"]  || [userExtraCheck rangeOfString:@"allowCustomStations"].location != NSNotFound ) {         
        configStationsStart = linePilot;
        configStationsEnd = lineZFW -1;        
    }
    
    for(int i =configStationsStart; i<configStationsEnd+1; i++) {        
        if (i == lineSeats) {
            continue;
        }        
        if (i == lineEquipment) {
            continue;
        }        
        itemCount = itemCount + 1;
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(xPos1 ,  yStart + (itemCount *yGap)  , 60, 35);
        [btn addTarget:self
                action:@selector(actionConfiguratorStationInOut:)
      forControlEvents:UIControlEventTouchUpInside];        
        btn.tag = i;        
        if ([[_arrayName2 objectAtIndex:i] floatValue] < 0) {            
            if ( [[_arrayName8 objectAtIndex:i] integerValue] == 0) {
                [btn setTitle: @"IN" forState: UIControlStateNormal];
                btn.backgroundColor = GreenColor;
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }else{
                [btn setTitle: @"OUT" forState: UIControlStateNormal];
                btn.backgroundColor = [UIColor redColor];
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }
        }else{            
            if ( [[_arrayName8 objectAtIndex:i] integerValue] == 0) {
                [btn setTitle: @"OUT" forState: UIControlStateNormal];
                btn.backgroundColor = [UIColor redColor];
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }else{
                [btn setTitle: @"IN" forState: UIControlStateNormal];
                btn.backgroundColor = GreenColor;
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }            
        }        
        [_viewConfiguratorStationItems addSubview: btn];
        
        // station name arrayName1
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake( xPos1 + 73 , yStart + (itemCount *yGap)  , 600, 35)];
        textField.borderStyle = UITextBorderStyleNone;
        textField.font = [UIFont boldSystemFontOfSize:16];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.textAlignment = NSTextAlignmentLeft;
        textField.enabled = NO;
        textField.backgroundColor = [UIColor clearColor];
        textField.textColor = [UIColor whiteColor];        
        [textField  setText: [[NSString alloc] initWithFormat:@"%@ - %@ ", [_arrayName12 objectAtIndex:i] ,  [_arrayName1 objectAtIndex:i] ]];        
        [_viewConfiguratorStationItems addSubview: textField];
        
    }    
    _viewConfiguratorStationItems.frame = CGRectMake(0, 0, 1024, itemCount * yGap + 250);
    [_scrollViewConfiguratorItems setContentSize:CGSizeMake(400, itemCount * 55)];
}



- (IBAction)actionConfiguratorStationInOut:(id)sender{
    
    
    //NSLog(@"actionConfiguratorStationInOut");
    
    UIButton *btn = (UIButton*)sender;
    int currentState = [[_arrayName8 objectAtIndex:btn.tag] intValue];
    
    // rule entire row:
    if (currentState == 0) {
        currentState = 1;
        [_arrayName8 replaceObjectAtIndex:btn.tag withObject:[[NSString alloc] initWithFormat:@"%d ", currentState]];
    }else{
        currentState = 0;
        [_arrayName8 replaceObjectAtIndex:btn.tag withObject:[[NSString alloc] initWithFormat:@"%d ", currentState]];
    }
    
    //check dependencies    
    //NSString *dependencyText = @"Med Floor_requiredFor_Med Carrier+Med Carrier_requiredFor_Patient+ECMO_kills_Backpack 1+Adapter Plate_requiredFor_Seat 4";//Backpack 1_requiredFor_ECMO
    
    NSString *dependencyText = @"";
    if (_arrayName25.count > 51) {    
        dependencyText = [_arrayName25 objectAtIndex:51]; //extra9    
    }
    
    if (dependencyText.length > 0) {
     
        NSCharacterSet*charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"+"];
        NSArray *arrayDependencies = [dependencyText componentsSeparatedByCharactersInSet:charSet1];
        
        for(int i=0; i<arrayDependencies.count; i++) {
            
            NSCharacterSet*charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"_"];
            NSArray *arrayDependencyItem = [[arrayDependencies objectAtIndex:i] componentsSeparatedByCharactersInSet:charSet1];
            NSString *dependFloor = [arrayDependencyItem objectAtIndex:0];
            NSString *connectedItemsText = @"";
            NSString *logicOperator = @"";
            NSString *dependTop = @"";
            
            
            //NSLog(@"dependFloor %@", dependFloor);
            //NSLog(@"logicOperator %@", logicOperator);
            
            
            
            //search to get the lines floor:
            int lineFloor = 0, lineTop = 0;
            
            if ([dependFloor isEqualToString:@"connectedAre"]) {                 
                //nothing needed
                connectedItemsText = [[arrayDependencies objectAtIndex:i] substringFromIndex:13]; 
                //NSLog(@"connectedItemsText %@", connectedItemsText);
                
                //we have a bunch of items that need to be synchonized
                //if one of them =1 then all = 1
                //NSLog(@"logicOperator %@", logicOperator);                
                NSCharacterSet*charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"_"];
                NSArray *arrayDependencyItem = [connectedItemsText componentsSeparatedByCharactersInSet:charSet1];
                //NSLog(@"arrayDependencyItem %@", arrayDependencyItem);                
                NSMutableArray *arrayItemsToSync = [[NSMutableArray alloc] init];                
                int lineItem = 0;                
                for (int i = 0; i < arrayDependencyItem.count  ; i++) {
                    for (int item = 3; item < lineZFW  ; item++) {
                        if ([[_arrayName1 objectAtIndex: item  ]  isEqualToString:[arrayDependencyItem objectAtIndex:i]]) {
                            lineItem = item;
                            [arrayItemsToSync addObject:[NSString stringWithFormat:@"%d",  item] ];
                            break;
                        }
                    }
                    
                }
                //NSLog(@"arrayItemsToSync %@", arrayItemsToSync);                
                //check if current item is one of them:
                int flagWeCanSwitch = 0;
                for (int i = 0; i < arrayItemsToSync.count  ; i++) {
                    if (btn.tag == [[arrayItemsToSync objectAtIndex:i]intValue]) {
                        flagWeCanSwitch = 1;
                    }
                }
                // now switch them all to status
                if (flagWeCanSwitch == 1) {
                    for (int i = 0; i < arrayItemsToSync.count  ; i++) {                                       
                        if (currentState == 0) {
                            [_arrayName8 replaceObjectAtIndex:[[arrayItemsToSync objectAtIndex:i]intValue] withObject:@"0"];                        
                        }else{
                            [_arrayName8 replaceObjectAtIndex:[[arrayItemsToSync objectAtIndex:i]intValue] withObject:@"1"];   
                        }
                        
                    }
                }
                
                
            }else{
                logicOperator = [arrayDependencyItem objectAtIndex:1]; 
                dependTop = [arrayDependencyItem objectAtIndex:2];
                for (int item = 3; item < lineZFW  ; item++) {
                    if ([[_arrayName1 objectAtIndex: item  ]  isEqualToString:dependFloor]) {
                        lineFloor = item;
                        break;
                    }
                }
                for (int item = 3; item < lineZFW  ; item++) {
                    if ([[_arrayName1 objectAtIndex: item  ]  isEqualToString:dependTop]) {
                        lineTop = item;
                        break;
                    }
                }
                
            }
            
            
            //NSLog(@"lineFloor %d", lineFloor);
            //NSLog(@"lineTop %d", lineTop);
            
            //requiredFor  **********************************************************************
            
            if ([logicOperator isEqualToString:@"requiredFor"]) {                
                if (lineTop == 0 || lineFloor == 0) {
                    //NSLog(@"error - no dependencies");
                }else{                
                    //NSLog(@"REQUIRED building if %@ at %d= 0, then  %@ at %d = 0 ", dependFloor, lineFloor, dependTop, lineTop);
                    //building principle! floor - carrier  & carrier - patient                
                    if ([[_arrayName8 objectAtIndex:lineFloor]floatValue] == 0) { //if floor == 0
                        //NSLog(@"replacing");
                        [_arrayName8 replaceObjectAtIndex:lineTop withObject:@"0"]; // then carrier == 0
                    }
                }                
            }
            
            
            
            
            
            if ([logicOperator isEqualToString:@"kills"]) {   
                
                if (lineTop == 0 || lineFloor == 0) {
                    //NSLog(@"error - no dependencies");
                }else{                
                    //NSLog(@"KILL if %@ at %d= 1, then  %@ at %d = 0 ", dependFloor, lineFloor, dependTop, lineTop);
                    //building principle! floor - carrier  & carrier - patient                
                    if ([[_arrayName8 objectAtIndex:lineFloor]floatValue] == 1) { //if ECMO == 1
                        //NSLog(@"replacing");
                        [_arrayName8 replaceObjectAtIndex:lineTop withObject:@"0"]; // then backpack1 == 0
                    }
                }                
            }
            
            
            if ([logicOperator isEqualToString:@"locks"]) { 
                if (lineTop == 0 || lineFloor == 0) {
                    //NSLog(@"error - no dependencies");
                }else{                
                    //NSLog(@"locks if %@ at %d= 1, then  %@ at %d = 0 ", dependFloor, lineFloor, dependTop, lineTop);                             
                    if ([[_arrayName8 objectAtIndex:lineFloor]floatValue] == 0) { //if backpack == 0
                        //NSLog(@"unlocking");
                        [_arrayName14 replaceObjectAtIndex:lineTop withObject:@"-"]; // then backpack1 == 0
                    }
                    
                    if ([[_arrayName8 objectAtIndex:lineFloor]floatValue] == 1) { //if backpack == 0
                        //NSLog(@"unlocking");
                        [_arrayName14 replaceObjectAtIndex:lineTop withObject:@"picAndLabelLocked"]; // then backpack1 == 0
                    }
                    
                }                
            }
            
            
            
            
            
            
            
            
            
            
        }        
    }
    
    
    previousConfiguration = 999;
    [self createListoItemsSlidersAndInterior];
    [self MainRoutine];
  
    [self createInteriorConfiguratorItems];
    
    _viewLegButtons.hidden = YES;
    _scrollViewTopDisplayButton.hidden = YES;
    
}

- (IBAction)actionExportSummaryAsPDF:(id)sender {
    
    
    [self createPDFDataFromSummary];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *fileNameSuffix = [NSString stringWithFormat:@"Leg Summary %@_%@.pdf",   displayHeliRegistration.text, timeStampForPDF ];
    if (_labelDepartureTimeLocal.text.length > 3) {
        fileNameSuffix = [NSString stringWithFormat:@"LM %@_%@.pdf",   displayHeliRegistration.text, _labelDepartureTimeLocal.text ];
    }
    
    //NSLog(@"fileNameSuffix  -%@- ", fileNameSuffix);
    
    NSString* fileName = [documentsDirectory stringByAppendingPathComponent:fileNameSuffix];
    [pdfData writeToFile:fileName atomically:YES];
    
    NSURL *url = [NSURL fileURLWithPath:fileName];
    
    //use the UIDocInteractionController API to get list of devices that support the file type
    docController = [UIDocumentInteractionController interactionControllerWithURL:url];
    
    
    //present a drop down list of the apps that support the file type, click an item in the list will open that app while passing in the file.
    
    // use this if view is where the button is
    //[docController presentOpenInMenuFromRect:[self.view convertRect:sender.frame fromView:sender.superview] inView:self.view animated:YES];
    
    //[docController presentOpenInMenuFromRect:[self.scrollViewSummaryManifest convertRect:self.scrollViewSummaryManifest.frame fromView:self.scrollViewSummaryManifest.superview] inView:self.view animated:YES];
    
    [docController presentOpenInMenuFromRect:CGRectZero inView:_scrollViewSummaryManifest animated:YES];

}


- (void)createPDFDataFromSummary {
    
    
    
    int pixelWidth = _scrollViewSummaryManifest.contentSize.width;
    int pixelHeight = summaryBoxHeight +290;  // set hight of pdf page here (cut off the bottom)
    
    pdfData = [NSMutableData data];
    
    UIGraphicsBeginPDFContextToData( pdfData, CGRectMake(0, 0, pixelWidth, pixelHeight),  nil );
    UIGraphicsBeginPDFPage();
    CGPoint savedContentOffset = _scrollViewSummaryManifest.contentOffset;
    CGRect savedFrame = _scrollViewSummaryManifest.frame;
    
    
    
    _scrollViewSummaryManifest.contentOffset = CGPointZero;
    _scrollViewSummaryManifest.frame = CGRectMake(0, 0, pixelWidth, pixelHeight);
    
    [_scrollViewSummaryManifest.layer renderInContext: UIGraphicsGetCurrentContext()];
    
    _scrollViewSummaryManifest.contentOffset = savedContentOffset;
    _scrollViewSummaryManifest.frame = savedFrame;
    
    UIGraphicsEndPDFContext();
    
    
}







- (IBAction)actionUseEnterPad:(UIButton*)sender {
    
    if (sender.tag == 1) {
        selectedItem = 30;
        calculatorscreen.text = @"" ; EnterPadString = @"";
        enterPad.hidden = NO; [viewOne bringSubviewToFront:enterPad]; flagButtonPressed = 1;
    }
    
}






- (IBAction)actionResetAllFlightsButton:(id)sender{
    
    UIButton *btn = (UIButton*)sender;
    
    buttonIDtransfer = btn.tag;
    
    if (flagLockReset == 1) {
        
        alertFlag = 1005;
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Not all flights sent."
                              message:@"Please send all load manifests via email."
                              delegate:self
                              cancelButtonTitle:@"Cancel"
                              
                              
                              otherButtonTitles:nil, nil];
        [alert show];

        
        
        
    }else{
        
        alertFlag = 1005;
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Reset All Flights"
                              message:@"This will delete all flights. Please Confirm"
                              delegate:self
                              
                              cancelButtonTitle:@"Cancel"
                              
                              
                              
                              otherButtonTitles:@"Reset All!", nil];
        [alert show];

        
        
        
    }
    
    
    
    
    
    
}


- (void) resetAllFlightsFromManager {
    
    //NSLog(@"resetAllFlightsFromManager");
    
    [allFlightsMasterArray removeAllObjects];    
    [allFlightsMasterArray addObject:@"-"];
    
    [arrayInternalFlightNumber removeAllObjects];
    [arrayInternalFlightNumber addObject:@"0"];
    [[NSUserDefaults standardUserDefaults]  setObject: arrayInternalFlightNumber  forKey:@"arrayInternalFlightNumber"];

    
    
    [[NSUserDefaults standardUserDefaults]  setObject: allFlightsMasterArray  forKey:@"allFlightsMasterArray"];   

    vLegID = @"1";
    vFlightID = @"0";
    flagMakeNewFlgtNow = 1;   
    
        
    [[NSUserDefaults standardUserDefaults]  setObject:@""  forKey:@"checkIfThisIsFirstFlight"];
    
    NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"]; 
    
    //NSLog(@"customerFolderName %@", customerFolderName);
    
    
    NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
    if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
    //NSLog(@"startup fetchAvailableProducts  userExtraCheck %@", userExtraCheck);  
    
    if ([customerFolderName isEqualToString:@"noAccount"]  || [userExtraCheck rangeOfString:@"flightSchoolPackage"].location != NSNotFound ) {         
        _viewSelectHelicopter.hidden = NO; [viewOne bringSubviewToFront:_viewSelectHelicopter];
        _viewFleetManager.hidden = NO;
        [viewOne bringSubviewToFront:_viewFleetManager];        
        NSNotification *myNotification = [NSNotification notificationWithName:@"notificationViewAircraftManager"
                                                                       object:self //object is usually the object posting the notification
                                                                     userInfo:nil]; //userInfo is an optional dictionary        
        //Post it to the default notification center
        [[NSNotificationCenter defaultCenter] postNotification:myNotification];   
        
    }else{
       
        _viewSelectHelicopter.hidden = NO; [viewOne bringSubviewToFront:_viewSelectHelicopter];
        _buttonCancelSelectAC.hidden = YES;
        if (flagSpecialPHIFlightSettingPage == 1) {
            _buttonCreateNewPHIFlight.hidden = NO;
            _buttonPHIcancelCreateFlight.hidden = YES;
        }
        
    }
   
    
}

- (void) deleteActiveFlightFromManager {
    
    [self SaveValues];
    
    //NSLog(@"actionDeleteFlightButton btn.tag %d ", btn.tag-100);
    
    [allFlightsMasterArray removeObjectAtIndex: [vFlightID integerValue] ];
    
    
    // look for new flight
    
    if ( [vFlightID intValue] >= (allFlightsMasterArray.count-1)  ) {
        
        vFlightID =  [ [NSString alloc] initWithFormat:@"%u", allFlightsMasterArray.count-1];
        
    }
    
    
    
    if ( [vFlightID intValue] == 0  ) {
        
        flagMakeNewFlgtNow = 1;
        _viewSelectHelicopter.hidden = NO; [viewOne bringSubviewToFront:_viewSelectHelicopter];
        
    }else{
        
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        [defaults  setObject: allFlightsMasterArray  forKey:@"allFlightsMasterArray"];

        [defaults  setObject: vFlightID                                     forKey:@"vFlightID"];
        
        vLegID = @"1";
        
        
        [self LoadValues];
        
        [self createFlightButtons];
        
        [self MainRoutine];
        
        
    }
    
    
    
}




- (IBAction)buttonActionImportEquipLocally:(id)sender {
    
  
    
    
    
}

- (IBAction)buttonActionExportEquip:(id)sender {
    
   }


- (IBAction)switchActionMainRoutine:(id)sender {
    
    [self MainRoutine];
}














- (void)actionSendPowerCheckEmail: (float)receivedTorque1  sendTorque2:(float)receivedTorque2 sendITT1:(float)receivedITT1 sendITT2:(float)receivedITT2 sendMaxITT1:(float)receivedMaxITT1 sendMaxITT2:(float)receivedMaxITT2  sendMargin1:(float)receivedMargin1  sendMargin2:(float)receivedMargin2 sendResult1:(NSString*)receivedResult1 sendResult2:(NSString*)receivedResult2 sendCheckType:(NSString*)receivedCheckType{

    
    
    _viewPowerCheck.hidden = NO;
    
    [self createTimeStampPowerCheck];
    
    [viewOne bringSubviewToFront: _viewPowerCheck]; [viewOne bringSubviewToFront:_viewLowerButtons];
    if (flagIsLandscape == 0) {
        _viewLowerButtons.center = CGPointMake( _viewLowerButtons.center.x , _viewLowerButtons.center.y - 46);
    }
    
    _pcPicName.text = [_arrayName7 objectAtIndex:linePilot];
    _pcAType.text = AC_Type;
    
    _pcTypeOfCheck.text = receivedCheckType;
    _pcRegistration.text =  vFlightRegistration.text;
    
    _pcTorque1.text = [NSString stringWithFormat:@"%.0f %%",receivedTorque1];
    _pcTorque2.text = [NSString stringWithFormat:@"%.0f %%",receivedTorque2];
    
    _pcITT1.text = [NSString stringWithFormat:@"%.0f ºC",receivedITT1];
    _pcITT2.text = [NSString stringWithFormat:@"%.0f ºC",receivedITT2];
    
    _pcMaxITT1.text = [NSString stringWithFormat:@"%.0f ºC",receivedMaxITT1];
    _pcMaxITT2.text = [NSString stringWithFormat:@"%.0f ºC",receivedMaxITT2];
    
    _pcMMarginITT1.text = [NSString stringWithFormat:@"%.0f ºC",receivedMargin1];
    _pcMMarginITT2.text = [NSString stringWithFormat:@"%.0f ºC",receivedMargin2];
    
    _pcResult1.text = receivedResult1;
    _pcResult2.text = receivedResult2;
    
    
    
    
    
   if ([_pcResult1.text rangeOfString:@"OK"].location != NSNotFound     ) {
       _pcResult1.textColor = [UIColor blackColor];
   }else{
       _pcResult1.textColor = [UIColor redColor];
   }
    
    if ([_pcResult2.text rangeOfString:@"OK"].location != NSNotFound     ) {
        _pcResult2.textColor = [UIColor blackColor];
    }else{
        _pcResult2.textColor = [UIColor redColor];
    }
    
    
}




- (IBAction)actionClosePowerCheck:(id)sender {
    
    _viewPowerCheck.hidden = YES;
}


- (void) createTimeStampPowerCheck {
    
    // Get current  time
    NSDate *currentDateTime = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    NSTimeZone *localTZ = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTZ];
    NSString *localTime = [dateFormatter stringFromDate:currentDateTime];
    [dateFormatter setDateFormat:@"MM"];    NSString *dateMonth = [dateFormatter stringFromDate:currentDateTime];
    [dateFormatter setDateFormat:@"dd"];    NSString *dateDay = [dateFormatter stringFromDate:currentDateTime];
    [dateFormatter setDateFormat:@"yyyy"];  NSString *dateYear = [dateFormatter stringFromDate:currentDateTime];
    
    if ( [[_arrayName23 objectAtIndex:5] isEqualToString:@"US"]) {
        // US
        _pcDate.text = [NSString stringWithFormat:@"%@ / %@.%@.%@",  localTime, dateMonth, dateDay, dateYear];
    }else{
        // EU
        _pcDate.text = [NSString stringWithFormat:@"%@/%@.%@",  vFlightRegistration.text, dateDay, dateMonth];
    }
    
}

- (IBAction)actionSendPowerCheck:(id)sender {
    
    //NSLog(@"statusSignature %.0f ", statusSignature);
    //NSLog(@"ScrollViewManifest.subviews.count  %d ", ScrollViewManifest.subviews.count);
    [self sendPowerCheckViaEmail];
}



- (void) sendPowerCheckViaEmail {
    
    
    int pixelWidth = _ScrollViewPowerCheck.contentSize.width;
    int pixelHeight = _ScrollViewPowerCheck.contentSize.height;  // set hight of pdf page here (cut off the bottom)
    
    //NSLog(@"pixelWidth %d ", pixelWidth);
    //NSLog(@"pixelHeight %d ", pixelHeight);
    
    pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData( pdfData, CGRectMake(0, 0, pixelWidth, pixelHeight),  nil );
    UIGraphicsBeginPDFPage();
    CGPoint savedContentOffset = _ScrollViewPowerCheck.contentOffset;
    CGRect savedFrame = _ScrollViewPowerCheck.frame;
    
    _ScrollViewPowerCheck.contentOffset = CGPointZero;
    _ScrollViewPowerCheck.frame = CGRectMake(0, 0, pixelWidth, pixelHeight);
    
    [_ScrollViewPowerCheck.layer renderInContext: UIGraphicsGetCurrentContext()];
    
    _ScrollViewPowerCheck.contentOffset = savedContentOffset;
    _ScrollViewPowerCheck.frame = savedFrame;
    
    UIGraphicsEndPDFContext();
    
    MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
    
    [composer setMailComposeDelegate: self];
    NSString *MailSubject     = [NSString stringWithFormat:@"Power Assurance Check %@, %@   ", vFlightRegistration.text  , _pcDate.text ];
    
    [composer setToRecipients:[NSArray arrayWithObjects: _defaultEmailAddress.text , nil]];
    [composer setCcRecipients:[NSArray arrayWithObjects: _defaultEmailAddressCC.text , nil]];
    
    [composer setSubject: MailSubject];
    [composer setMessageBody:@"Power Check attached as PDF document"  isHTML:NO];
    [composer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    
    [composer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:[NSString stringWithFormat:@"%@.pdf",  vFlightRegistration.text]];
    //[composer addAttachmentData:pdfData2 mimeType:@"application/pdf" fileName:[NSString stringWithFormat:@"Med. Equip. List.pdf"]];
    
    [self presentModalViewController:composer animated:YES];
    
    
}




- (IBAction)actionToggleStationEquipmentConfigurator:(id)sender {
    
    if (_scrollViewInteriorMaker.hidden == YES) {
        _scrollViewInteriorMaker.hidden = NO; [_viewConfigurator bringSubviewToFront: _scrollViewInteriorMaker];
        _scrollViewConfiguratorItems.hidden = YES;
        _viewCGLong.hidden = YES;
        _viewCGlat.hidden = YES;
        _viewConfiguratorTotals.hidden = YES;
        _buttonRefreshInterior.hidden = NO;
        
        [self createInteriorMakerItems];
    }else{
        _scrollViewConfiguratorItems.hidden = NO; [_viewConfigurator bringSubviewToFront: _scrollViewConfiguratorItems];
        _scrollViewInteriorMaker.hidden = YES;
        _viewCGLong.hidden = NO;
        _viewCGlat.hidden = NO;
        _viewConfiguratorTotals.hidden = NO;
        _buttonRefreshInterior.hidden = YES;
        [_viewConfigurator bringSubviewToFront:_viewConfiguratorTotals];
    }
    
}

- (IBAction)actionRefreshInterior:(id)sender {
    
    
    
    for(int i =4; i<lineZFW; i++) {
        
        //NSLog(@"i %d", i);
        
        if ([[_arrayName1 objectAtIndex:i] isEqualToString:@"Seats"] || [[_arrayName1 objectAtIndex:i] isEqualToString:@"Equipment"] || [[_arrayName1 objectAtIndex: i  ] isEqualToString:@"Seats/Equip."] ) {
            continue;
        }
        
        
        NSString *text;
        
        UITextField *textField = [[UITextField alloc] init];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 1  ]; text = textField.text;
        
        
        //NSLog(@"text  %@", text);
        
        
        
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 1  ]; text = textField.text;
        [_arrayName1 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 2  ]; text = textField.text;
        [_arrayName2 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 3  ]; text = textField.text;
        [_arrayName3 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 4  ]; text = textField.text;
        [_arrayName4 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 5  ]; text = textField.text;
        [_arrayName5 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 6  ]; text = textField.text;
        [_arrayName6 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 7  ]; text = textField.text;
        [_arrayName7 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 8  ]; text = textField.text;
        [_arrayName8 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 9  ]; text = textField.text;
        [_arrayName9 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 10  ]; text = textField.text;
        [_arrayName10 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 11  ]; text = textField.text;
        [_arrayName11 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 12  ]; text = textField.text;
        [_arrayName12 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 13  ]; text = textField.text;
        [_arrayName13 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 14  ]; text = textField.text;
        [_arrayName14 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 15  ]; text = textField.text;
        [_arrayName15 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 16  ]; text = textField.text;
        [_arrayName16 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 17  ]; text = textField.text;
        [_arrayName17 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 18  ]; text = textField.text;
        [_arrayName18 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 19  ]; text = textField.text;
        [_arrayName19 replaceObjectAtIndex:i withObject:text];
        textField = (UITextField *)[ _viewInteriorMakerItems viewWithTag: i * 100 + 20  ]; text = textField.text;
        [_arrayName20 replaceObjectAtIndex:i withObject:text];
        
    }
    
  
    
    previousConfiguration = 999;
    [self createListoItemsSlidersAndInterior];
    [self MainRoutine];
    
}

- (void) createInteriorMakerItems {
    
    
    NSMutableArray *arrayItems = [[NSMutableArray alloc] init];
    
    [arrayItems addObject:@"-"];
    [arrayItems addObject:@"Station Name"];
    [arrayItems addObject:@"Seat Label"];
    [arrayItems addObject:@"On/Off"];
    [arrayItems addObject:@"Weight"];
    [arrayItems addObject:@"Long Arm"];
    [arrayItems addObject:@"Lat Arm"];
    [arrayItems addObject:@"Long Mom."];
    [arrayItems addObject:@"Lat Mom."];
    [arrayItems addObject:@"Occupant"];
    [arrayItems addObject:@"Max Weight"];
    [arrayItems addObject:@"Symbol"];
    [arrayItems addObject:@"Long. Offset"];
    [arrayItems addObject:@"Lat Offset"];
    [arrayItems addObject:@"Specials"];
    [arrayItems addObject:@"Rotation"];
    [arrayItems addObject:@"L/R/Crew"];
    [arrayItems addObject:@"Item Weight"];
    [arrayItems addObject:@"Arm (if diff)"];
    [arrayItems addObject:@"Sym. Width"];
    [arrayItems addObject:@"Sym. Height"];
    
    //NSLog(@"createInteriorMakerItems");
    
    for(UIView *subview in [_viewInteriorMakerItems subviews]) {
        [subview removeFromSuperview];
    }
    
    
    float yStart = 20;
    float xPos1 = 10;
    float yGap = 70;
    float xGap = 10;
    float cellWidth = 90;
    float secondLineGap = 30;
    
    int itemCount = -1;
    
    float formerXpos =0;
    float formerWidth = 0;
    
    
    _viewInteriorMakerItems.frame = CGRectMake(0, 0, 2800, 2500);
    
    for(int i =4; i<lineZFW; i++) {
        
        if ([[_arrayName1 objectAtIndex:i] isEqualToString:@"Seats"] || [[_arrayName1 objectAtIndex:i] isEqualToString:@"Equipment"] || [[_arrayName1 objectAtIndex: i  ] isEqualToString:@"Seats/Equip."]) {
            continue;
        }
        
        itemCount = itemCount + 1;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake( xPos1 , yStart + (itemCount *yGap)  , 150, 35)];
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor lightGrayColor];
        [label  setText: [[NSString alloc] initWithFormat:@"%@", [arrayItems objectAtIndex:1] ] ];
        [_viewInteriorMakerItems addSubview: label];
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake( xPos1 , yStart + (itemCount *yGap) + secondLineGap  , 150, 35)];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:15];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.textAlignment = NSTextAlignmentLeft;
        textField.enabled = YES;
        textField.backgroundColor = [UIColor darkGrayColor];
        textField.textColor = [UIColor whiteColor];
        [textField  setText: [[NSString alloc] initWithFormat:@"%@", [_arrayName1 objectAtIndex:i] ] ];
        textField.tag = i*100 + 1;
        [textField addTarget:self
                      action:@selector(actionRefreshInterior:)
            forControlEvents:UIControlEventEditingDidEndOnExit];
        [_viewInteriorMakerItems addSubview: textField];
        
        
        formerXpos = label.frame.origin.x;
        formerWidth = label.frame.size.width;
        
        for(int arrayItem =2; arrayItem<arrayItems.count; arrayItem++) {
            
            label = [[UILabel alloc] initWithFrame:CGRectMake( formerXpos +  formerWidth + xGap, yStart + (itemCount *yGap)  , cellWidth, 35)];
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor lightGrayColor];
            [label  setText: [[NSString alloc] initWithFormat:@"%@", [arrayItems objectAtIndex:arrayItem] ] ];
            [_viewInteriorMakerItems addSubview: label];
            
            // get item from array
            
            NSString *itemText;
            
            if (arrayItem == 2) {  itemText = [_arrayName2 objectAtIndex:i];   }
            if (arrayItem == 3) {  itemText = [_arrayName3 objectAtIndex:i];   }
            if (arrayItem == 4) {  itemText = [_arrayName4 objectAtIndex:i];   }
            if (arrayItem == 5) {  itemText = [_arrayName5 objectAtIndex:i];   }
            if (arrayItem == 6) {  itemText = [_arrayName6 objectAtIndex:i];   }
            if (arrayItem == 7) {  itemText = [_arrayName7 objectAtIndex:i];   }
            if (arrayItem == 8) {  itemText = [_arrayName8 objectAtIndex:i];   }
            if (arrayItem == 9) {  itemText = [_arrayName9 objectAtIndex:i];   }
            if (arrayItem == 10) {  itemText = [_arrayName10 objectAtIndex:i];   }
            if (arrayItem == 11) {  itemText = [_arrayName11 objectAtIndex:i];   }
            if (arrayItem == 12) {  itemText = [_arrayName12 objectAtIndex:i];   }
            if (arrayItem == 13) {  itemText = [_arrayName13 objectAtIndex:i];   }
            if (arrayItem == 14) {  itemText = [_arrayName14 objectAtIndex:i];   }
            if (arrayItem == 15) {  itemText = [_arrayName15 objectAtIndex:i];   }
            if (arrayItem == 16) {  itemText = [_arrayName16 objectAtIndex:i];   }
            if (arrayItem == 17) {  itemText = [_arrayName17 objectAtIndex:i];   }
            if (arrayItem == 18) {  itemText = [_arrayName18 objectAtIndex:i];   }
            if (arrayItem == 19) {  itemText = [_arrayName19 objectAtIndex:i];   }
            if (arrayItem == 20) {  itemText = [_arrayName20 objectAtIndex:i];   }
            
            int xPos = 0;
            
            if (arrayItem == 12) {  xPos = 170;   };
            if (arrayItem == 8) {  xPos = 270;   };
            if (arrayItem == 2) {  xPos = 370;   };
            if (arrayItem == 3) {  xPos = 470;   };
            if (arrayItem == 5) {  xPos = 570;   };
            if (arrayItem == 4) {  xPos = 670;   };
            if (arrayItem == 6) {  xPos = 770;   };
            if (arrayItem == 7) {  xPos = 870;   };
            if (arrayItem == 9) {  xPos = 970;   };
            if (arrayItem == 10) {  xPos = 1070;   };
            if (arrayItem == 11) {  xPos = 1170;   };
            if (arrayItem == 13) {  xPos = 1270;   };
            if (arrayItem == 14) {  xPos = 1370;   };
            if (arrayItem == 15) {  xPos = 1470;   };
            if (arrayItem == 16) {  xPos = 1570;   };
            if (arrayItem == 17) {  xPos = 1670;   };
            if (arrayItem == 18) {  xPos = 1770;   };
            if (arrayItem == 19) {  xPos = 1870;   };
            if (arrayItem == 20) {  xPos = 1970;   };
            
            
            
            
            
            //textField = [[UITextField alloc] initWithFrame:CGRectMake( formerXpos +  formerWidth + xGap , yStart + (itemCount *yGap) + secondLineGap , cellWidth, 35)];
            
            textField = [[UITextField alloc] initWithFrame:CGRectMake( xPos , yStart + (itemCount *yGap) + secondLineGap , cellWidth, 35)];
            
            
            
            textField.borderStyle = UITextBorderStyleRoundedRect;
            textField.font = [UIFont systemFontOfSize:15];
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            textField.textAlignment = NSTextAlignmentLeft;
            textField.enabled = YES;
            textField.backgroundColor = [UIColor darkGrayColor];
            textField.textColor = [UIColor whiteColor];
            [textField  setText: [[NSString alloc] initWithFormat:@"%@", itemText] ];
            textField.tag = i*100 + arrayItem;
            [textField setKeyboardType:UIKeyboardTypeNumberPad];
            [textField addTarget:self
                          action:@selector(actionRefreshInterior:)
                forControlEvents:UIControlEventEditingDidEndOnExit];
            [_viewInteriorMakerItems addSubview: textField];
            
            formerXpos = label.frame.origin.x;
            formerWidth = label.frame.size.width;
            
            
        }
        
        
        
        
        
        
        
    }
    
    
    
    [_scrollViewInteriorMaker setContentSize:CGSizeMake(2200, itemCount * 90)];
    
}



- (IBAction)actionCloseSecrectACsettings:(id)sender {
    
    _switchAdjustACTopView.on = NO;
    
    [self MainRoutine];
}

- (IBAction)actionSegmentUnits:(id)sender {
    [self convertWeightUnits];
   
    [self createListoItemsSlidersAndInterior];
    [self setCGenvelope];
    [self MainRoutine];
    [self copyLabelsManifest];
}

- (void) convertWeightUnits {
    
    //NSLog(@"convertWeightUnits");    
    NSString *previousSelectedUnitForItems = selectedUnitForItems;    
    if (_segmentUnitsForItems.selectedSegmentIndex == 0) {
        selectedUnitForItems = @"kg";
    }else{
        selectedUnitForItems = @"lbs";
    }
    if (_segmentUnitsForFuel.selectedSegmentIndex == 0) {
        selectedUnitForFuel = @"kg";
    }else{
        selectedUnitForFuel = @"lbs";
    }
    
   
    //NSLog(@"selectedUnitForFue %@", selectedUnitForFuel);
    //NSLog(@"selectedUnitForItems %@", selectedUnitForItems);
    //NSLog(@"previousSelectedUnitForItems %@", previousSelectedUnitForItems);
    //NSLog(@"selectedUnitForItems %@", selectedUnitForItems);
 
     //NSLog(@"1 _inputQuickLoadPreset.text %@", _inputQuickLoadPreset.text);
    
    if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"forceUnitLBS"].location != NSNotFound ) {
         _inputQuickLoadPreset.text = [ [NSString alloc] initWithFormat:@"%.0f", [[_arrayName21 objectAtIndex: 33 ]floatValue] * 2.2046 ];        
        float toRound =  [_inputQuickLoadPreset.text floatValue] ;        
        int dummy = toRound / 10;        
        toRound =  (dummy * 10)+10;
        _inputQuickLoadPreset.text = [ [NSString alloc] initWithFormat:@"%.0f",toRound ];
        
    }
    
    if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"forceUnitKG"].location != NSNotFound ) {
        _inputQuickLoadPreset.text = [ [NSString alloc] initWithFormat:@"%.0f", [[_arrayName21 objectAtIndex: 33 ]floatValue] / 2.2046 ];        
        float toRound =  [_inputQuickLoadPreset.text floatValue] ;        
        int dummy = toRound / 10;        
        toRound =  (dummy * 10)+10;
        _inputQuickLoadPreset.text = [ [NSString alloc] initWithFormat:@"%.0f",toRound ];        
    }
    
    
    
    if ([previousSelectedUnitForItems isEqualToString:@"lbs"] & [selectedUnitForItems isEqualToString:@"kg"]) {   
        //NSLog(@"1 convertWeightUnits");  
        float toRound =  [_inputQuickLoadPreset.text floatValue] / 2.2046;        
        int dummy = toRound / 10;        
        toRound =  (dummy * 10)+10;
        _inputQuickLoadPreset.text = [ [NSString alloc] initWithFormat:@"%.0f",toRound ];
    }
    if ([previousSelectedUnitForItems isEqualToString:@"kg"] & [selectedUnitForItems isEqualToString:@"lbs"]) {
        //NSLog(@"2 convertWeightUnits");  
        float toRound =  [_inputQuickLoadPreset.text floatValue] * 2.2046;        
        int dummy = toRound / 10;        
        toRound =  (dummy * 10)-10;
        _inputQuickLoadPreset.text = [ [NSString alloc] initWithFormat:@"%.0f", toRound ];
    }
    
    
   
    
    
     [self setUnitConversionFactors]; 
    
  //NSLog(@"2 _inputQuickLoadPreset.text %@", _inputQuickLoadPreset.text);
    
    //NSLog(@"2 selectedUnitForFue %@", selectedUnitForFuel);
    //NSLog(@"2 selectedUnitForItems %@", selectedUnitForItems);
    
    
}


- (IBAction)actionConvertFuelFlow:(id)sender {
    
    //NSLog(@"actionConvertFuelFlow");
    
    
    NSString *previousFuelEnterMode = fuelEnterMode;
    
    
    if (_segmentFuelVolumeOrMass.selectedSegmentIndex == 0) {
        [_arrayName21 replaceObjectAtIndex:24 withObject:@"volume"];
        fuelEnterMode = @"volume";
    }else{
        [_arrayName21 replaceObjectAtIndex:24 withObject:@"mass"];
        fuelEnterMode = @"mass";
    }
    
    flagDoNotResetFuelFlow = 1;
    
    float internalSpecificFuelMassPerVolume = 0;
    
    if ([fuelUnits isEqualToString:selectedUnitForFuel] ) { 
        //convert lbs/Gal to kg/liter            
        internalSpecificFuelMassPerVolume = [_inputSpecificFuelMassPerVolume.text floatValue] ;          
    }
    
    if ([fuelUnits isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) { 
        //convert lbs/Gal to kg/liter            
        internalSpecificFuelMassPerVolume =  ([_inputSpecificFuelMassPerVolume.text floatValue] / 2.2046 ) / 3.78541;            
    }
    
    if ([fuelUnits isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) { 
        
        //convert lbs/Gal to kg/liter            
        internalSpecificFuelMassPerVolume =  ([_inputSpecificFuelMassPerVolume.text floatValue] * 2.2046 ) * 3.78541;            
    }
   
     //NSLog(@"internalSpecificFuelMassPerVolume %.2f", internalSpecificFuelMassPerVolume);
    
    //NSLog(@"1");
    if ([selectedUnitForFuel isEqualToString:@"lbs"] ) {
        //NSLog(@"2");
         if ([previousFuelEnterMode isEqualToString:@"mass"] & [fuelEnterMode isEqualToString:@"volume"]) {
             //NSLog(@"3");
              inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.2f", [inputFuelFlowOverride.text floatValue] / internalSpecificFuelMassPerVolume ];
             //from lbs to gallons
              calculatePerformanceClass_.cruiseInputFuelFlow.text = [ [NSString alloc] initWithFormat:@"%.1f", [calculatePerformanceClass_.cruiseInputFuelFlow.text floatValue] / internalSpecificFuelMassPerVolume ];
         }
        
        if ([previousFuelEnterMode isEqualToString:@"volume"] & [fuelEnterMode isEqualToString:@"mass"]) {
            //NSLog(@"4");
            inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.2f", [inputFuelFlowOverride.text floatValue] * internalSpecificFuelMassPerVolume ];            
            //from gallons to lbs
            calculatePerformanceClass_.cruiseInputFuelFlow.text = [ [NSString alloc] initWithFormat:@"%.1f", [calculatePerformanceClass_.cruiseInputFuelFlow.text floatValue] * internalSpecificFuelMassPerVolume ];
        }
    }else{
        
        if ([previousFuelEnterMode isEqualToString:@"mass"] & [fuelEnterMode isEqualToString:@"volume"]) {
            //NSLog(@"5");
            // from kg to liter
            inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.2f", [inputFuelFlowOverride.text floatValue] / internalSpecificFuelMassPerVolume ];            
            calculatePerformanceClass_.cruiseInputFuelFlow.text = [ [NSString alloc] initWithFormat:@"%.1f", [calculatePerformanceClass_.cruiseInputFuelFlow.text floatValue] / internalSpecificFuelMassPerVolume ];
        }
        
        
        if ([previousFuelEnterMode isEqualToString:@"volume"] & [fuelEnterMode isEqualToString:@"mass"]) {
            //NSLog(@"7");
            inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.2f", [inputFuelFlowOverride.text floatValue] * internalSpecificFuelMassPerVolume ];            
            //from liter to kilo
             calculatePerformanceClass_.cruiseInputFuelFlow.text = [ [NSString alloc] initWithFormat:@"%.1f", [calculatePerformanceClass_.cruiseInputFuelFlow.text floatValue] * internalSpecificFuelMassPerVolume ];
        }
    }
    
  

    //NSLog(@"inputFuelFlowOverride.text %@", inputFuelFlowOverride.text);
  
    if (flagCreateFuelPage == 1) {
        [self createFuelPage];
    }
    
 
    [self MainRoutine];
    
}


- (IBAction)actionSegmentFuelUnits:(id)sender {
    
    [self convertFuelUnits];
    
    [self createListoItemsSlidersAndInterior];
    [self setCGenvelope];  
    if (flagCreateFuelPage == 1) {
        [self createFuelPage];
    }
    [self MainRoutine];
    [self copyLabelsManifest];
}

- (void) convertFuelUnits {
    
    //NSLog(@"convertFuelUnits");

    NSString *previousSelectedUnitForFuel = selectedUnitForFuel;    
    if (_segmentUnitsForFuel.selectedSegmentIndex == 0) {
        selectedUnitForFuel = @"kg";
    }else{
        selectedUnitForFuel = @"lbs";
    }
    
    /*
    if ([selectedUnitForFuel isEqualToString:@"lbs"]) {       
        //NSArray *itemArray = [NSArray arrayWithObjects: @"Enter Fuel in Gallons", @"Enter Fuel in lbs",  nil];
        //_segmentFuelVolumeOrMass = [[UISegmentedControl alloc] initWithItems:itemArray];
        //NSLog(@"2 convertFuelUnits");
        [self.segmentFuelVolumeOrMass setTitle:@"Love It" forSegmentAtIndex:0];
        [self.segmentFuelVolumeOrMass setTitle:@"Love It NOT" forSegmentAtIndex:1];
        _segmentFuelVolumeOrMass.hidden = YES;
        
    }else{     
        NSArray *itemArray = [NSArray arrayWithObjects: @"Enter Fuel in Liter", @"Enter Fuel in Kilo",  nil];
        _segmentFuelVolumeOrMass = [[UISegmentedControl alloc] initWithItems:itemArray];
    }
     */
    
    [self setUnitConversionFactors];
    // convert fuel flow
    if ([fuelEnterMode isEqualToString:@"mass"] ) {    
        
        if ([previousSelectedUnitForFuel isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) {
            //NSLog(@"mass lbs to kg");
            inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.2f", [inputFuelFlowOverride.text floatValue] / 2.2046 ];
        }         
        if ([previousSelectedUnitForFuel isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) {
            //NSLog(@"kg to punds");
            inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.2f", [inputFuelFlowOverride.text floatValue] * 2.2046 ];
        }         
    }else{  
        
        if ([previousSelectedUnitForFuel isEqualToString:@"lbs"] & [selectedUnitForFuel isEqualToString:@"kg"]) {
            //NSLog(@"volume gal to liter");
            inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.2f", [inputFuelFlowOverride.text floatValue] * 3.78541 ];
            //NSLog(@"1 inputFuelFlowOverride.text  %@", inputFuelFlowOverride.text );
        }
        if ([previousSelectedUnitForFuel isEqualToString:@"kg"] & [selectedUnitForFuel isEqualToString:@"lbs"]) {
            //NSLog(@"volume liter to gal inputFuelFlowOverride.text %@", inputFuelFlowOverride.text);
            //NSLog(@"_inputSpecificFuelMassPerVolume  %@", _inputSpecificFuelMassPerVolume.text );
                        
            if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"forceUnitKG"].location != NSNotFound ) {               
                if ([specialdata2 rangeOfString:@"GALLONS"].location != NSNotFound ) {
                    //input in pounds -- convert to gallons
                    inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.2f", [inputFuelFlowOverride.text floatValue] / [_inputSpecificFuelMassPerVolume.text floatValue] ]; 
                }
                if ([specialdata2 rangeOfString:@"POUNDS"].location != NSNotFound ) {
                    //input in pounds -- convert to gallons
                    //inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.2f", [inputFuelFlowOverride.text floatValue] / [_inputSpecificFuelMassPerVolume.text floatValue] ]; 
                }
                
                //NSLog(@"1 inputFuelFlowOverride  %@", inputFuelFlowOverride.text);
                
            }else{                
                inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.2f", [inputFuelFlowOverride.text floatValue] / 3.78541]; // liter in gal: lite in kg,  kg in lbs   
                 //NSLog(@"2 inputFuelFlowOverride  %@", inputFuelFlowOverride.text);
            }
        }
        
        
        if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"forceUnitKG"].location != NSNotFound ) {             
            //if selected is kg and original units is lbs we need to convert Gallons to liters!
            if ([selectedUnitForFuel isEqualToString:@"kg"] && [[_arrayName21 objectAtIndex:15 ]isEqualToString:@"lbs"] ) {
                inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.2f", [inputFuelFlowOverride.text floatValue] * 3.78541];                 
                 //NSLog(@"3 inputFuelFlowOverride  %@", inputFuelFlowOverride.text);
            }
            
        }
    }

    if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"fuelFlow"].location != NSNotFound ) {  
    [self overrideFuelFlowFromSpecialData];
    }
      

    
   
}


- (void) overrideSledWeightFromSpecialData {
    
    NSRange range = [specialdata2 rangeOfString:@"sledWeight"];        
    NSString *codeItem =  [specialdata2 substringWithRange:NSMakeRange(range.location+11, 3)]; 
    _inputPHIOverrideSledWeight.text = [ [NSString alloc] initWithFormat:@"%.1f", [codeItem floatValue] ]; 
    
}

- (void) overrideFuelFlowFromSpecialData {
    
    
    //fuelFlowLT=00000 
    //IN PLANUNG
    //fuelFlowLB=00000
    //fuelFlowKG=00000
    //fuelFlowGA=00000
              
    NSRange range = [specialdata2 rangeOfString:@"fuelFlow"];        
    NSString *codeItem =  [specialdata2 substringWithRange:NSMakeRange(range.location+11, 5)]; 
    //NSLog(@"codeItem %@", codeItem);
    if ([specialdata2 rangeOfString:@"fuelFlowLT"].location != NSNotFound ) {  
        
        if ([fuelEnterMode isEqualToString:@"volume"] ) {           
            if ([selectedUnitForFuel isEqualToString:@"kg"]  ) {
                inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.1f", [codeItem floatValue] ]; 
            }
        }
        
        if ([fuelEnterMode isEqualToString:@"mass"] ) {
            //now we need to convert liter  (specialData) to kilo
            if ([selectedUnitForFuel isEqualToString:@"kg"]  ) {
                inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.1f", [codeItem floatValue] * [_inputSpecificFuelMassPerVolume.text floatValue] ]; 
            }
        }
    }
    
 
    if ([specialdata2 rangeOfString:@"fuelFlowKG"].location != NSNotFound ) {  
        
        if ([fuelEnterMode isEqualToString:@"volume"] ) {   
            //now we need to convert kilo  (specialData) to liter
            if ([selectedUnitForFuel isEqualToString:@"kg"]  ) {
                inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.1f", [codeItem floatValue]  / [_inputSpecificFuelMassPerVolume.text floatValue] ]; 
            }
        }
        
        if ([fuelEnterMode isEqualToString:@"mass"] ) {           
            if ([selectedUnitForFuel isEqualToString:@"kg"]  ) {
                inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.1f", [codeItem floatValue]  ]; 
            }
        }
    }
    
    
    //***********************
    
    
    
    if ([specialdata2 rangeOfString:@"fuelFlowLB"].location != NSNotFound ) {  
        
        if ([fuelEnterMode isEqualToString:@"mass"] ) {           
                   if ([selectedUnitForFuel isEqualToString:@"lbs"]  ) {
                       inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.1f", [codeItem floatValue]  ]; 
                   }
         }       
        
        if ([fuelEnterMode isEqualToString:@"volume"] ) {  
             //now we need to convert lbs to gallons
            if ([selectedUnitForFuel isEqualToString:@"lbs"]  ) {
                inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.1f", [codeItem floatValue] / [_inputSpecificFuelMassPerVolume.text floatValue] ]; 
            }
        }
       
    }
    
    
    if ([specialdata2 rangeOfString:@"fuelFlowGA"].location != NSNotFound ) {  
        
        if ([fuelEnterMode isEqualToString:@"mass"] ) {    
            //now we need to convert gallons to lbs
                   if ([selectedUnitForFuel isEqualToString:@"lbs"]  ) {
                       inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.1f", [codeItem floatValue] * [_inputSpecificFuelMassPerVolume.text floatValue] ]; 
                   }
         }       
        
        if ([fuelEnterMode isEqualToString:@"volume"] ) {  
             
            if ([selectedUnitForFuel isEqualToString:@"lbs"]  ) {
                inputFuelFlowOverride.text = [ [NSString alloc] initWithFormat:@"%.1f", [codeItem floatValue]  ]; 
            }
        }
       
    }
    
    
    
    //NSLog(@"overrideFuelFlowFromSpecialData %@", inputFuelFlowOverride.text);
}




- (void) setUnitConversionFactors {
    
    //NSLog(@"setUnitConversionFactors");
    //NSLog(@"setUnitConversionFactors selectedUnitForFuel %@ ", selectedUnitForFuel);
    //NSLog(@"setUnitConversionFactors fuelUnits %@ ", fuelUnits);
    
    float meterFactor = 1.0;
    
     if ( [[_arrayName23 objectAtIndex:48] isEqualToString:@"yes"]) {         
         // if meter
         meterFactor = 1000;
     }
    
    if ([selectedUnitForItems isEqualToString: unitsWeight.text]  ) {
        //NSLog(@"c1");
        factorApplyToNativeWeightforItems = 1;
        factorApplyToNativeDistanceInchMM = 1;
        factorApplyToNativeMoment = 1;
    }
    
    if ([selectedUnitForFuel isEqualToString: fuelUnits]  ) {
        //NSLog(@"c2");
        factorApplyToNativeFuelWeight = 1;
        factorApplyToNativeFuelVolumeGalLiter = 1;
    }
    
    
    if ([selectedUnitForFuel isEqualToString:@"kg"] & [fuelUnits isEqualToString:@"lbs"] ) {
        //NSLog(@"c3");
        factorApplyToNativeFuelWeight = 1/2.2046;
        factorApplyToNativeDistanceInchMMforFuel = 25.4;
        factorApplyToNativeFuelMoment = 1/0.086795276;
        factorApplyToNativeFuelVolumeGalLiter = 3.78541;
    }
    
    if ([selectedUnitForFuel isEqualToString:@"lbs"] & [fuelUnits isEqualToString:@"kg"] ) {
        //NSLog(@"c4");
        factorApplyToNativeFuelWeight = 2.2046;
        factorApplyToNativeDistanceInchMMforFuel = 1/25.4;
        factorApplyToNativeFuelMoment = 0.086795276;
        factorApplyToNativeFuelVolumeGalLiter = 1/3.78541;
    }
    
    
    
    if ([selectedUnitForItems isEqualToString:@"kg"] & [unitsWeight.text isEqualToString:@"lbs"] ) {
        //NSLog(@"c5");
        factorApplyToNativeWeightforItems = 1/2.2046;
        factorApplyToNativeDistanceInchMM = 25.4;
        factorApplyToNativeMoment = 1/0.086795276;
        
        
    }
    
    if ([selectedUnitForItems isEqualToString:@"lbs"] & [unitsWeight.text isEqualToString:@"kg"] ) {
        //NSLog(@"c6");
        factorApplyToNativeWeightforItems = 2.2046;
        factorApplyToNativeDistanceInchMM = 1/25.4 * meterFactor;
        factorApplyToNativeMoment = 0.086795276 * meterFactor;
        
    
        
    }
    
    //NSLog(@"setting factorApplyToNativeMoment %f", factorApplyToNativeMoment);

    
}




- (IBAction)actionViewAllAvailableAircraft:(id)sender {
    
    if (_viewFleetManager.hidden == YES) {
        _viewFleetManager.hidden = NO;
        [viewOne bringSubviewToFront:_viewFleetManager];  
        
        NSNotification *myNotification = [NSNotification notificationWithName:@"notificationViewAllAvailAircraft"
                                                                       object:self //object is usually the object posting the notification
                                                                     userInfo:nil]; //userInfo is an optional dictionary
        
        //Post it to the default notification center
        [[NSNotificationCenter defaultCenter] postNotification:myNotification];
        
        
        
    }else{
        _viewFleetManager.hidden = YES;
    }       
    
}

- (IBAction)actionViewAircraftSetup:(id)sender {
    
    if (_viewFleetManager.hidden == YES) {
        _viewFleetManager.hidden = NO;
        [viewOne bringSubviewToFront:_viewFleetManager];        
        NSNotification *myNotification = [NSNotification notificationWithName:@"notificationViewAircraftManager"
                                                                       object:self //object is usually the object posting the notification
                                                                     userInfo:nil]; //userInfo is an optional dictionary
        
        //Post it to the default notification center
        [[NSNotificationCenter defaultCenter] postNotification:myNotification];
        
    }else{
        _viewFleetManager.hidden = YES;
    }       
    
}



- (void)startLoadingACsFromFleetControl {
    
    //NSLog(@"startLoadingACsFromFleetControl");    
    triggerSetDefaultsForPerformanceCharts = 0;
    [self performSelector: @selector (loadACDataMyFLeet) withObject:nil afterDelay: 0.1f];  
    
    
}

- (void) loadACDataMyFLeet {
    
    //NSLog(@"1 loadACDataMyFLeet");    
    importPerformanceData *_importPerformanceData = [[importPerformanceData alloc]init];
    [_importPerformanceData loadPerformanceData: @"loadDataFromFleetControl_myFleetOnly"];    
    [calculatePerformanceClass_ resetPreviousChartName ];
    [self addPerformanceButtons];
    //******
   
    importConfigurations *_importConfigurations = [[importConfigurations alloc]init];
    [_importConfigurations loadConfigurationData : @"loadDataFromFleetControl_myFleetOnly"];
    // load initial config
    [self loadArrayListo];
    [self setConfiguration];
    [self SaveValues];   
    [self createListoItemsSlidersAndInterior];
    [self makeConfigButtons];
    _viewLoadingData.hidden = YES;
    //*********

    [self addHelicopterButtonsMyFleet];    
    [self MainRoutine];      
    _viewLoadDataFleetManager.hidden = YES;    
    //[self deleteAllFlightsWithoutFleetData]; 
    
    
    _viewFleetManager.hidden = NO;
    [viewOne bringSubviewToFront:_viewFleetManager]; 
    
    NSNotification *myNotification = [NSNotification notificationWithName:@"notificationViewAircraftManager"
                                                                   object:self //object is usually the object posting the notification
                                                                 userInfo:nil]; //userInfo is an optional dictionary
    
    //Post it to the default notification center
    [[NSNotificationCenter defaultCenter] postNotification:myNotification];    
      
    //NSLog(@"2 loadACDataMyFLeet");
    
}

- (void) addHelicopterButtonsMyFleet {
    
    //NSLog(@"addHelicopterButtonsMyFleet");
    
    HeliDataLoaded = 1; connectedToFleetControl = 1;
    
    for (UIView *subview in helicopter_sview.subviews) {
        [subview removeFromSuperview];
    }
    
    arrayMyFleetACTypes = [[NSMutableArray alloc] init];
    
   int yCoord=14;
    [helicopter_sview setContentSize:CGSizeMake(432, yCoord +100)];
    [helicopter_sview setScrollEnabled:YES];
    
    
}

- (void) showLoadDataFM {
    
    float loadingSeconds = 60;
    
    NSString *userExtraCheck = [[NSUserDefaults standardUserDefaults] stringForKey:@"userExtras"];
    if (userExtraCheck.length < 1) {  userExtraCheck = @"";   }
    if ([userExtraCheck rangeOfString:@"flightSchoolPackage"].location != NSNotFound  ) {   
        loadingSeconds = 100;
         //NSLog(@"setting loading Seconds to 180");  
    }
    
    _viewProgress.frame = CGRectMake(350, 270, 1, 9); 
    
    //NSLog(@"showLoadDataFM");
    [_spinner2 startAnimating];
    _viewLoadDataFleetManager.hidden = NO;
    [_viewFleetManager bringSubviewToFront:_viewLoadDataFleetManager];
    [viewOne bringSubviewToFront:_viewFleetManager];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:loadingSeconds];   
    
    
    _viewProgress.frame = CGRectMake(350, 270, 300, 9);                    
    //_backgroundSkyImage.frame = CGRectMake(_backgroundSkyImage.frame.origin.x-500, _backgroundSkyImage.frame.origin.y-500, _backgroundSkyImage.frame.size.width + 1000, _backgroundSkyImage.frame.size.height + 1000);                    
    [UIView commitAnimations];
    
    
}






- (void) incomingNotificationFromPerformance:(NSNotification *)notification{
    
    //NSString *theString2 = [notification object];  
    
    //_labelLoadingDataType.text = theString2;
    
    //NSLog(@"theString2 %@", theString2);
}

- (void) remoteControlCreateNewFlight {
    
      
    [_viewProgress.layer removeAllAnimations];
    MBpagevisit = 100;
    [[NSUserDefaults standardUserDefaults]  setFloat:  100   forKey:@"MBpagevisit"];
     
    arrayConfigurations = [[NSMutableArray alloc] init];  
    [arrayConfigurations setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"arrayConfigurations%@", AC_Type] ] mutableCopy]];
       
    NSString *theString  = [[NSUserDefaults standardUserDefaults]  stringForKey:@"note1"];
    int ACbuttonID = [theString intValue];   
    
    arrayDictAllAircraft = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"] mutableCopy];
     //NSLog(@"arrayDictAllAircraft %@", arrayDictAllAircraft);
    NSString *tempACtype = [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"fleetAC_Type"];     
    NSString *nextACCategory = [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"fleetACCategory"];    
    ACCategory = [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"fleetACCategory"];
    [[NSUserDefaults standardUserDefaults]  setObject:tempACtype        forKey:@"tempACtype"];

    if ([_labelFlightID.text floatValue] < 1 ) {  
        //NSLog(@"2");
        flagTriggerSpecialCreateFlight = 0;      
        [self SaveValues]; // save old stuff
        flagMakeNewFlgtNow = 1;       
        [self LoadValues];  
        [self createNewFlight];
        if ([ACCategory isEqualToString:@"FixedWing"]) {
            //NSLog(@"3");           
            [calculatePerformanceClass_ triggerPresetSliders];
        }
    }else{        
        if (allFlightsMasterArray.count > 1 ) {             
            
            [self SaveValues]; // save old stuff            
            flagMakeNewFlgtNow = 1;       
            [self LoadValues];             
            //flagDoNotCreateFlightNow = 0;
            if (flagDoNotCreateFlightNow == 1) { 
            }else{           
                [self createNewFlight];  
                if ([nextACCategory isEqualToString:@"FixedWing"]) {  
                    [calculatePerformanceClass_ triggerPresetSliders];
                }
            }
            flagMakeNewFlgtNow = 0;
            _vFuelPresetField.text = @"";
        }  
    }
    
    flagDoNotCreateFlightNow = 0; 
    
    //coming from actionStartFlightWithAircraft    
    [[NSUserDefaults standardUserDefaults]  setObject:@"yes"   forKey:@"firstFlightCreated"];
    
    previousACType = AC_Type; 
    arrayDictAllAircraft = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"] mutableCopy];
    vFlightRegistration.text = [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"Callsign"];
    loadedBEWUnits =  [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"Units"];    
    
    if ( [loadedBEWUnits isEqualToString:@"lbs"]) {
        _labelHeliDataMass.text = @"Mass [lbs]";
        _labelHeliDataMomentLong.text = @"Moment [lbs.In]";
        _labelHeliDataMomentLat.text = @"Moment [lbs.In]";
    }else{
        _labelHeliDataMass.text = @"Mass [kg]";
        _labelHeliDataMomentLong.text = @"Moment [kg.mm]";
        _labelHeliDataMomentLat.text = @"Moment [kg.mm]";
    }    
    
    // replace BEW  
    NSString *checkSelectedUnits =  [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"SelectedUnits"]; 
    if ([checkSelectedUnits isEqualToString:loadedBEWUnits]) {    
        bew =  [[[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"BEW"] doubleValue];
        momlong =  [[[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"MomLong"] doubleValue];
        momlat =  [[[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"MomLat"] doubleValue];
    }else if ([checkSelectedUnits isEqualToString:@"lbs"] && [loadedBEWUnits isEqualToString:@"kg"]) {        
        bew =  [[[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"BEW"] doubleValue] / 2.2046;
        momlong =  [[[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"MomLong"] doubleValue] / 0.086795276 ;
        momlat =  [[[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"MomLat"] doubleValue] / 0.086795276;
    }else if ([checkSelectedUnits isEqualToString:@"kg"] && [loadedBEWUnits isEqualToString:@"lbs"]) {        
        bew =  [[[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"BEW"] doubleValue] * 2.2046;
        momlong =  [[[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"MomLong"] doubleValue] * 0.086795276 ;
        momlat =  [[[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"MomLat"] doubleValue] * 0.086795276;
    }
    
    armlong = momlong / bew;
    armlat = momlat   / bew;
    
    ACCategory = [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"fleetACCategory"];
    ACmanufacturer = [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"Manufacturer"];
    AC_Type = [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"fleetAC_Type"]; 
    ACVariant = [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"Variant"]; 
    specialdata1 = [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"specialdata1"];    
    dateOfWeighing = [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"dateOfWeighing"];
    weighingRemarks = [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"weighingRemarks"];
    trialCheck = [[arrayDictAllAircraft objectAtIndex:ACbuttonID] objectForKey:@"isATrial"];
    
   
    
    
    [[NSUserDefaults standardUserDefaults]  setObject:ACCategory        forKey:@"ACCategory"];
    [[NSUserDefaults standardUserDefaults]  setObject:ACmanufacturer    forKey:@"ACmanufacturer"];
    [[NSUserDefaults standardUserDefaults]  setObject:AC_Type           forKey:@"AC_Type"];
    [[NSUserDefaults standardUserDefaults]  setObject:ACVariant         forKey:@"ACVariant"];  
    
    [self setConfiguration]; 
    
    
    vBEW.text = [NSString stringWithFormat:@"%.2f",bew  ];
    vBEWMom.text = [NSString stringWithFormat:@"%.2f",momlong ];
    vBEWMomLat.text = [NSString stringWithFormat:@"%.2f",momlat ];
    lBEWArm.text = [NSString stringWithFormat:@"%.4f",armlong ];
    lBEWArmLat.text = [NSString stringWithFormat:@"%.4f",armlat];    
    
    // replace BEW
     //NSLog (@"5 replacing");
    [_arrayName2 replaceObjectAtIndex:3 withObject:vBEW.text];
    [_arrayName3 replaceObjectAtIndex:3 withObject:lBEWArm.text];
    [_arrayName4 replaceObjectAtIndex:3 withObject:vBEWMom.text];
    [_arrayName5 replaceObjectAtIndex:3 withObject:lBEWArmLat.text];
    [_arrayName6 replaceObjectAtIndex:3 withObject:vBEWMomLat.text];
    
 
    
    
    [self addPerformanceButtons];
    [self makeConfigButtons];
    
    triggerSetDefaultsForPerformanceCharts = 0;
    _viewSelectHelicopter.hidden = YES;
    
    if (flagMakeNewFlgtNow == 1) {
        
        //NSLog(@"yes createNewFlight anyways!!! ");
        flagDoNotCreateFlightNow = 0; 
        [self createNewFlight];
        displayWindow = 0;
        [self displayWindows];
        [self MainRoutine];
    }else{       
        displayWindow = 0;
        [self displayWindows];
        //[self createFlightButtons];
    }
    
    
    [self loadDefaultEquipmentArrays];
    //[[EquipPackagesManager sharedInstance] addNewPackageWithKey: vFlightRegistration.text andDefaultConfig:0];
    [self resetFlightSettings];  // set configuration and load array listo
    
    // do we need to retain crew?
    //NSLog(@"allFlightsMasterArray %d ", allFlightsMasterArray.count);
    if ([previousACType isEqualToString:AC_Type]) {        
        if (allFlightsMasterArray.count > 2) {
            //[self retainCrewNames];
        }
    }
    
    [self SaveValues];
    
    [self MainRoutine];
    [self MainRoutine];
    
    
    //NSLog (@"vBEW.text %@", vBEW.text);
    
    _buttonCancelSelectAC.hidden = NO;
    
  
    
    
}



- (void) incomingNotificationCreateFakeFlight:(NSNotification *)notification{
    
   
    //NSLog (@"!!!!! incomingNotificationCreateFakeFlight");   
    //NSLog(@"allFlightsMasterArray.count  %lu", (unsigned long)allFlightsMasterArray.count); 
    
    //NSLog(@"1MBpagevisit  %.0f", MBpagevisit); 
    //NSLog (@"allFlightsMasterArray %@", allFlightsMasterArray);    
    //NSLog(@"1AC_Type %@", AC_Type);
    
    if (MBpagevisit < 10) {
        [allFlightsMasterArray removeAllObjects];
        [allFlightsMasterArray addObject:@"-"];
        [self addInternalFlightNumber];
        [[NSUserDefaults standardUserDefaults]  setObject: allFlightsMasterArray  forKey:@"allFlightsMasterArray"];
        //NSLog (@"haha 0");
    }
    
    if (allFlightsMasterArray.count > 1 ) {        
        //NSLog(@"incomingNotificationCreateFakeFlight and load");
        
        [self SaveValues]; // save old stuff            
        vFlightID =  [ [NSString alloc] initWithFormat:@"%lu", (unsigned long)allFlightsMasterArray.count];        
        //NSLog(@"create fake vFlightID %@ ", vFlightID);        
        vLegID = @"1";        
        [allFlightsMasterArray addObject:@"-"];    
         [self addInternalFlightNumber];
        //NSLog(@"createNewFlight  vFlightID:%@  vLegID:  %@", vFlightID, vLegID);        
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        [defaults  setObject: vFlightID  forKey:@"vFlightID"];        
        [self SaveValues]; // save old stuff        
        [self LoadValues]; 
        
        //NSLog(@"vFlightID %@", vFlightID);
    }
    
    //NSLog (@"2vFlightID %@", vFlightID);
    
}

- (void) incomingNotificationDeleteFakeFlight:(NSNotification *)notification{
    
    
    //noteDeleteFakeFlight
    //NSLog (@"!!!!! incomingNotificationDeleteFakeFlight");   
    
    NSString *flightToDelete = [[NSUserDefaults standardUserDefaults]  stringForKey:@"vFlightID"]; 
    
    //NSLog(@"flightToDelete %@", flightToDelete);
    
    //NSLog(@"allFlightsMasterArray.count %d", allFlightsMasterArray.count);
    
    if (allFlightsMasterArray.count <= 1) {
        return;
    }
    
    //NSLog(@"actionDeleteFlightButton btn.tag %d ", btn.tag-100);    
    [allFlightsMasterArray removeObjectAtIndex: [flightToDelete intValue] ];    
    
    vFlightID =  [ [NSString alloc] initWithFormat:@"%lu", allFlightsMasterArray.count-1];
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    [defaults  setObject: allFlightsMasterArray  forKey:@"allFlightsMasterArray"];
    
    [defaults  setObject: vFlightID                                     forKey:@"vFlightID"];        
    [self LoadValues];
    [self createFlightButtons];
    [self MainRoutine]; 
    //NSLog(@"new vFlightID %@", vFlightID);
    
    
    
}


- (IBAction)actionPurchaseCategory:(id)sender {
    
    _viewFleetManager.hidden = NO;
    [viewOne bringSubviewToFront:_viewFleetManager];    
    
    NSNotification *myNotification = [NSNotification notificationWithName:@"notificationViewPurchase"
                                                                   object:self //object is usually the object posting the notification
                                                                 userInfo:nil]; //userInfo is an optional dictionary
    
    //Post it to the default notification center
    [[NSNotificationCenter defaultCenter] postNotification:myNotification];
    
}



//achtung
- (void) checkAvailabaleAircraftInFleetControl {
  
    //NSLog(@"checkAvailabaleAircraftInFleetControl ");
    
    if (!([self is_online])) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Error"
                              message:@"Cannot reach server. Please check if this device is online."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    } else {      
        NSString *url=serverpath_new;
        // load only typr
        //url = [url stringByAppendingFormat:@"get_helicopters/1.1/?customer=%@&type=%@",customer,helicopterTypeOfThisApp];
        // trick 1 load all helicopters
        url = [url stringByAppendingFormat:@"get_helicopters/1.1/?customer=%@",customer];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
           
        NSData* data = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString: url]];
        
        NSString *dataString=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
        //NSLog(@"loadHelicoptersFromFleetControl datastring: ---%@--- ",dataString);
        
        
        
        if ([dataString isEqualToString:@"NOK"]) {            
            NSString *msg=[[NSString alloc]initWithFormat:@"No helicopter found in your FleetControl fleet."];
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Error"
                                  message:msg
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
        } else {           
            __autoreleasing NSError* error = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
            //check if json data is valid
            if (error != nil) {
                //NSLog(@"%@",error);
                UIAlertView *alert = [[UIAlertView alloc]
                                      initWithTitle:@"Error"
                                      message:@"Received data that is not valid. Please contact administrator."
                                      delegate:self
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
                [alert show];                
            } else {                
                //create helicopter objects and store them in helicopters array                   
                NSMutableArray *tempAllAircraft = [[NSMutableArray alloc] init];
                NSArray *allItems = [result objectForKey:@"helicopterData"];  
                //NSLog (@"allItems  %@", allItems);                
                arrayDictAllAircraft  = [[NSMutableArray alloc] init];
                
                
                NSMutableArray *tempArrayAllCallsigns = [[NSMutableArray alloc] init];
                tempArrayAllCallsigns = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayAllCallsigns"] mutableCopy];
                //NSLog(@"tempArrayAllCallsigns %@ ", tempArrayAllCallsigns);
              
                for (int i=0; i<allItems.count; ++i) {                    
                    // loop all aircraft from Fleet Control 
                    
                   
                    NSDictionary *item = [allItems objectAtIndex:i];               
                    NSString *TheType;  
                    TheType=[item objectForKey:@"type"]; 
                    int triggerUHIconversion = 0;
                    if ([TheType isEqualToString:@"R44 Raven II"] || [TheType isEqualToString:@"R22 Beta II"] || [TheType isEqualToString:@"R44 Raven"] ) {
                        triggerUHIconversion = 1;
                    }
                    
                    
                    TheType = [TheType stringByReplacingOccurrencesOfString:@" " withString:@""];
                                     
                    //NSLog (@"checking TheType %@", TheType);
                    
                    //********************************************************************************
                    //******************************  FILTER  ****************************************
                    //********************************************************************************
                    
                  
                    
                    for(int i =0; i<tempArrayAllCallsigns.count; i++) {
                        
                      
                        //NSLog(@"TheType  %@ == [tempArrayAllCallsigns objectAtIndex:i] %@ ", TheType, [[tempArrayAllCallsigns objectAtIndex:i] objectForKey:@"fleetAC_Type"]);  
                        
                       
                        if ( [[[tempArrayAllCallsigns objectAtIndex:i] objectForKey:@"fleetAC_Type"]isEqualToString:TheType]) {
                            //NSLog(@"wumms %@ ", TheType);                            
                            NSMutableDictionary *myACsDictionary = [[NSMutableDictionary alloc] init];
                            myACsDictionary[@"Callsign"]            =  [item objectForKey:@"callsign"];
                            
                            myACsDictionary[@"Manufacturer"]        =  [[tempArrayAllCallsigns objectAtIndex:i] objectForKey:@"Manufacturer"];
                            myACsDictionary[@"fleetACCategory"]     =  [[tempArrayAllCallsigns objectAtIndex:i] objectForKey:@"fleetACCategory"];                              
                            myACsDictionary[@"BEW"]                 =  [item objectForKey:@"bew"];                            
                            if (triggerUHIconversion == 0) {
                                myACsDictionary[@"MomLong"]         =  [item objectForKey:@"armlong"];
                                myACsDictionary[@"MomLat"]          =  [item objectForKey:@"armlat"];
                            }else{                               
                               float bewConv = [[item objectForKey:@"bew"]floatValue];
                               myACsDictionary[@"MomLong"]          =  [ [NSString alloc] initWithFormat:@"%.0f", [ [item objectForKey:@"armlong"] floatValue] * bewConv];
                               myACsDictionary[@"MomLat"]           =  [ [NSString alloc] initWithFormat:@"%.0f", [ [item objectForKey:@"armlat"] floatValue] * bewConv];
                            }
                            
                            myACsDictionary[@"fleetAC_Type"]        =  TheType;
                            myACsDictionary[@"Variant"]             =  @"NONE";                               
                            myACsDictionary[@"Units"]               =  [[tempArrayAllCallsigns objectAtIndex:i] objectForKey:@"Units"];
                            
                            myACsDictionary[@"SelectedUnits"]       =  [[tempArrayAllCallsigns objectAtIndex:i] objectForKey:@"Units"];
                            myACsDictionary[@"priceCategory"]       =  [[tempArrayAllCallsigns objectAtIndex:i] objectForKey:@"priceCategory"];
                            myACsDictionary[@"downloadStatus"]      =  @"notLoaded"; // acdownloaded notLoaded
                            myACsDictionary[@"Version"]             =  [[tempArrayAllCallsigns objectAtIndex:i] objectForKey:@"Version"];
                            myACsDictionary[@"imageName"]           =  [[tempArrayAllCallsigns objectAtIndex:i] objectForKey:@"imageName"];
                            myACsDictionary[@"backendID"]           =  [[tempArrayAllCallsigns objectAtIndex:i] objectForKey:@"backendID"];  
                            myACsDictionary[@"description1"]        =  @"lockedFromFleetControl";
                            myACsDictionary[@"description2"]        =  [[tempArrayAllCallsigns objectAtIndex:i] objectForKey:@"description2"];
                            myACsDictionary[@"ACdataSource"]        =  @"backend";                            
                            [arrayDictAllAircraft addObject:myACsDictionary]; 
                                                       
                        }
                        
                    }
                    [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft forKey:@"arrayDictAllAircraft"];
                    //NSLog(@"saving arrayDictAllAircraft %@", arrayDictAllAircraft);
                    
                    NSNotification *myNotification = [NSNotification notificationWithName:@"notificationCreateMyFleetList"
                                                                                   object:self 
                                                                                 userInfo:nil];
                    [[NSNotificationCenter defaultCenter] postNotification:myNotification];

                    
                }
                
                
            }
        }
    }
    
    
    
}

- (void) loadHelicoptersFromFleetControl {
    // was loadHelicoptersNow    
    availableACTypes = [[NSMutableArray alloc] init];
    availableACTypes = [[[NSUserDefaults standardUserDefaults] objectForKey:@"availableACTypesArray"] mutableCopy];
    NSLog(@"3 loadHelicoptersFromFleetControl availableACTypes = %@", availableACTypes);
    
    if (availableACTypes.count < 1) {
        return;
    }    
    if (!([self is_online])) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Error"
                              message:@"Cannot reach server. Please check if this device is online."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    } else {
        
        //send request to server to get helicopter data as json data
        NSString *helicopterTypeOfThisApp = AC_Type;
        //NSLog(@"loadHelicoptersFromFleetControl  helicopterTypeOfThisApp = %@", helicopterTypeOfThisApp);
        
        NSString *url=serverpath_new;
        // load only typr
        //url = [url stringByAppendingFormat:@"get_helicopters/1.1/?customer=%@&type=%@",customer,helicopterTypeOfThisApp];
        // trick 1 load all helicopters
        url = [url stringByAppendingFormat:@"get_helicopters/1.1/?customer=%@",customer];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

        NSData* data = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString: url]];
        
        NSString *dataString=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
 
        if ([dataString isEqualToString:@"NOK"]) {            
            NSString *msg=[[NSString alloc]initWithFormat:@"No %@ helicopter found in your FleetControl fleet.",helicopterTypeOfThisApp];
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Error"
                                  message:msg
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
        } else {
            __autoreleasing NSError* error = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
            //check if json data is valid
            if (error != nil) {
                //NSLog(@"%@",error);
                UIAlertView *alert = [[UIAlertView alloc]
                                      initWithTitle:@"Error"
                                      message:@"Received data that is not valid. Please contact administrator."
                                      delegate:self
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
                [alert show];                
            } else {                
                //create helicopter objects and store them in helicopters array                
                arrayDictAllAircraft = [[NSMutableArray alloc] init];
                //arrayDictAllAircraft = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"] mutableCopy];
                if (arrayDictAllAircraft.count < 1) {
                    arrayDictAllAircraft = [[NSMutableArray alloc] init];
                }  
              
                
                NSArray *allItems = [result objectForKey:@"helicopterData"];              
                for (int i=0; i<allItems.count; ++i) {                    
                    // loop all aircraft from Fleet Control                                        
                    NSDictionary *item = [allItems objectAtIndex:i];               
                    NSString *TheType;                   
                    if (![[item objectForKey:@"type"] isEqualToString:@"0"]) {
                        TheType=[item objectForKey:@"type"];                        
                        if ([TheType isEqualToString:@"EC135P1"]) {                           
                            TheType = @"H135P1";
                        } 
                        //NSLog(@"TheType changed to:%@",TheType);
                        
                    }else{
                        continue;
                    }                    
                    //NSLog (@"checking TheType %@", TheType);
                    
                    //********************************************************************************
                    //******************************  FILTER  ****************************************
                    //********************************************************************************
                    
                    
                    // filter out aircraft that are not on our customerData.txt list                                        
                    if (![availableACTypes containsObject:  TheType]) {
                        //NSLog (@"this aircraft is in Fleet Control but not authorized for this app -%@-",TheType );  
                        continue;
                    } 
                    // check if we need to replace or OVERWRITE this aircraft  // remove items from array                  
                    for (int i=arrayDictAllAircraft.count-1; i>=0; i--) {                        
                        if ( [[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"] isEqualToString: TheType]) {
                            //NSLog (@"----- we have this type already %@", TheType);                            
                            if ( [[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Callsign"] isEqualToString:  [item objectForKey:@"callsign"]]) {
                                //NSLog (@"----- we have this Callsign already %@",  [item objectForKey:@"callsign"]);
                                //flagDoNotAddThisAC = 1;
                                [arrayDictAllAircraft removeObjectAtIndex:i];
                            }
                        }
                    }
                    
                    NSMutableDictionary *myACsDictionary = [[NSMutableDictionary alloc] init];
                    
                    NSString *loadedACcategory = @"";
                    NSString *loadedACmanufacturer = @"";
                    NSString *loadedAC_Type = @"";
                    NSString *loadedACVariant = @""; 
                    NSString *loadedCustomFiles = @"";
                    
                    if ([availableACTypes containsObject:  TheType]) {
                        
                         //NSLog(@"searching for TheType %@ ", TheType);
                        //check if we have data on importedTextCustomerData
                        NSString *importedTextCustomerData = [[NSUserDefaults standardUserDefaults] objectForKey:@"importedTextCustomerData"];
       
                        if (importedTextCustomerData.length > 1) {
                            //NSLog(@"we have data importedTextCustomerData ");
                            NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"|"];
                            NSArray *components = [importedTextCustomerData componentsSeparatedByCharactersInSet:charSet];                            
                            //NSLog(@"1components %@ ", components);                            
                            for(int i =0; i<components.count; i++) {
                                NSArray* componentItems  = [[components objectAtIndex:i] componentsSeparatedByString:@","];                                
                                 //NSLog(@"2componentItems %@ ", componentItems);
                                if (componentItems.count > 1) {
                                    if (componentItems.count >=4) {
                                        loadedACcategory = [componentItems objectAtIndex:0];
                                        loadedACmanufacturer = [componentItems objectAtIndex:1];
                                        loadedAC_Type = [componentItems objectAtIndex:2];
                                        loadedACVariant = [componentItems objectAtIndex:3]; 
                                        
                                        if ([loadedAC_Type isEqualToString:TheType]) {
                                            myACsDictionary[@"fleetACCategory"] = loadedACcategory;
                                            myACsDictionary[@"Manufacturer"] = loadedACmanufacturer;
                                            //NSLog(@"setting loadedACmanufacturer %@ ", loadedACmanufacturer);
                                            if (componentItems.count >=5) {
                                                loadedCustomFiles= [componentItems objectAtIndex:4];
                                                myACsDictionary[@"loadedCustomFiles"] = loadedCustomFiles; 
                                                //NSLog(@"we have data customFiles %@", loadedCustomFiles);
                                            } else{
                                                myACsDictionary[@"loadedCustomFiles"] = @""; 
                                            }
                                        }                          
                                    }
                                }
                            }
                        }
                        
                        //units enthält "kg" oder "lbs", könnte man verwenden, um in der App ne Ausgabe zu machen,
                        //dass die in der App eingestellten Units nicht zu FC passen, damit der Kunde auch check, wenn er zu blöd ist ;)
                        
                        specialdata1 =[item objectForKey:@"specialdata1"];
                        dateOfWeighing =[item objectForKey:@"dateOfWeighing"];
                        weighingRemarks =[item objectForKey:@"weighingRemarks"];
                        loadedBEWUnits=[item objectForKey:@"customer_units"];                        
                        myACsDictionary[@"Callsign"] = [item objectForKey:@"callsign"];
                         if (flagSpecialPHIFlightSettingPage == 1) {
                             _inputPHIOverrideRegistration.text = [item objectForKey:@"callsign"];                            
                             //NSLog(@"_inputPHIOverrideRegistration.text %@", _inputPHIOverrideRegistration.text);                              
                         }
                        myACsDictionary[@"fleetAC_Type"] = TheType;                        
                        myACsDictionary[@"Variant"] = @"NONE";
                        myACsDictionary[@"Units"] = [item objectForKey:@"customer_units"];
                        myACsDictionary[@"BEW"] = [item objectForKey:@"bew"];
                        myACsDictionary[@"MomLong"] = [item objectForKey:@"armlong"];
                        myACsDictionary[@"MomLat"] = [item objectForKey:@"armlat"];
                        myACsDictionary[@"SelectedUnits"] = [item objectForKey:@"customer_units"];
                        myACsDictionary[@"backendID"] = @"";
                        myACsDictionary[@"ACdataSource"] = @"FleetControl";
                        myACsDictionary[@"specialdata1"] = [item objectForKey:@"specialdata1"];
                        myACsDictionary[@"specialdata2"] = [item objectForKey:@"specialdata2"];
                        myACsDictionary[@"specialdata3"] = [item objectForKey:@"specialdata3"]; 
                        myACsDictionary[@"dateOfWeighing"] = [item objectForKey:@"dateOfWeighing"]; 
                        myACsDictionary[@"weighingRemarks"] = [item objectForKey:@"weighingRemarks"]; 
                        //NSLog (@"adding type %@  callsign %@ " ,  [item objectForKey:@"type"],  [item objectForKey:@"callsign"]);                    
                        [arrayDictAllAircraft addObject:myACsDictionary]; 
                        
                    } 
                }
                
                [[NSUserDefaults standardUserDefaults]  setObject: arrayDictAllAircraft forKey:@"arrayDictAllAircraft"];                                
                allItems = [result objectForKey:@"updateData"];
                NSDictionary *item = [allItems objectAtIndex:0];
                lastupdate_helicopters=[item objectForKey:@"lastUpdate"];               
                
                //NSLog (@"2 arrayDictAllAircraft %@  ", arrayDictAllAircraft );
                //NSLog (@"HeliDataLoaded %.0f  ", HeliDataLoaded ); 
                //create button for each helicopter                
                [self addHelicopterButtons];
                
                if (HeliDataLoaded != 0) {
                    UIAlertView *alert = [[UIAlertView alloc]
                                          initWithTitle:@"INFO"
                                          message:@"Aircraft data successfully loaded."
                                          delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
                    
                    [alert show];                        
                }    
                
                HeliDataLoaded = 1; connectedToFleetControl = 1;                
                //NSLog (@"HeliDataLoaded  " );
                
            }// helicopter load was ok
            importPerformanceData *_importPerformanceData = [[importPerformanceData alloc]init];
            NSString *customerFolderName  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];            
            //NSLog (@"111customerFolderName %@", customerFolderName);                   
            //NSLog (@"2 arrayDictAllAircraft %@  ", arrayDictAllAircraft );             
            if ([customerFolderName isEqualToString:@"Test User"] || [customerFolderName isEqualToString:@"Apple"] || [customerFolderName isEqualToString:@"Tester"] ) {
                
                NSString *customerFolderName0  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];
                //NSLog (@"*********** loading from iPad for tester = %@", customerFolderName); 
                [_importPerformanceData loadPerformanceData: @"loadDataFromiPad"]; // or  loadDataFromFleetControl                 
                NSString *customerFolderName1  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];               
                [calculatePerformanceClass_ resetPreviousChartName ];            
                importConfigurations *_importConfigurations= [[importConfigurations alloc]init];
                NSString *customerFolderName2  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];                
                [_importConfigurations loadConfigurationData: @"loadDataFromiPad"];
               NSString *customerFolderName3  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerFolderName"];
                                           
            }else{              
                 //NSLog (@"*********** loading from Fleet Control for customerFolderName = %@", customerFolderName);            
                 // load from Fleet Control                
                if (flagUpdateFleetControlDataOnly == 1) {
                     //NSLog(@"now DO NOT load performance");
                }else{
                     //NSLog(@"now load performance");
                    [_importPerformanceData loadPerformanceData: @"loadDataFromFleetControl"]; // or  loadDataFromFleetControl                 
                    [calculatePerformanceClass_ resetPreviousChartName ];                 
                    importConfigurations *_importConfigurations= [[importConfigurations alloc]init];                
                    [_importConfigurations loadConfigurationData: @"loadDataFromFleetControl"];                    
                }
            }
        }
    }
    
    
    if (flagSpecialPHIFlightSettingPage == 1) {
        if (MBpagevisit > 10) {
             [self loadWebcall]; 
        }
    }
    
    
}

- (void) combineACinArrayDictAllAircraft {        
    arrayDictAllAircraft = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"] mutableCopy]; 
       
}

- (IBAction)buttonActionAutoCalcMode:(id)sender {
    
     if ([calcMode isEqualToString:@"plan"]) {
         calcMode = @"individual";   
         _labelNotePlanMode.hidden = YES;
     }else{
          calcMode = @"plan";         
     }    
    [self MainRoutine];
}









- (IBAction)actionShowHideEquipmentListPage:(id)sender {

    if (_viewEquipmentListOverManifest.hidden == YES) {
        _viewEquipmentListOverManifest.hidden = NO;
        [self createSpecialEquipListItemsForManifest];
        [ScrollViewManifest bringSubviewToFront:_viewEquipmentListOverManifest];
    }else{
        _viewEquipmentListOverManifest.hidden = YES;
    }

}

- (IBAction)actionDropDownAvailablePHIEquipLists:(id)sender {
    
    //NSLog(@"actionDropDownAvailablePHIEquipLists ");
    _dropDownAvailablePHIEquipListsOverride.text = _dropDownAvailablePHIEquipLists.text;
    [self loadPHIEquipment];
   
    
}

- (IBAction)actionDropDownAvailablePHIEquipListsOverride:(id)sender {
    
    //NSLog(@"actionDropDownAvailablePHIEquipListsOverride ");
     _dropDownAvailablePHIEquipLists.text = _dropDownAvailablePHIEquipListsOverride.text;
    [self loadPHIEquipment];
    [self checkOverrideInputs];
 
   
}


- (void) loadPHIEquipment {
    
    //NSLog(@"loadPHIEquipment _dropDownAvailablePHIEquipLists.text %@", _dropDownAvailablePHIEquipLists.text);    
    //NSLog(@"AC_Type %@", AC_Type);    
    if (!([self is_online])) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Error"
                              message:@"Cannot reach server. Please check if this device is online."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    } else {        
        if ([_dropDownAvailablePHIEquipLists.text isEqualToString:@""] ) {        
            _dropDownAvailablePHIEquipLists.text = @"Med 1";
            _dropDownAvailablePHIEquipListsOverride.text = @"Med 1";
        }        
        PHIequipListDictionary = [[NSMutableDictionary alloc] init];
        
       
        for(int i=1; i<6; i++) {
            
            //BH407
            //AS350b3e
            //EC135P2
            //EC135P2-Plus
            //BK-117-C2
            //S76-C-Plus-Plus
            
            NSString *acNameForEquip = AC_Type;
            if ([AC_Type isEqualToString:@"B407"] || [AC_Type isEqualToString:@"B407i"]) {
                acNameForEquip =@"BH407";
            }
            if ([AC_Type isEqualToString:@"EC135P2P"] || [AC_Type isEqualToString:@"H135P2P"]) {
                acNameForEquip =@"EC135P2-Plus";
            }            
            if ([AC_Type isEqualToString:@"H135P2"] ) {
                acNameForEquip =@"EC135P2";
            }            
            if ([AC_Type isEqualToString:@"H145"]|| [AC_Type isEqualToString:@"BK117C2"]) {
                acNameForEquip =@"BK-117-C2";
            }            
            if ([AC_Type isEqualToString:@"S76CPP"]) {
                acNameForEquip =@"S76-C-Plus-Plus";
            }            
            NSString *equipListName = _dropDownAvailablePHIEquipLists.text;
            equipListName  = [equipListName stringByReplacingOccurrencesOfString:@" " withString:@"%20"];            
            NSString *urlstring1 = @"https://api.phiairmedical.com/0.1/EquipmentList";        
            NSString *urlstring2 = [[NSString alloc] initWithFormat:@"%@/%@/%@/%d", urlstring1, acNameForEquip, equipListName, i];   
            NSStringEncoding encoding;
            NSError *error;
            NSString *availableACTypesURL = urlstring2;
            NSURL *URL = [NSURL URLWithString: availableACTypesURL];
            [[NSURLCache sharedURLCache] removeAllCachedResponses];
            [[NSURLCache sharedURLCache] setDiskCapacity:0];
            [[NSURLCache sharedURLCache] setMemoryCapacity:0];
            NSString *textImport = [NSString stringWithContentsOfURL:URL usedEncoding:&encoding error:&error];
            textImport  = [textImport stringByReplacingOccurrencesOfString:@"\n" withString:@"|"];
            textImport  = [textImport stringByReplacingOccurrencesOfString:@"\t" withString:@""];            
            //NSLog(@"textImport %@", textImport);                 
            PHIequipListDictionary[[NSString stringWithFormat:@"%d", i]] = textImport; 
            [[NSUserDefaults standardUserDefaults]  setObject: PHIequipListDictionary  forKey:@"PHIequipListDictionary"];
             
        }
        
        if (PHIequipListDictionary.count < 2) {
            NSString *alertMsg = [[NSString alloc]initWithFormat:@"Equipment Error (data not available) for %@", _dropDownAvailablePHIEquipLists.text ];                     
            UIAlertView *alert = [[UIAlertView alloc]                                           
                                  initWithTitle:@"Equipment Error"                                  
                                  message:alertMsg                                 
                                  delegate:self                                  
                                  cancelButtonTitle: @"OK"                                  
                                  otherButtonTitles: nil];            
            [alert show];
        }else{
            
            equipMessage = @"";
            equipWarningMessage = @"";
            
            configuration = 1;
            [self convertPHIEquipment];          
            configuration = 2;
            [self convertPHIEquipment];
            configuration = 3;          
            [self convertPHIEquipment];
            configuration = 4;
            [self convertPHIEquipment];
            configuration = 5;      
            [self convertPHIEquipment];  
            configuration = 1;
            [self convertPHIEquipment]; 
            
            NSString *alertMsg = [[NSString alloc]initWithFormat:@"Equipment list successfully loaded:\n%@ \n\nPlease check config weights:\n\n%@", _dropDownAvailablePHIEquipLists.text, equipMessage ];     
            UIAlertView *alert = [[UIAlertView alloc]                                           
                                  initWithTitle:@"Equipment Loaded"                                  
                                  message:alertMsg                                 
                                  delegate:self                                  
                                  cancelButtonTitle: @"OK"                                  
                                  otherButtonTitles: nil];            
            [alert show];
           
            
        }
        
    }
    
   
    
}

-(void) convertPHIEquipment {
    
    
    arrayConfigItemName = [[NSMutableArray alloc] init];
    arrayConfigItemWeight = [[NSMutableArray alloc] init];
    arrayConfigItemArmLong = [[NSMutableArray alloc] init];
    arrayConfigItemMomLong = [[NSMutableArray alloc] init];
    arrayConfigItemArmLat = [[NSMutableArray alloc] init];
    arrayConfigItemMomLat = [[NSMutableArray alloc] init];
    arrayConfigIteminOut = [[NSMutableArray alloc] init];
    arrayConfigItemLocked = [[NSMutableArray alloc] init];
    arrayConfigItemData = [[NSMutableArray alloc] init];
    arrayConfigItemMoved = [[NSMutableArray alloc] init];    
    arrayConfigItemAltLong = [[NSMutableArray alloc] init];
    arrayConfigItemAltLat = [[NSMutableArray alloc] init];
    arrayConfigItemMovable = [[NSMutableArray alloc] init];
    arrayConfigItemTrigger = [[NSMutableArray alloc] init];    
    arrayConfigItemItemR1 = [[NSMutableArray alloc] init];
    arrayConfigItemItemR2 = [[NSMutableArray alloc] init];
    arrayConfigItemItemR3 = [[NSMutableArray alloc] init]; 
    arrayPackageName = [[NSMutableArray alloc] init]; 
  
    
    PHIequipListDictionary = [[NSMutableDictionary alloc] init];
    PHIequipListDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PHIequipListDictionary"] mutableCopy];    
    
    //NSLog(@"configuration %d", configuration);
    NSString *configName = [[NSString alloc] initWithFormat:@"%d", configuration];
    //NSLog(@"configName %@", configName);
    NSString *tet0 = [PHIequipListDictionary objectForKey: configName];    
    //NSLog(@"tet0 %@", tet0);
    NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"|"];
    NSArray *components = [tet0 componentsSeparatedByCharactersInSet:charSet];    
    
      
    //NSLog(@"components %@", components);    
    //NSLog(@"components.count %lu", components.count);
        
    NSString *currentPackageName = @"";  
    NSString *currentPackageInOut = @"IN"; 
     for(int i=0; i<components.count; i++) {
         
         //NSLog(@"[components objectAtIndex:i] %@",[components objectAtIndex:i]);         
         if ([[components objectAtIndex:i]length] > 3) {  
             
             //NSLog(@"checking  %@",[components objectAtIndex:i]);    
             
             
             if ([[components objectAtIndex:i] rangeOfString:@"Package ="].location != NSNotFound ) {               
                 //NSLog(@"is a package %@", [components objectAtIndex:i]); 
                 NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"="];
                 NSArray *packComponents = [[components objectAtIndex:i] componentsSeparatedByCharactersInSet:charSet];                  
                 NSString *packNameText = [[packComponents objectAtIndex:1]substringFromIndex:1];                
                 //packNameText  = [packNameText stringByReplacingOccurrencesOfString:@"\t" withString:@""];
                 //packNameText  = [packNameText stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                 //packNameText  = [packNameText stringByReplacingOccurrencesOfString:@"\n\n" withString:@""];
                 //packNameText  = [packNameText stringByReplacingOccurrencesOfString:@"\r\\n" withString:@""];
                 //NSLog(@"%@  name is >%@< ",  [components objectAtIndex:i], packNameText); 
                 packNameText  = [packNameText stringByReplacingOccurrencesOfString:@"\r" withString:@""]; // thats the one filter for carriage return 
                 
                NSString *inOutString=[packNameText substringToIndex:1];                 
                 if ([inOutString isEqualToString:@"-"]) {                    
                     [arrayConfigIteminOut addObject:@"OUT"]; 
                     currentPackageInOut = @"OUT";
                     packNameText = [packNameText substringFromIndex:2];                    
                 } else{
                   [arrayConfigIteminOut addObject:@"IN"];   
                   currentPackageInOut = @"IN";
                 }
                 
                 currentPackageName = packNameText;  
                 
                 //NSLog(@"currentPackageName  %@ = %@",currentPackageName, currentPackageInOut);   
                 
                 [arrayConfigItemName addObject:@"Package"];
                 [arrayConfigItemWeight addObject: @""];
                 [arrayConfigItemArmLong addObject: @""];
                 [arrayConfigItemMomLong addObject: @""];
                 [arrayConfigItemArmLat addObject: @""];
                 [arrayConfigItemMomLat addObject: @""];
                 [arrayConfigItemLocked addObject: @"unlocked"];
                 [arrayConfigItemData addObject:@""];
                 [arrayConfigItemMoved addObject:@""];
                 [arrayConfigItemAltLong addObject:@""];
                 [arrayConfigItemAltLat addObject:@""];
                 [arrayConfigItemMovable addObject:@""];
                 [arrayConfigItemTrigger addObject:@""];
                 [arrayConfigItemItemR1 addObject:packNameText];
                 [arrayConfigItemItemR2 addObject:@""];
                 [arrayConfigItemItemR3 addObject:@""];                 
                 [arrayPackageName addObject:packNameText];
                 //NSLog(@"adding %@",packNameText);
                       
               
                
                 
             }else{
                 //add to equip                   
                 NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@","];
                 NSArray *compEL = [[components objectAtIndex:i] componentsSeparatedByCharactersInSet:charSet];                 
                 //NSLog(@"compEL %@", compEL);                 
                 //Example Item;weigth;long;lat;longMom;latMom;status;locked;in/out;specials;ALT LON;ALT LAT;MOVABLE;Trigger;R1;R2;R3                  
                 if (compEL.count <7) { 
                     //NSLog(@"111 compEL %@", compEL); 
                     NSString *alertMsg = [[NSString alloc]initWithFormat:@"Unreadable item = %@",compEL ];                     
                     UIAlertView *alert = [[UIAlertView alloc]                                           
                                           initWithTitle:@"Equipment Error"                                  
                                           message:alertMsg                                 
                                           delegate:self                                  
                                           cancelButtonTitle: @"OK"                                  
                                           otherButtonTitles: nil];            
                     [alert show];
                     continue;                     
                 }                 
                 if ([[compEL objectAtIndex:0]length] < 1)  {                    
                     continue;
                 }
                 
                 if ([[compEL objectAtIndex:1]length] < 1 ||
                     [[compEL objectAtIndex:3]length] < 1 ||
                     [[compEL objectAtIndex:4]length] < 1 ||
                     [[compEL objectAtIndex:5]length] < 1 ||
                     [[compEL objectAtIndex:6]length] < 1) {
                     NSString *alertMsg = [[NSString alloc]initWithFormat:@"Unreadable item = %@",compEL ];
                     //NSLog(@"222 compEL %@", compEL);
                     UIAlertView *alert = [[UIAlertView alloc]                                           
                                           initWithTitle:@"Equipment Error"                                  
                                           message:alertMsg                                 
                                           delegate:self                                  
                                           cancelButtonTitle: @"OK"                                  
                                           otherButtonTitles: nil];            
                     [alert show];
                     continue;
                 }
                 
                 //NSLog(@"make normal item compEL %@", compEL); 
                 
                                  
                 NSString *inOutString=[[compEL objectAtIndex:0] substringToIndex:1];
                 //NSLog(@"inOutString %@", inOutString);       
                 if ([inOutString isEqualToString:@"-"]) {
                     NSString *nameString = [[compEL objectAtIndex:0] substringFromIndex:1];
                     [arrayConfigItemName addObject:nameString];
                     //NSLog(@"1nameString %@ is for package %@", nameString, currentPackageName);
                 }else{
                     [arrayConfigItemName addObject:[compEL objectAtIndex:0]];
                     //NSLog(@"2nameString %@ is for package %@", [compEL objectAtIndex:0], currentPackageName);
                 }
                  [arrayConfigItemWeight addObject:[compEL objectAtIndex:1]];
                  [arrayConfigItemArmLong addObject:[compEL objectAtIndex:3]];
                  [arrayConfigItemMomLong addObject:[compEL objectAtIndex:4]];
                  [arrayConfigItemArmLat addObject:[compEL objectAtIndex:5]];
                  [arrayConfigItemMomLat addObject:[compEL objectAtIndex:6]];
                  if ([inOutString isEqualToString:@"-"]) {
                     [arrayConfigIteminOut addObject:@"OUT"];
                  }else{
                      if ([currentPackageInOut isEqualToString:@"OUT"]) {
                           [arrayConfigIteminOut addObject:@"OUT"];
                      }else{
                           [arrayConfigIteminOut addObject:@"IN"];
                      }
                    
                  }
                  [arrayConfigItemLocked addObject:@"unlocked"];
                  [arrayConfigItemData addObject:@""];
                  [arrayConfigItemMoved addObject:@""];
                  [arrayConfigItemAltLong addObject:@""];
                  [arrayConfigItemAltLat addObject:@""];
                  [arrayConfigItemMovable addObject:@""];
                  [arrayConfigItemTrigger addObject:@""];
                  [arrayConfigItemItemR1 addObject:currentPackageName];
                  [arrayConfigItemItemR2 addObject:@""];
                  [arrayConfigItemItemR3 addObject:@""];  
                  [arrayPackageName addObject:currentPackageName];  
                
             }
             
         }
        
         
     }
    
    float totalweight = 0;
    for(int i=0; i<arrayConfigItemName.count; i++) {        
        //NSLog(@"%@ %@", [arrayConfigItemName objectAtIndex:i] , [arrayConfigItemArmLat objectAtIndex:i]);
        float equipOnOffFactor = 1;
        if ([[arrayConfigIteminOut objectAtIndex:i] isEqualToString:@"OUT"]) {
            equipOnOffFactor = 0;
        }
        totalweight = totalweight + ([[arrayConfigItemWeight objectAtIndex:i] floatValue] * equipOnOffFactor);        
    }
    
    [arrayConfigurations setArray: [[[NSUserDefaults standardUserDefaults] objectForKey: [NSString stringWithFormat:@"arrayConfigurations%@", AC_Type] ] mutableCopy]];
    
    //NSLog(@"1 arrayConfigurations %@", arrayConfigurations);
    
  
    if ([configName intValue] < arrayConfigurations.count) {
        //NSLog(@"2 arrayConfigurations  %@", [arrayConfigurations objectAtIndex:[configName intValue]] );
        configName = [arrayConfigurations objectAtIndex:[configName intValue]];
        if (totalweight < 1) {           
            equipWarningMessage = [equipWarningMessage stringByAppendingString: [[NSString alloc] initWithFormat:@"%@, ", configName]];
            
        }
    }
    
    equipMessage = [equipMessage stringByAppendingString: [[NSString alloc] initWithFormat:@"%@ = %.1f lbs", configName, totalweight]];
    equipMessage = [equipMessage stringByAppendingString: @"\n"];
    //NSLog(@"configName totalweight %@  %f", configName, totalweight); 
    
     _viewConfiguratorStationItems.frame = CGRectMake(0, 0, 1024, arrayConfigItemName.count * 40 + 250);
    //[_scrollViewSpecialEquipList setContentSize:CGSizeMake(_scrollViewSpecialEquipList.frame.size.width, _viewConfiguratorStationItems.frame.size.height)];
     [_scrollViewConfiguratorItems setContentSize:CGSizeMake(_scrollViewConfiguratorItems.frame.size.width, _viewConfiguratorStationItems.frame.size.height)];
    
    //NSLog(@"result arrayPackageName %@",arrayPackageName);
    
    [self createSpecialEquipListItems];
    
   
    
}

- (IBAction)actionCheckOverrideInputs:(id)sender {
    [self checkOverrideInputs];
   
}

- (void) checkOverrideInputs {

    _inputPHIOverrideBase.backgroundColor =yellowSpecialColor; 
    _inputPHIOverrideACtype.backgroundColor = yellowSpecialColor;  
    _dropDownAvailablePHIEquipListsOverride.backgroundColor = yellowSpecialColor; 
    _labelEquipWarningMessage.hidden = YES; 
    
    if (equipWarningMessage.length > 1) {
        _labelEquipWarningMessage.hidden = NO;
        _labelEquipWarningMessage.adjustsFontSizeToFitWidth = YES;
        _labelEquipWarningMessage.text = [[NSString alloc] initWithFormat:@"Warning! No Equip Data for: %@", equipWarningMessage];
    }
    
    int checkOK = 1;
    UIImage *butImg = [UIImage imageNamed:@"button generic blue.png"];
    [_buttonCreateNewPHIFlight setBackgroundImage:butImg forState:UIControlStateNormal];
    if (_inputPHIOverrideBase.text.length >= 1) {
        _inputPHIOverrideBase.backgroundColor = GreenColor;
    }else{
        checkOK = 0;
    }
   
    if (_inputPHIOverrideACtype.text.length >= 1) {
        _inputPHIOverrideACtype.backgroundColor = GreenColor;
    }else{
        checkOK = 0;
    }
    if (_dropDownAvailablePHIEquipListsOverride.text.length >= 1) {
        _dropDownAvailablePHIEquipListsOverride.backgroundColor = GreenColor;
    }else{
        checkOK = 0;
    }
    if (checkOK == 1) {        
        UIImage *butImg = [UIImage imageNamed:@"button generic green.png"];
        [_buttonCreateNewPHIFlight setBackgroundImage:butImg forState:UIControlStateNormal];
    }
   
}




- (IBAction)actionDownloadPHIEquipList:(id)sender {
    //NSLog(@"actionDownloadPHIEquipList ");
    [self loadWebcall];
}




-(void) loadWebcall {
    
    NSString *currentCallsign = _dropDownAvailablePHIEquipLists.text;   
 
    //NSLog(@"loadWebcall AC_Type %@", AC_Type );
    //BH407
    //AS350b3e
    //EC135P2
    //EC135P2-Plus
    //BK-117-C2
    //S76-C-Plus-Plus
    
    NSString *acNameForEquip = AC_Type;
    
    
    if ([AC_Type isEqualToString:@"B407"] || [AC_Type isEqualToString:@"B407i"]) {
        acNameForEquip =@"BH407";
    }
    if ([AC_Type isEqualToString:@"EC135P2P"] || [AC_Type isEqualToString:@"H135P2P"]) {
        acNameForEquip =@"EC135P2-Plus";
    }    
    if ([AC_Type isEqualToString:@"H135P2"] ) {
        acNameForEquip =@"EC135P2";
    }    
    if ([AC_Type isEqualToString:@"H145"]|| [AC_Type isEqualToString:@"BK117C2"]) {
        acNameForEquip =@"BK-117-C2";
    }    
    if ([AC_Type isEqualToString:@"S76CPP"]) {
        acNameForEquip =@"S76-C-Plus-Plus";
    }    
    if ([acNameForEquip isEqualToString:@""] ) {
        acNameForEquip = @"BH407";
    }
   
    NSString *equipListName = _dropDownAvailablePHIEquipLists.text;
    equipListName  = [equipListName stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    NSString *urlstring1 = @"https://api.phiairmedical.com/0.1/Helicopters/";        
    NSString *urlString = [[NSString alloc] initWithFormat:@"%@/%@", urlstring1, acNameForEquip];  
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; 
    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];    
    callsignArray = [[NSMutableArray alloc] init]; 
    
    //NSLog(@"urlString %@", urlString );
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
     {
         if (data)
         {             
             //NSLog(@"webcall: data online ");
             id webCallJSON;
             @try {
                 webCallJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                 NSError *error = nil;
                 NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                 //NSLog(@"dictionary: %@", dictionary);
                 NSArray *itemsArray = [dictionary valueForKey:@"helicopterData"];
                 
                 //NSLog(@"itemsArray %@",itemsArray);
                 
                 for(int i =1; i<itemsArray.count; i++) {                     
                     NSDictionary *dictionaryItem = [itemsArray objectAtIndex:i];
                     //NSLog(@"dictionaryItem %@", dictionaryItem );
                     //NSLog(@"adding istationname %@",  [dictionaryItem objectForKey: @"istationname"] );
                     [callsignArray addObject:  [ [NSString alloc] initWithFormat:@"%@", [dictionaryItem valueForKey: @"callsign"] ] ];
                     //NSLog(@"adding %@", [ [NSString alloc] initWithFormat:@"%@", [dictionaryItem valueForKey: @"callsign"]]);                     
                 }
             }
             @catch (NSException *exception) {
             }
             @finally {
             }
             
             //NSArray *jsonArray = (NSArray *)webCallJSON;             
             //callsignArray = [[NSMutableArray alloc] init];             
             //callsignArray = [jsonArray valueForKey:@"callsign"];             
             // save array for offline use             
             NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];             
             [defaults  setObject:callsignArray      forKey:@"callsignArray"];             
             //NSLog(@"saving webcall");             
             _dropDownAvailablePHIEquipLists.items  = callsignArray;
             _dropDownAvailablePHIEquipListsOverride.items  = callsignArray;
             
             //NSLog(@"loadWebcall callsignArray %@", callsignArray );
             
             
             if (callsignArray.count < 1) {
                 _dropDownAvailablePHIEquipLists.text = @"NO DATA";
                 _dropDownAvailablePHIEquipListsOverride.text = _dropDownAvailablePHIEquipLists.text;
                 UIAlertView *alert = [[UIAlertView alloc]
                                       initWithTitle:@"No Callsign Data"
                                       message:@"Please check internet connection and try again."
                                       delegate:self
                                       cancelButtonTitle:@"OK"
                                       otherButtonTitles:nil];
                 [alert show];
             }else{
                 /*
                 UIAlertView *alert = [[UIAlertView alloc]
                                       initWithTitle:@"Callsigns Updated"
                                       message:@"Callsign data successfully updated"
                                       delegate:self
                                       cancelButtonTitle:@"OK"
                                       otherButtonTitles:nil];
                 [alert show]; 
                  */
                 
                 _dropDownAvailablePHIEquipLists.text = currentCallsign;   
                 _dropDownAvailablePHIEquipListsOverride.text = _dropDownAvailablePHIEquipLists.text;
             }
         }else{
             UIAlertView *alert = [[UIAlertView alloc]
                                   initWithTitle:@"No Callsign Data"
                                   message:@"Device offline, using previously saved data"
                                   delegate:self
                                   cancelButtonTitle:@"OK"
                                   otherButtonTitles:nil];
             [alert show];             
             //NSLog(@"webcall: data OFFLINE - loading previous data");             
             // no web call data, load data from previous session             
             callsignArray = [[NSMutableArray alloc] init];             
             NSMutableArray *callsignArrayLoad = [[[NSUserDefaults standardUserDefaults] objectForKey:@"callsignArray"] mutableCopy];             
             [callsignArray setArray:callsignArrayLoad];             
             //NSLog(@"loading previous webcall %@", callsignArray);             
             _dropDownAvailablePHIEquipLists.items  = callsignArray; 
             _dropDownAvailablePHIEquipListsOverride.items  = callsignArray;
             if (callsignArray.count < 1) {
                 _dropDownAvailablePHIEquipLists.text = @"NO DATA";
                 _dropDownAvailablePHIEquipListsOverride.text = _dropDownAvailablePHIEquipLists.text;
             }else{                 
                 _dropDownAvailablePHIEquipLists.text = currentCallsign;
                 _dropDownAvailablePHIEquipListsOverride.text = _dropDownAvailablePHIEquipLists.text;
             }
             
         }
     }];   
    
    return;
    
}





- (IBAction)actionUploadSummary:(id)sender {
    
    
    float legsForThisFlight = [[allFlightsMasterArray objectAtIndex:[vFlightID intValue]] count] -1  ;        
    int allLegsForThisFLightOK = 1;        
    for (int a = 0; a <legsForThisFlight; a++) {            
        int guidanceCheckValue = [[[[allFlightsMasterArray objectAtIndex: [vFlightID intValue]] objectAtIndex: a+1 ] objectForKey:@"guidanceLegCheckOK"] floatValue]; // trick to get values from within            
        if (guidanceCheckValue != 1) {
            allLegsForThisFLightOK = 0;
        }
    }
    
    if (allLegsForThisFLightOK == 1) {
        [self uploadSummaryAfterCheck];
    }else{
        alertFlag = 2010;
        UIAlertView *alert = [[UIAlertView alloc]
                              
                              initWithTitle:@"Missing Flight Data"                              
                              message:@"Not all legs of this flight are completed. Are you sure you want to upload the summary?"
                              delegate:self                              
                              cancelButtonTitle:@"CANCEL"                              
                              otherButtonTitles:@"Upload Summary", nil];        
        [alert show];
        
        
    }
  
    
}

- (void) uploadSummaryAfterCheck {
    NSString *url=@"https://api.phiairmedical.com/0.1/FlightData";
    NSData* data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSURLRequest *urlRequest = [self postRequestWithURL:url data:data];  ; 
    //NSLog(@"POST: %@", [urlRequest allHTTPHeaderFields]);    
    //NSLog(@"prepare 1");     
    NSMutableArray *PHIuploadConnections;
    [PHIuploadConnections insertObject:[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] atIndex:0];
    //NSLog(@"PHIuploadConnections done");  
    
}


- (IBAction)actionPHICHangeBackToOriginalFormC:(id)sender {
    _inputPHIOverrideBEW.text = [NSString stringWithFormat:@"%.1f",bew];
    _inputPHIOverrideMoment.text = [NSString stringWithFormat:@"%.1f",momlong];
    _inputPHIOverrideMomentLat.text = [NSString stringWithFormat:@"%.1f",momlat]; 
    if (specialdata2.length > 1 && [specialdata2 rangeOfString:@"sledWeight"].location != NSNotFound ) {          
        [self overrideSledWeightFromSpecialData];
    }else{
        _inputPHIOverrideSledWeight.text = @"";        
    }
    UIImage *btnImg = [UIImage imageNamed:@"lock - locked-01.png"];
    [_buttonUnlockBEWOverride setBackgroundImage:btnImg forState:UIControlStateNormal];
    _inputPHIOverrideRegistration.enabled = NO; _inputPHIOverrideRegistration.backgroundColor = [UIColor lightGrayColor];
    _inputPHIOverrideBEW.enabled = NO; _inputPHIOverrideBEW.backgroundColor = [UIColor lightGrayColor];
    _inputPHIOverrideMoment.enabled = NO; _inputPHIOverrideMoment.backgroundColor = [UIColor lightGrayColor];
    _inputPHIOverrideFuelFlow.enabled = NO; _inputPHIOverrideFuelFlow.backgroundColor = [UIColor lightGrayColor];
    _inputPHIOverrideMomentLat.enabled = NO; _inputPHIOverrideMomentLat.backgroundColor = [UIColor lightGrayColor];
    _inputPHIOverrideSledWeight.enabled = NO; _inputPHIOverrideSledWeight.backgroundColor = [UIColor lightGrayColor];
    _buttonPHIchangeBackToOriginalFormC.hidden = YES;

}


-(NSURLRequest *)postRequestWithURL: (NSString *)url
                               data: (NSData *)data
{
    
    //NSLog(@"postRequestWithURL 1");    
    //This is how we do this:
    //
    //1. DateKey = HMAC-SHA256(“TailNumber” + “Secret Key I give you”, “YYYYMMDD”)
    //2. DateBaseKey = HMAC-SHA256(“DateKey”, “Flight Base”)
    //3. DateBaseServiceKey = HMAC-SHA256(“DateBaseKey”, “Electronic Flight Sheet”)
    //4. SigningKey = HMAC-SHA256(“DateBaseServiceKey”, “PHIAM-api-request”)
    //5. Signature = HMAC-SHA256(“SigningKey”, “host”+“JSON You are sending”)
    
    //collection data for signature    
    //SecretKey
  
    NSString *secret = @"HQarT!CkUWQ8P28TSDFh35=UEZaQNxkB";    
    //secret = [[NSUserDefaults standardUserDefaults]   stringForKey:@"phiKeyText"]
    //NSString *tailnumber = vFlightRegistration.text;    
    float randomID = arc4random()% 9999999;
    NSString *tailnumber = [NSString stringWithFormat:@"%@_%.0f", vFlightRegistration.text, randomID ];
    //NSLog(@"tailnumber %@",tailnumber );
    //NSString *tailnumber = @"tailtest123";
    //CurrentDate
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyyMMdd"];
    NSString *currentDate = [dateFormat stringFromDate:today];
    NSString *FlightBase = _sBase.text;
    NSString *service = @"EFS";
    NSString *post = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
    
    NSData *SigningKey = [self getDerivedKey:secret
                                  tailNumber:tailnumber
                                        date:currentDate
                                        base:FlightBase
                                     service:service];
    
    NSString *dataToSign = [NSString stringWithFormat: @"%@",post];
    
    NSData *signature = [self sha256HMacWithData:[dataToSign dataUsingEncoding:NSUTF8StringEncoding]
                                         withKey:SigningKey];    
    NSString *signatureString = [self hexEncode:[[NSString alloc] initWithData:signature
                                                                      encoding:NSASCIIStringEncoding]];
    
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSString *authorization = @"PHI-AM1-HMACSHA256 Credential=Gyronimo/";
    authorization = [authorization stringByAppendingString:tailnumber];
    authorization = [authorization stringByAppendingFormat:@"/%@",currentDate];
    authorization = [authorization stringByAppendingFormat:@"/%@",FlightBase];
    authorization = [authorization stringByAppendingFormat:@"/%@",service];
    authorization = [authorization stringByAppendingFormat:@"/%@",PHIAMSigV4Terminator];
    authorization = [authorization stringByAppendingFormat:@",SignedHeaders=host;content,Signature="];
    authorization = [authorization stringByAppendingString:signatureString];
    
    //add authorization to POST Request Header
    [request addValue:authorization forHTTPHeaderField: @"Authorization"];    
    //add body with JSON data to POST REquest
    [request setHTTPBody:data];    
    return request;
    
    
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;   
    if ((long)[httpResponse statusCode] == 200) {
        flagLoadManifestSentForThisFlight = 1;
        [self SaveValues];
        //NSLog(@"response ok");
        NSString *messageText = @"Data was sent successfully";
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:messageText
                                                                                 message:nil
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil];  
    }else{ 
        flagLoadManifestSentForThisFlight = 0;
        //NSLog(@"response not ok");
        [self SaveValues];
        NSString *messageText = [NSString stringWithFormat:@"Error! Data not sent. Error code = %.0ld", (long)[httpResponse statusCode]];
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:messageText
                                                                                 message:nil
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil];  
    }

 
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared 
    //NSLog(@"Server responded: %@",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
    return nil;
}



- (NSData *)getDerivedKey:(NSString *)secret tailNumber:(NSString *)tailNumber date:(NSString *)dateStamp base:(NSString *)baseName service:(NSString *)serviceName {
    NSString *secretKey = [NSString stringWithFormat:@"%@%@",tailNumber,secret];
    
    NSData *dateKey = [self sha256HMacWithData:[secretKey dataUsingEncoding:NSUTF8StringEncoding]
                                       withKey:[dateStamp dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *dateBaseKey = [self sha256HMacWithData:[baseName dataUsingEncoding:NSUTF8StringEncoding]
                                           withKey:dateKey];
    NSData *dateBaseServiceKey = [self sha256HMacWithData:[serviceName dataUsingEncoding:NSUTF8StringEncoding]
                                                  withKey:dateBaseKey];
    NSData *signingKey = [self sha256HMacWithData:[PHIAMSigV4Terminator dataUsingEncoding:NSUTF8StringEncoding]
                                          withKey:dateBaseServiceKey];
    return signingKey;
}

- (NSData *)sha256HMacWithData:(NSData *)data withKey:(NSData *)key {
    CCHmacContext context;
    
    CCHmacInit(&context, kCCHmacAlgSHA256, [key bytes], [key length]);
    CCHmacUpdate(&context, [data bytes], [data length]);    
    unsigned char digestRaw[CC_SHA256_DIGEST_LENGTH];
    NSInteger digestLength = CC_SHA256_DIGEST_LENGTH;    
    CCHmacFinal(&context, digestRaw);    
    return [NSData dataWithBytes:digestRaw length:digestLength];
}

- (NSString *)hexEncode:(NSString *)string {
    NSUInteger len = [string length];
    unichar *chars = malloc(len * sizeof(unichar));    
    [string getCharacters:chars];    
    NSMutableString *hexString = [NSMutableString new];
    for (NSUInteger i = 0; i < len; i++) {
        if ((int)chars[i] < 16) {
            [hexString appendString:@"0"];
        }
        [hexString appendString:[NSString stringWithFormat:@"%x", chars[i]]];
    }
    free(chars);    
    return hexString;
}

- (IBAction)buttonActionPHIcancelCreateFlight:(id)sender {
    _viewSelectHelicopter.hidden = YES;
    buttonIDtransfer = [vFlightID intValue] + 100;
    
    if ([vFlightID intValue] > 1) {       
        [self deleteFlightFromManager];
    }
}
        
   
   



@end




