//
//  RiskAssessment.m
//  EC145
//
//  Created by Claus Richter on 4/30/14.
//
//

#import "RiskAssessment.h"
#import "Reachability.h"
#import "VDLabelWithDropDown.h"

#import "riskass_form.h"
#import "riskass_category.h"
#import "riskass_question.h"
#import "riskass_answer.h"

#import "crewPerson.h"

#import "ViewController.h"


#import "JBSignatureController.h"
#import "JBSignatureView.h"




// iOS Version Checking
#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)


#define Rgb2UIColor(r, g, b)  [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]



@interface RiskAssessment ()




@end

@implementation RiskAssessment


-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}


float totalQuestions = 0;

float view1PosY = 0;

float viewYincrement = 0;

float scrollYPosition = 0;

float barHeight = 43.6;

float alertFlagRA = 0;

float statusSignatureRA = 0;

NSMutableData *pdfDataRA;




JBSignatureController *signatureControllerRA ;
UIImageView *scrollSigRA;







- (void) saveStatus {
    
    
    
    NSString *fullString = _result_totalScore.text;
    
    NSString *prefix = nil;
    
    if ([fullString length] >= 3)
        prefix = [fullString substringToIndex:3];
    else
        prefix = fullString;
    
    
    
    
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    [defaults  setObject: prefix  forKey:@"RAScore"];
    
    
    
    //NSLog(@"saving RAscore: _%@_", prefix);
    
    
    
    
    
}





- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    
    _viewOPSControl.hidden = YES;
    NSString *RAtypeOPS = [[NSUserDefaults standardUserDefaults]  stringForKey:@"RAtypeOPS"];
    if ([RAtypeOPS isEqualToString: @"OPS"] || [RAtypeOPS isEqualToString: @"OCC"]) {
        _viewOPSControl.hidden = NO;
        _buttonSendRAtoOPS.hidden=NO;
        _buttonCheckResultFromOPS.hidden=YES;
        _buttonOPSSignAndSendRA.hidden=YES;
        _labelOPSStatus.text = @"";
        _labelOPSStatus.backgroundColor = [UIColor clearColor];
    }
    
    
    
    
    _viewSignature.hidden = YES; _viewMailResult.hidden = YES; _buttonSignRiskAssessment.hidden = NO;
    
    scrollYPosition  = 0;
    
    // Initiallize the signature controller
    signatureControllerRA = [[ JBSignatureController  alloc] init];
    //signatureController.view = _viewSignature;
    //JBSignatureController *signatureController = [[JBSignatureController alloc] initWithView:viewSignature];
    [ _viewSignature addSubview:signatureControllerRA.view];
    //signatureController.delegate = self;

    
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];

    customer    = [defaults  stringForKey:@"customer"];
    
    serverpath=@"http://gyronimo.kulanaserver.com/api/default/";
    serverhost=@"gyronimo.kulanaserver.com";
    
    riskass_forms = [[NSMutableArray alloc] init];
    
    [self loadFormsFromDefault];
    
    
    
    if ( SYSTEM_VERSION_LESS_THAN(@"7.0") ) {
        
        
        _viewMain.center = CGPointMake( 512, 374 );
        
        
        
    }
    
    
    // set date
    
    
    NSDate *currentDateTime = [NSDate date];
    
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    
    [dateFormatter setDateFormat:@"MM dd yyyy"];
    
//    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
//    [dateFormatter setTimeZone:gmt];
    
    
    [dateFormatter setDateFormat:@"MM-dd-yyy"];    NSString *dateMonth = [dateFormatter stringFromDate:currentDateTime];
    
   
    
    _inputDate.text = dateMonth;

    
      
    defaultEmailRiskAssessment   = [defaults  stringForKey:@"defaultEmailAddressCC"];
    
    //NSLog(@"defaultEmailRiskAssessment %@", defaultEmailRiskAssessment);
    
    
    NSString * LOADvflightID    = [defaults  stringForKey:@"vFlightID"];
    
    
    
 
    
   
    ViewController *updateRAresult = [[ViewController alloc]init];
    
   
 
    
     //NSLog(@"LOADpilotName %@", pilotNameGlobal);

    
    
    _inputACRegistration.text = vFlightRegGlobal;
    
    self.answer100.text = pilotNameGlobal;
    
    
    _inputTrip.text = LOADvflightID;
    
    
     self.answer102.text = LOADvflightID;
    
    
    
    
    
    
    
    
    
    [_scrollViewQuestions setScrollEnabled:YES];
    
    [_scrollViewQuestions setContentSize:CGSizeMake(1024, 7230)];
    
    
    [_scrollViewMailResults setScrollEnabled:YES];
    
    [_scrollViewMailResults setContentSize:CGSizeMake(1024, 1800)];

    [_scrollViewQuestions setHidden:YES];
    
    [self createFormButtons];
    
    
    
   // poistion views
    
    
    viewYincrement = 600;
    
    view1PosY = 310;
    
    float viewXpos = 512;
    
    _view0.center = CGPointMake( viewXpos, view1PosY);
    
    _view1.center = CGPointMake( viewXpos, view1PosY + ( 1 * viewYincrement ) );
    
    _view2.center = CGPointMake( viewXpos, view1PosY + ( 2 * viewYincrement ) );
    
    _view3.center = CGPointMake( viewXpos, view1PosY + ( 3 * viewYincrement ) );
    
    _view4.center = CGPointMake( viewXpos, view1PosY + ( 4 * viewYincrement ) );
    
    _view5.center = CGPointMake( viewXpos, view1PosY + ( 5 * viewYincrement ) );
    
    _view6.center = CGPointMake( viewXpos, view1PosY + ( 6 * viewYincrement ) );
    
    _view7.center = CGPointMake( viewXpos, view1PosY + ( 7 * viewYincrement ) );
    
    _view8.center = CGPointMake( viewXpos, view1PosY + ( 8 * viewYincrement ) );
    
    _view9.center = CGPointMake( viewXpos, view1PosY + ( 9 * viewYincrement ) );
    
    _view10.center = CGPointMake( viewXpos, view1PosY + ( 10 * viewYincrement ) );
    
  
   _viewResult.center = CGPointMake( viewXpos, view1PosY + ( 11 * viewYincrement + 50 ) );

   

    
    
    
    
    // ######################################### CREW PILOTS
    
    //set info for the case that the crewlist was not loaded yet
    self.answer100.items   =  @[ @"No crew data loaded.", @"Please close Risk Assessment", @"and load crew list from server" ];
    
    // Set desired crewType
    NSString *crewType=@"Pilot";
    
    //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]];
    
    //get crewType ID
    int crewType_ID=0;
    for (int i=0; i<crew_types.count; i++) {
        if ([[crew_types objectAtIndex:i] isEqualToString:crewType]) {
            crewType_ID=i;
        }
    }
    
    //get crew name
    crew = [[NSMutableArray alloc] init];
    if (crew_sectioned.count>0) {
        for (int i=0; i<[[crew_sectioned objectAtIndex:crewType_ID] count]; i++) {
            NSString *crewname=[[[crew_sectioned objectAtIndex:crewType_ID] objectAtIndex:i] name];
            crewname = [crewname stringByAppendingFormat:@", %@",[[[crew_sectioned objectAtIndex:crewType_ID] objectAtIndex:i] initial]];
            [crew addObject:crewname];
        }
        
        //set crew name to drop down
        self.answer100.items = crew;
        
    }
    
    // #########################################

    
    
    
    

    
    
  
    
    
    self.answer102.items   =  @[ @"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",];
    
    self.listName.items   =  @[ @"Preset 1", @"Preset 2", @"Preset 3", @"Preset 4", ];
    
    self.listName2.items   = self.listName.items;

     self.listName2.text =  self.listName.text;
    
    
}





- (IBAction)closeKeyboard:(id)sender {


      [self.view endEditing:TRUE];
    
    

}

- (IBAction)fixedListDidEndEditing:(id)sender {
    
    self.listName2.text =  self.listName.text;
    
    
    [self dropDownSelectionChanged:sender];
}

- (IBAction)list2DidEndEditing:(id)sender {
    
    
    self.listName.text =  self.listName2.text;
    
    
    
    _inputListName.text = self.listName2.text;

    
    
    [self dropDownSelectionChanged:sender];
    
    
    
}

- (void)dropDownSelectionChanged:(id)sender {
    
    
    if ([sender tag] == 2) {
        
        
        scrollYPosition = scrollYPosition + 600;
        
        if (scrollYPosition > 6600) {
            scrollYPosition = 6600;
        }
        
        
        
        
        CGRect zoomRect = CGRectMake(0, scrollYPosition, _scrollViewQuestions.frame.size.width, _scrollViewQuestions.frame.size.height);
        
        [_scrollViewQuestions scrollRectToVisible:zoomRect animated:YES];

    }
    
    
    if ([sender isKindOfClass:[VDLabelWithDropDown class]]) {
        [self checkAnswers];
    }
    
}

- (void) checkAnswers{
    
    float RAscore = 0; //float iScore = 0;
    
    float rYEL = 255, gYEL = 225, bYEL = 4;
    
    float rGRN = 202, gGRN = 255, bGRN = 185;
    
    float rRED = 255, gRED = 83, bRED = 104;
    
    int CarcadianTOScore =0;
    float questionAnswered = 0;
    NSMutableArray *cat_points;
    cat_points = [[NSMutableArray alloc]init];
    
    
    for (int i=0; i<10; i++) {
        [cat_points addObject:@"0"];
    }
    
    for (int i=1; i<answers.count; i++) {
        
        int min_points=1000;
        int max_points=0;
        int selected_points=0;
        VDLabelWithDropDown *current_field=[answers objectAtIndex:i];
        

        
        if (!([current_field.text isEqualToString:@""])) {
        
            questionAnswered+=1;
            
        for (int j=0; j<[[[questions objectAtIndex:i]answers]count];j++) {
            
            
            int points=[[[[questions objectAtIndex:i]answers]objectAtIndex:j]points];
            if (points<min_points) {
                min_points=points;
            }
            if (points>max_points) {
                max_points=points;
            }
            if ([[[[[questions objectAtIndex:i]answers]objectAtIndex:j]Answer] isEqualToString:current_field.text]) {
                selected_points=[[[[questions objectAtIndex:i]answers]objectAtIndex:j]points];
                
                //INC cat points
                int cat=[[questions_cat objectAtIndex:i] intValue];
                int saved_catpoints=[[cat_points objectAtIndex:cat]intValue];
                saved_catpoints+=selected_points;
      
                [cat_points replaceObjectAtIndex:cat withObject:[[NSString alloc] initWithFormat:@"%i",saved_catpoints]];

            }
            
            
        
        }
        
        //NSLog(@"selected point: %i, min: %i, max: %i",selected_points,min_points,max_points);
        
        if (selected_points==min_points) {
             current_field.superview.backgroundColor = Rgb2UIColor(rGRN, gGRN, bGRN);
        }
        if ((selected_points>min_points)&&(selected_points<max_points)) {
            current_field.superview.backgroundColor = Rgb2UIColor(rYEL, gYEL, bYEL);
        }
        if (selected_points==max_points) {
            current_field.superview.backgroundColor = Rgb2UIColor(rRED, gRED, bRED);
            
        }
        
        
        CarcadianTOScore = CarcadianTOScore + selected_points;
            
        } else {
        //set to white if answer empty
        current_field.superview.backgroundColor = Rgb2UIColor(255,255,255);
        }
    }
    
    RAscore=CarcadianTOScore;
    
    
    
    
    float riskBarHeight = 0 ;
    
    
    
    _bar1.layer.anchorPoint = CGPointMake(0.5, 1);
    _bar2.layer.anchorPoint = CGPointMake(0.5, 1);
    _bar3.layer.anchorPoint = CGPointMake(0.5, 1);
    _bar4.layer.anchorPoint = CGPointMake(0.5, 1);
    _bar5.layer.anchorPoint = CGPointMake(0.5, 1);
    _bar6.layer.anchorPoint = CGPointMake(0.5, 1);
    _bar7.layer.anchorPoint = CGPointMake(0.5, 1);
    _bar8.layer.anchorPoint = CGPointMake(0.5, 1);
    _bar9.layer.anchorPoint = CGPointMake(0.5, 1);
    _bar10.layer.anchorPoint = CGPointMake(0.5, 1);
    
    [_bar1 setAlpha:0.0];
    [_bar2 setAlpha:0.0];
    [_bar3 setAlpha:0.0];
    [_bar4 setAlpha:0.0];
    [_bar5 setAlpha:0.0];
    [_bar6 setAlpha:0.0];
    [_bar7 setAlpha:0.0];
    [_bar8 setAlpha:0.0];
    [_bar9 setAlpha:0.0];
    [_bar10 setAlpha:0.0];
    
    [_cat01 setAlpha:0.0];
    [_cat02 setAlpha:0.0];
    [_cat03 setAlpha:0.0];
    [_cat04 setAlpha:0.0];
    [_cat05 setAlpha:0.0];
    [_cat06 setAlpha:0.0];
    [_cat07 setAlpha:0.0];
    [_cat08 setAlpha:0.0];
    [_cat09 setAlpha:0.0];
    [_cat10 setAlpha:0.0];
    
    _label1.text = @"";
    _label2.text = @"";
    _label3.text = @"";
    _label4.text = @"";
    _label5.text = @"";
    _label6.text = @"";
    _label7.text = @"";
    _label8.text = @"";
    _label9.text = @"";
    _label10.text = @"";
    
    // make cat labels
    
    for(UIView *subview in [_viewCategories subviews]) {
        [subview removeFromSuperview];
    }
    
    
    int categories_count = [[[riskass_forms objectAtIndex:currentForm] categories] count];

    
    float xStart = 20;
    float yTop = 15;
    float labelHeight = 60;
    float labelWidth = 680 / categories_count;
    float gap = 20 + labelWidth;
    
    
    for (int i=0; i<categories_count; i++) {
        
    UITextView *textField = [[UITextView alloc] initWithFrame:CGRectMake(xStart + (i*gap) , yTop + 15 , labelWidth , labelHeight ) ];
    textField.font = [UIFont systemFontOfSize:13];
    textField.textAlignment = NSTextAlignmentCenter;
    textField.backgroundColor = [UIColor clearColor];
    textField.text = [[[riskass_forms objectAtIndex:currentForm] getCategory:i]Title];
    
    textField.tag = i + 100;
    [_viewCategories addSubview:textField];
    
    
        
    // make score labels
    
    UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(xStart + (i*gap) , yTop, labelWidth , 30 ) ];
    label.font = [UIFont boldSystemFontOfSize:17.0];
    label.textColor =[UIColor blackColor];
    label.alpha = 1.0;
    label.textAlignment = NSTextAlignmentCenter;
        
    //label.backgroundColor = [UIColor whiteColor];
    
    label.text = [ [NSString alloc] initWithFormat:@"%i", [[cat_points objectAtIndex:i]intValue]];
    
    label.tag = i + 200;
    [_viewCategories addSubview:label];
        
        
        
        
        // make score bars
        
        float maxBarHeightForScore = 550;
        
        
        riskBarHeight = (maxBarHeightForScore / [[riskass_forms objectAtIndex:currentForm]maxPoints]  ) * [[cat_points objectAtIndex:i]intValue];
        
        UIImageView *barImage= [[UIImageView alloc] initWithFrame:CGRectMake(xStart + (i*gap) , yTop, labelWidth , -riskBarHeight ) ];
        barImage.backgroundColor = [UIColor blueColor];
        
        
        
        [_viewCategories addSubview:barImage];

        
    
    }
    
    
    if ([[[riskass_forms objectAtIndex:currentForm] categories]count]>=1) {
        _label1.text = [ [NSString alloc] initWithFormat:@"%i", [[cat_points objectAtIndex:0]intValue]];
        
        // cr
        
        
        riskBarHeight = (barHeight / 100) * [[cat_points objectAtIndex:0]intValue];
        _bar1.layer.transform = CATransform3DMakeScale(1, riskBarHeight, 0);
        [_bar1 setAlpha:1.0];
        [_cat01 setAlpha:1.0];
    }
    if ([[[riskass_forms objectAtIndex:currentForm] categories]count]>=2) {
        _label2.text = [ [NSString alloc] initWithFormat:@"%i", [[cat_points objectAtIndex:1]intValue]];
        riskBarHeight = (barHeight / 100) * [[cat_points objectAtIndex:1]intValue];
        _bar2.layer.transform = CATransform3DMakeScale(1, riskBarHeight, 0);
        [_bar2 setAlpha:1.0];
        [_cat02 setAlpha:1.0];
    }
    if ([[[riskass_forms objectAtIndex:currentForm] categories]count]>=3) {
        _label3.text = [ [NSString alloc] initWithFormat:@"%i", [[cat_points objectAtIndex:2]intValue]];
        riskBarHeight = (barHeight / 100) * [[cat_points objectAtIndex:2]intValue];
        _bar3.layer.transform = CATransform3DMakeScale(1, riskBarHeight, 0);
        [_bar3 setAlpha:1.0];
        [_cat03 setAlpha:1.0];
    }
    if ([[[riskass_forms objectAtIndex:currentForm] categories]count]>=4) {
        _label4.text = [ [NSString alloc] initWithFormat:@"%i", [[cat_points objectAtIndex:3]intValue]];
        riskBarHeight = (barHeight / 100) * [[cat_points objectAtIndex:3]intValue];
        _bar4.layer.transform = CATransform3DMakeScale(1, riskBarHeight, 0);
        [_bar4 setAlpha:1.0];
        [_cat04 setAlpha:1.0];
    }
    if ([[[riskass_forms objectAtIndex:currentForm] categories]count]>=5) {
        _label5.text = [ [NSString alloc] initWithFormat:@"%i", [[cat_points objectAtIndex:4]intValue]];
        riskBarHeight = (barHeight / 100) * [[cat_points objectAtIndex:4]intValue];
        _bar5.layer.transform = CATransform3DMakeScale(1, riskBarHeight, 0);
        [_bar5 setAlpha:1.0];
        [_cat05 setAlpha:1.0];
    }
    if ([[[riskass_forms objectAtIndex:currentForm] categories]count]>=6) {
        _label6.text = [ [NSString alloc] initWithFormat:@"%i", [[cat_points objectAtIndex:5]intValue]];
        riskBarHeight = (barHeight / 100) * [[cat_points objectAtIndex:5]intValue];
        _bar6.layer.transform = CATransform3DMakeScale(1, riskBarHeight, 0);
        [_bar6 setAlpha:1.0];
        [_cat06 setAlpha:1.0];
    }
    if ([[[riskass_forms objectAtIndex:currentForm] categories]count]>=7) {
        _label7.text = [ [NSString alloc] initWithFormat:@"%i", [[cat_points objectAtIndex:6]intValue]];
        riskBarHeight = (barHeight / 100) * [[cat_points objectAtIndex:6]intValue];
        _bar7.layer.transform = CATransform3DMakeScale(1, riskBarHeight, 0);
        [_bar7 setAlpha:1.0];
        [_cat07 setAlpha:1.0];
    }
    if ([[[riskass_forms objectAtIndex:currentForm] categories]count]>=8) {
        _label8.text = [ [NSString alloc] initWithFormat:@"%i", [[cat_points objectAtIndex:7]intValue]];
        riskBarHeight = (barHeight / 100) * [[cat_points objectAtIndex:7]intValue];
        _bar8.layer.transform = CATransform3DMakeScale(1, riskBarHeight, 0);
        [_bar8 setAlpha:1.0];
        [_cat08 setAlpha:1.0];
    }
    if ([[[riskass_forms objectAtIndex:currentForm] categories]count]>=9) {
        _label9.text = [ [NSString alloc] initWithFormat:@"%i", [[cat_points objectAtIndex:8]intValue]];
        riskBarHeight = (barHeight / 100) * [[cat_points objectAtIndex:8]intValue];
        _bar9.layer.transform = CATransform3DMakeScale(1, riskBarHeight, 0);
        [_bar9 setAlpha:1.0];
        [_cat09 setAlpha:1.0];
    }
    if ([[[riskass_forms objectAtIndex:currentForm] categories]count]>=10) {
        _label10.text = [ [NSString alloc] initWithFormat:@"%i", [[cat_points objectAtIndex:9]intValue]];
        riskBarHeight = (barHeight / 100) * [[cat_points objectAtIndex:9]intValue];
        _bar10.layer.transform = CATransform3DMakeScale(1, riskBarHeight, 0);
        [_bar10 setAlpha:1.0];
        [_cat10 setAlpha:1.0];
    }

    
    
    
    
    
    

    
    
    
   
    
    
    /// AUSWERTUNG  - results
    
    
    _result_PICName.text = self.answer100.text;
    
    _result_totalScore.text =   [ [NSString alloc] initWithFormat:@"%.0f   (max %i)", RAscore, [[riskass_forms objectAtIndex:currentForm]maxPoints] ];
    
    _labelQuestionsAnswered.text = [ [NSString alloc] initWithFormat:@"%.0f / %i", questionAnswered, (questions.count-1)];
    
    //u1
    _labelMissionRiskScore.text =   [ [NSString alloc] initWithFormat:@"%.0f / %i", RAscore ,[[riskass_forms objectAtIndex:currentForm]maxPoints]];
    
    
    
    
    if (questionAnswered >= (questions.count-1)) {
        _viewNotCompleted.center = CGPointMake( -420, 278 );
        
        //RAcompleted = 1;
        
        
    }else{
        
        _viewNotCompleted.center = CGPointMake( 420, 278 );
        
        //vRAcompleted = 0;
    }
    
    
    
    //vRAscore = RAscore;
    
    
    
    // update
    
    
    //NSLog (@"go to update with vRAscore %@ ", [ [NSString alloc] initWithFormat:@"%.0f ", vRAscore  ]);
    
    
    //ViewController *updateRAresult = [[ViewController alloc]init];
    
    
    //[updateRAresult setLoadmanifestVariables];
    
  
    
    _riskBar.layer.anchorPoint = CGPointMake(0.5, 1);
    
    
    float riskBarScore = RAscore;
    
    //u1
    if (riskBarScore > [[riskass_forms objectAtIndex:currentForm]maxPoints] ) {
        riskBarScore = [[riskass_forms objectAtIndex:currentForm]maxPoints] ;
    }
    
    //u1
    riskBarHeight = (barHeight / [[riskass_forms objectAtIndex:currentForm]maxPoints] ) * riskBarScore;
    
    
    
    _riskBar.layer.transform = CATransform3DMakeScale(1, riskBarHeight, 0);
    
    
    //NSLog (@"yellow  %d ", [[riskass_forms objectAtIndex:currentForm]yellowThreshold] );
    //NSLog (@"orange  %d ", [[riskass_forms objectAtIndex:currentForm]orangeThreshold] );
    //NSLog (@"red     %d ", [[riskass_forms objectAtIndex:currentForm]redThreshold] );
    
    //NSLog (@"recomm green     %@ ",  [[riskass_forms objectAtIndex:currentForm]recomm_green] );
    //NSLog (@"recomm yel     %@ ",  [[riskass_forms objectAtIndex:currentForm]recomm_yellow] );
    //NSLog (@"recomm orange     %@ ",  [[riskass_forms objectAtIndex:currentForm]recomm_orange] );
    //NSLog (@"recomm red     %@ ",  [[riskass_forms objectAtIndex:currentForm]recomm_red] );
    
    
    
    
    
    
    if (RAscore < [[riskass_forms objectAtIndex:currentForm]yellowThreshold]  ) { // green
        
        [_riskBar setBackgroundColor:[UIColor greenColor]];
        
        _recommendation.text = [[riskass_forms objectAtIndex:currentForm]recomm_green];
        
    }
    
    
   
    if (RAscore >= [[riskass_forms objectAtIndex:currentForm]yellowThreshold]  &  RAscore <= [[riskass_forms objectAtIndex:currentForm]orangeThreshold] ) { // yellow
        
        [_riskBar setBackgroundColor:[UIColor yellowColor]];
        
        _recommendation.text = [[riskass_forms objectAtIndex:currentForm]recomm_yellow];
        
    }
    
    
    if (RAscore >= [[riskass_forms objectAtIndex:currentForm]orangeThreshold]  &  RAscore <= [[riskass_forms objectAtIndex:currentForm]redThreshold] ) { // orange
        
        [_riskBar setBackgroundColor:[UIColor orangeColor]];
        
        _recommendation.text = [[riskass_forms objectAtIndex:currentForm]recomm_orange];
        
    }
    
    
    if (RAscore >= [[riskass_forms objectAtIndex:currentForm]redThreshold]   ) { // red
        
        [_riskBar setBackgroundColor:[UIColor redColor]];
        
        _recommendation.text = [[riskass_forms objectAtIndex:currentForm]recomm_red];
        
    }

    
    
    
    


    
    // mail labels:
    
    NSString *AssessmentName = self.answer100.text; // pilot name
    
    AssessmentName = [AssessmentName stringByAppendingString:@" - "];
    AssessmentName = [AssessmentName stringByAppendingString:self.listName.text]; // plus preset name
   
    
    
    _mail_AssessmentName.text = AssessmentName;
    
    [self makeTimeStamp];
    
    _mail_Remarks.text = _inputRemarks.text;
    
    _mail_Date.text = timeStamp;
    
    _mail_TailNumber.text = _inputACRegistration.text;
    
    _mail_PIC.text = self.answer100.text;
    
    _mail_LegNumber.text =  self.answer102.text;
    
    _mailScore.text = _result_totalScore.text;
    
    _mail_TripNumber.text = _inputTrip.text;
    
    _mail_Recommendation.text = _recommendation.text;
    

    NSString *result;
    
    result =@"";
    
    for (int i=1; i<[answers count]; i++) {
    
        UILabel *field=[answers objectAtIndex:i];
        if (field.text) {
            NSString *questionTxt=[[questions objectAtIndex:(i)]Question];
            result = [result stringByAppendingString:questionTxt];
            result = [result stringByAppendingString:@"       --   "];
            result = [result stringByAppendingString:field.text];
            result = [result stringByAppendingString:@"\n"];
        }
    }
    
    
    _textViewMail.text = result;

    
    
    
}

- (IBAction)actionswitchToMainPage:(id)sender {
    
    
    [self saveStatus];
    
   [self dismissModalViewControllerAnimated:YES];
    
    
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




- (IBAction)buttonActionNextPage:(id)sender {
    
    
    //NSLog (@"scrollYPosition %@ ", [ [NSString alloc] initWithFormat:@"%.0f ", scrollYPosition]);
    int maxScroll=0;
    if ([riskass_forms count]>0) {
        int cat_count=[[[riskass_forms objectAtIndex:currentForm] categories]count];
        maxScroll=(cat_count*600)+600;
    } else {
        maxScroll=6600;
    }
    
   scrollYPosition = scrollYPosition + 600;
    
   
    if (scrollYPosition > maxScroll) {
        scrollYPosition = maxScroll;
    }
    
    

    
    CGRect zoomRect = CGRectMake(0, scrollYPosition, _scrollViewQuestions.frame.size.width, _scrollViewQuestions.frame.size.height);
    
    [_scrollViewQuestions scrollRectToVisible:zoomRect animated:YES];
    
    
   
    
    
}

- (IBAction)buttonActionPreviousPage:(id)sender {
    
    
    scrollYPosition = scrollYPosition - 600;
    
    if (scrollYPosition < 0) {
        scrollYPosition = 0;
    }
    
    
    
    
    CGRect zoomRect = CGRectMake(0, scrollYPosition, _scrollViewQuestions.frame.size.width, _scrollViewQuestions.frame.size.height);
    
    [_scrollViewQuestions scrollRectToVisible:zoomRect animated:YES];
    
   
    
    
    
}

- (IBAction)buttonActionLoadList:(id)sender {
    
   
    
    alertFlagRA = 1;
    
    
    UIAlertView *alert = [[UIAlertView alloc]
                          
                          initWithTitle:@"Load Assessment Lists"
                          
                          message:@"Are you sure you want to load a new list? You will overwrite the existing list. "
                          
                          delegate:self
                          
                          cancelButtonTitle:@"CANCEL"
                          
                          
                          
                          otherButtonTitles:@"OK", nil];
    
    [alert show];

  
    
    
    
}

- (IBAction)buttonActionSaveList:(id)sender {
    
    
    alertFlagRA = 2;
    
    
    UIAlertView *alert = [[UIAlertView alloc]
                          
                          initWithTitle:@"Save Assessment Lists"
                          
                          message:@"Are you sure you want to save this list under the current name? You will overwrite the existing list. "
                          
                          delegate:self
                          
                          cancelButtonTitle:@"CANCEL"
                          
                          
                          
                          otherButtonTitles:@"OK", nil];
    
    [alert show];

    
    
}






-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    
    
    
    if (alertFlagRA == 1) {
        
        
        if (buttonIndex == 0) {
            
           //NSLog (@"index 0 ");
            
            
            
        }
        
        
        if (buttonIndex == 1) {
            
            //NSLog (@"loading ");
            
            [self loadList];
           
        }
        
    }
    
    
    
    
    if (alertFlagRA == 2) {
        
        
        if (buttonIndex == 0) {
            
            //NSLog (@"index 0 ");
            
            
            
        }
        
        
        if (buttonIndex == 1) {
            
            //NSLog (@"loading ");
            
            [self saveList];
            
        }
        
    }


}












- (void) loadList {
    
    
     NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
   // self.listName.text    = [defaults  stringForKey:@"listName"];
    
 
   
    
    NSString *AssessmentName = self.answer100.text; // pilot name
    
    AssessmentName = [AssessmentName stringByAppendingString:@" - "];
    AssessmentName = [AssessmentName stringByAppendingString:self.listName.text]; // plus preset name
    
    
    _inputListName.text = AssessmentName;
    
    
    
    
    NSString *formtitle = [[riskass_forms objectAtIndex:currentForm]Title];
    NSString *savedTitle = [defaults  stringForKey:[[NSString alloc]initWithFormat:@"%@_form%i_title",_inputListName.text,currentForm]];
    
    if ([formtitle isEqualToString:savedTitle]) {
        for (int i=1; i<answers.count; i++) {
            UITextField *current_field=[answers objectAtIndex:i];
            NSString *key=[[NSString alloc] initWithFormat:@"%@_form%i_field%i",_inputListName.text,currentForm,i];

            current_field.text  = [defaults stringForKey:key];
        }
    }
    
    
    self.answer100.text    = [defaults  stringForKey:[_inputListName.text stringByAppendingString:@"answer100"]];
    _inputACRegistration.text    = [defaults  stringForKey:[_inputListName.text stringByAppendingString:@"_inputACRegistration"]];
    
     _inputRemarks.text    = [defaults  stringForKey:[_inputListName.text stringByAppendingString:@"_inputRemarks"]];
    
    self.answer102.text    = [defaults  stringForKey:[_inputListName.text stringByAppendingString:@"answer102"]];
    
    
    
    _inputDate.text             = [defaults  stringForKey:[_inputListName.text stringByAppendingString:@"_inputDate"]];
   
    
    _inputTrip.text             = [defaults  stringForKey:[_inputListName.text stringByAppendingString:@"_inputTrip"]];
    
    
    
     //NSLog(@"loaded!!!!  self.answer1.text  %@", self.answer1.text);
    
    
    [self checkAnswers];
    
    
}

- (void) saveList {
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    
//     [defaults  setObject:  self.listName.text       forKey:@"listName"];
//    
    NSString *AssessmentName = self.answer100.text; // pilot name
    
    AssessmentName = [AssessmentName stringByAppendingString:@" - "];
    AssessmentName = [AssessmentName stringByAppendingString:self.listName.text]; // plus preset name
    
    
    _inputListName.text = AssessmentName;
    
    
    for (int i=1; i<answers.count; i++) {
        
        NSString *formtitle = [[riskass_forms objectAtIndex:currentForm]Title];
        [defaults setObject:formtitle forKey:[[NSString alloc]initWithFormat:@"%@_form%i_title",_inputListName.text,currentForm]];
        NSString *key=[[NSString alloc] initWithFormat:@"%@_form%i_field%i",_inputListName.text,currentForm,i];
        UITextField *field =[answers objectAtIndex:i];
        [defaults setObject:field.text forKey:key];
     }
    
    [defaults  setObject:  self.answer100.text       forKey:[_inputListName.text stringByAppendingString:@"answer100"]];
    [defaults  setObject:  _inputACRegistration.text       forKey:[_inputListName.text stringByAppendingString:@"_inputACRegistration"]];
    
    [defaults  setObject:  _inputRemarks.text       forKey:[_inputListName.text stringByAppendingString:@"_inputRemarks"]];
    
    [defaults  setObject:  self.answer102.text       forKey:[_inputListName.text stringByAppendingString:@"answer102"]];
    
   
    
    [defaults  setObject:  _inputDate.text       forKey:[_inputListName.text stringByAppendingString:@"_inputDate"]];
    
    [defaults  setObject:  _inputTrip.text       forKey:[_inputListName.text stringByAppendingString:@"_inputTrip"]];
    
    
    
    
    
    //NSLog(@"saved!!!!  self.answer1.text  %@", self.answer1.text);
    
    
    
}





- (IBAction)buttonCloseMailResult:(id)sender {
    
    _viewMailResult.hidden = YES;
}

- (IBAction)buttonActionShowMailResults:(id)sender {
    
    
    _viewMailResult.hidden = NO;
    
    [_viewMain bringSubviewToFront:_viewMailResult];
    
}



// email


- (IBAction)actionSendMailResults:(id)sender {
    
    
    int pixelWidth = _scrollViewMailResults.contentSize.width*1.6;
    int pixelHeight = _scrollViewMailResults.contentSize.height*0.8;
    
    pdfDataRA = [NSMutableData data];
    
    UIGraphicsBeginPDFContextToData( pdfDataRA, CGRectMake(0, 0, pixelWidth, pixelHeight),  nil );
    UIGraphicsBeginPDFPage();
    CGPoint savedContentOffset = _scrollViewMailResults.contentOffset;
    CGRect savedFrame = _scrollViewMailResults.frame;
    
    _scrollViewMailResults.contentOffset = CGPointZero;
    _scrollViewMailResults.frame = CGRectMake(0, 0, pixelWidth, pixelHeight);
    
    [_scrollViewMailResults.layer renderInContext: UIGraphicsGetCurrentContext()];
    
    _scrollViewMailResults.contentOffset = savedContentOffset;
    _scrollViewMailResults.frame = savedFrame;
    
	UIGraphicsEndPDFContext();
    
    MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
    
    [composer setMailComposeDelegate: self];
    NSString *MailSubject     = [NSString stringWithFormat:@"RA %@, %@", _mail_TailNumber.text, _mail_Date.text ];
    
    
    [composer setToRecipients:[NSArray arrayWithObjects: defaultEmailRiskAssessment , nil]];
    
    //NSLog(@"_emailAdressForManifest %@", _emailAdressForManifest.text);
    
    
    
    
    [composer setSubject: MailSubject];
    
    //[composer setMessageBody:messageBody  isHTML:YES];
    [composer setMessageBody:@"Risk Assessment attached as PDF document"  isHTML:NO];
    
    
    [composer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    
    
    
    
    
    
    
    //[composer addAttachmentData:pdfDataRA mimeType:@"application/pdf" fileName:[NSString stringWithFormat:@"Gyronimo.pdf"]];
    
    [composer addAttachmentData:pdfDataRA mimeType:@"application/pdf" fileName:[NSString stringWithFormat:@"Risk_Assessment.pdf"]];
    
    
    [self presentModalViewController:composer animated:YES];
    
    
    
    
}


-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    
    if (error) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"error"
                              
                                                        message:[NSString stringWithFormat:@"error %@", [error description]]
                              
                                                       delegate:nil cancelButtonTitle:@"dismiss" otherButtonTitles:nil, nil];
        
        [alert show];
        
        
        
        [self dismissModalViewControllerAnimated:YES];
        
    }
    
    else {
        
        [self dismissModalViewControllerAnimated:YES];
        
    }
    
}




// Dennis BEGIN



- (void) loadFormsFromDefault {
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    NSData *dataRepresentingSavedArray = [defaults objectForKey:@"riskass_forms"];
    if (dataRepresentingSavedArray != nil)
    {
        NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
        if (oldSavedArray != nil)
            riskass_forms = [[NSMutableArray alloc] initWithArray:oldSavedArray];
        else
            riskass_forms = [[NSMutableArray alloc] init];
    }
    
    
}

-(void) saveFormsFromDefault {
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:riskass_forms] forKey:@"riskass_forms"];
}

- (bool)is_online {
    
    //check if server is reachable / device is online
    
    Reachability *r = [Reachability reachabilityWithHostName:serverhost];
    NetworkStatus internetStatus = [r currentReachabilityStatus];
    
    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
    {
        return false;
    } else {
        return true;
    }
    
}

- (IBAction)load_forms_from_server:(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 {
        
        
        // send request to server
        
        NSString *url=serverpath;
        url = [url stringByAppendingString:@"get_riskass_forms/1.0/?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) {
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Error"
                                  message:@"Received data that is not valid. Please contact administrator."
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            //NSLog(@"%@",error);
        } else {
            
            
            
            //create crew objects
            
            
            
            [riskass_forms removeAllObjects];

            NSArray *allForms = [result objectForKey:@"formData"];

            for (int i=0; i<allForms.count; i++) {
                
                int maxPoints=0;
                int maxPoints_temp=0;
                
                NSDictionary *item = [allForms objectAtIndex:i];
                NSString *title=[item objectForKey:@"formtitle"];
                int yellowT=[[item objectForKey:@"yellowThreshold"] intValue];
                int orangeT=[[item objectForKey:@"orangeThreshold"] intValue];
                int redT=[[item objectForKey:@"redThreshold"] intValue];
                
                NSString *recomm_green=[item objectForKey:@"recomm_green"];
                NSString *recomm_yellow=[item objectForKey:@"recomm_yellow"];
                NSString *recomm_orange=[item objectForKey:@"recomm_orange"];
                NSString *recomm_red=[item objectForKey:@"recomm_red"];
                
                NSArray *allCats = [item objectForKey:@"categories"];
                [riskass_forms addObject:[[riskass_form alloc] initWithTitle:title AndYellowT:yellowT AndOrangeT:orangeT AndRedT:redT AndRecGreen:recomm_green AndRecYellow:recomm_yellow AndRecOrange:recomm_orange AndRecRed:recomm_red]];
                
                
                //Create Categories
                for (int j=0; j<allCats.count; j++) {
                    
                    NSDictionary *itemCat = [allCats objectAtIndex:j];
                    NSString *cattitle=[itemCat objectForKey:@"catTitle"];
                    
                    //NSLog(@"----- loading cattitle %@", cattitle);
                    
                    
                    NSArray *allQuests = [itemCat objectForKey:@"questions"];
                    [[riskass_forms objectAtIndex:i] addCategory:[[riskass_category alloc] initWithTitle:cattitle]];
                    //[[[[riskass_forms objectAtIndex:i] categories] addObject:[[riskass_category alloc] initWithTitle:cattitle]];
                    
                    //Create Questions
                    for (int k=0; k<allQuests.count; ++k) {
                        
                        NSDictionary *itemQ = [allQuests objectAtIndex:k];
                        NSString *Question=[itemQ objectForKey:@"Question"];
                
                        NSArray *allAnsws = [itemQ objectForKey:@"answers"];
                        [[[riskass_forms objectAtIndex:i] getCategory:j] addQuestion:[[riskass_question alloc] initWithQuestion:Question]];
                        //[[[[[riskass_forms objectAtIndex:i] categories]objectAtIndex:j] questions] addObject:[[riskass_question alloc] initWithQuestion:Question]];
                        
                        maxPoints_temp=0;
                        
                        //Create Answers
                        for (int l=0; l<allAnsws.count; l++) {
                            NSDictionary *itemA = [allAnsws objectAtIndex:l];
                            NSString *Answer=[itemA objectForKey:@"Answer"];
                            int points=[[itemA objectForKey:@"points"] intValue];

                            [[[[riskass_forms objectAtIndex:i] getCategory:j] getQuestion:k] addAnswer:[[riskass_answer alloc] initWithAnswer:Answer AndPoints:points]];
                            //[[[[[[[riskass_forms objectAtIndex:i] categories]objectAtIndex:j]questions] objectAtIndex:k] answers] addObject:[[riskass_answer alloc] initWithAnswer:Answer AndPoints:points]];
                            if (maxPoints_temp<points) {
                                maxPoints_temp=points;
                            }
                            
                        }
                        maxPoints+=maxPoints_temp;
                        
                       
                    }
                }
                [[riskass_forms objectAtIndex:i] setMaxPoints:maxPoints];
                //NSLog(@"maxPoints: %i",maxPoints);
            }
        }
    }
    
    currentForm=0;
    [self createFormButtons];
    [self saveFormsFromDefault];
    
}






-(void) createRiskAssViews {
    
    
    for (UIView *subview in [_riskass_view subviews]) {
        if (subview.tag==666) {
            [subview removeFromSuperview];
        }
    }
    
    //u1
    ///  make risk bars
    
    //NSLog(@"maxPoints: %i",[[riskass_forms objectAtIndex:currentForm]maxPoints] );
    
    float maxPointsForRiskBar = [[riskass_forms objectAtIndex:currentForm]maxPoints];
    
    
    
    
    
    float barsAlpha = 0.7;
    
    float barTop = 102;
    float barBottom = 539;
    
    float barWidth = 12;
    float barXleft = 93;
    
    
    float pixScale =  (barBottom - barTop) / maxPointsForRiskBar ;
    
    float xLabel = 108;
    
    // red
    
    float barY =  ([[riskass_forms objectAtIndex:currentForm]redThreshold] * pixScale) ;
    
    float barYHeight = (maxPointsForRiskBar - [[riskass_forms objectAtIndex:currentForm]redThreshold] ) * pixScale ;
    
    _riskBarRed.frame = CGRectMake(barXleft, barBottom - barY , barWidth, - barYHeight );
    
    [_riskBarRed setBackgroundColor:[UIColor redColor]];
    
    _riskBarRed.alpha = barsAlpha;
    
    _labelThresholdRed.frame = CGRectMake(xLabel, barBottom - barY - 10, 30, 21);
    
    _labelThresholdRed.text =[[NSString alloc]initWithFormat:@"%d",[[riskass_forms objectAtIndex:currentForm]redThreshold]    ];
    
    // orange
    
    barY =  ([[riskass_forms objectAtIndex:currentForm]orangeThreshold] * pixScale) ;
    
    barYHeight = ([[riskass_forms objectAtIndex:currentForm]redThreshold] - [[riskass_forms objectAtIndex:currentForm]orangeThreshold] ) * pixScale ;
    
    _riskBarOrange.frame = CGRectMake(barXleft, barBottom - barY , barWidth, - barYHeight );
    
    [_riskBarOrange setBackgroundColor:[UIColor orangeColor]];
    
    _riskBarOrange.alpha = barsAlpha;
    
    
    _labelThresholdOrange.frame = CGRectMake(xLabel, barBottom - barY - 10 , 30, 21);
    
    _labelThresholdOrange.text =[[NSString alloc]initWithFormat:@"%d",[[riskass_forms objectAtIndex:currentForm]orangeThreshold]    ];
    
    if ([[riskass_forms objectAtIndex:currentForm]orangeThreshold]  < 1) {
        _labelThresholdOrange.hidden = YES;
    }else{
        
        _labelThresholdOrange.hidden = NO;
        
    }
    
    
    
    // yellow
    
    barY =  ([[riskass_forms objectAtIndex:currentForm]yellowThreshold] * pixScale) ;
    
    barYHeight = ([[riskass_forms objectAtIndex:currentForm]orangeThreshold] - [[riskass_forms objectAtIndex:currentForm]yellowThreshold] ) * pixScale ;
    
    _riskBarYellow.frame = CGRectMake(barXleft, barBottom - barY , barWidth, - barYHeight );
    
    [_riskBarYellow setBackgroundColor:[UIColor yellowColor]];
    
    _riskBarYellow.alpha = barsAlpha;
    
    
    _labelThresholdYellow.frame = CGRectMake(xLabel, barBottom - barY - 10 , 30, 21);
    
    _labelThresholdYellow.text =[[NSString alloc]initWithFormat:@"%d",[[riskass_forms objectAtIndex:currentForm]yellowThreshold]    ];
    
    
    
    
    // green
    
    barY =  ([[riskass_forms objectAtIndex:currentForm]yellowThreshold] * pixScale) ;
    
    barYHeight = ([[riskass_forms objectAtIndex:currentForm]yellowThreshold]  ) * pixScale ;
    
    _riskBarGreen.frame = CGRectMake(barXleft, barBottom - barY , barWidth,  barYHeight );
    
    [_riskBarGreen setBackgroundColor:[UIColor greenColor]];
    
    _riskBarGreen.alpha = barsAlpha;
    
    
    
    
    
    
    
    
    
    //u1 delete

    [_view1 setHidden:YES];
    [_view2 setHidden:YES];
    [_view3 setHidden:YES];
    [_view4 setHidden:YES];
    [_view5 setHidden:YES];
    [_view6 setHidden:YES];
    [_view7 setHidden:YES];
    [_view8 setHidden:YES];
    [_view9 setHidden:YES];
    [_view10 setHidden:YES];
    
    int cat_count=[[[riskass_forms objectAtIndex:currentForm] categories]count];
    
    [_scrollViewQuestions setContentSize:CGSizeMake(1024, 1215+(cat_count*600))]; //7230
    [_scrollViewMailResults setContentSize:CGSizeMake(1024, 1800)];
    
    
    
    viewYincrement = 600;
    
    view1PosY = 655;
    
    
    int categories_count = [[[riskass_forms objectAtIndex:currentForm] categories] count];
    int questions_count = 0;
    int answer_count = 0;
    
    
    int question_no = 1;
    answers = [[NSMutableArray alloc] init];
    questions = [[NSMutableArray alloc] init];
    questions_cat = [[NSMutableArray alloc] init];
    [answers addObject:@"NULL"];
    [questions addObject:@"NULL"];
    [questions_cat addObject:@"NULL"];
    
    int current_y=0;
    
    for (int i=0; i<categories_count; i++) {
        
        current_y=(i*viewYincrement);
        CGRect frame = CGRectMake(28,view1PosY + (current_y),984,512);
        UIView *contentView = [[UIView alloc] initWithFrame:frame];
        contentView.backgroundColor = [UIColor whiteColor];
        
        //Background Image
        NSMutableArray  *bgImages = [NSMutableArray arrayWithObjects:@"helipad.jpg", @"clouds.jpg", @"altitude.jpg", @"takeoff.jpg", @"city.jpg", @"apolets.jpg",nil];
        int randomInt = arc4random() % [bgImages count];
        
        
        UIGraphicsBeginImageContext(frame.size);
        [[UIImage imageNamed:[bgImages objectAtIndex:randomInt]] drawInRect:contentView.bounds];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        contentView.backgroundColor = [UIColor colorWithPatternImage:image];
        
        //Category Title
        
        frame = CGRectMake(20,29,819,30);
        UILabel *categoryTitle = [[UILabel alloc] initWithFrame:frame];
        NSString *catTitle;
        
        
        
        if (i<9) {
            catTitle=[[NSString alloc]initWithFormat:@"0%i : ",(i+1)];
        } else {
            catTitle=[[NSString alloc]initWithFormat:@"%i : ",(i+1)];
        }
        
        
        catTitle=[catTitle stringByAppendingString:[[[riskass_forms objectAtIndex:currentForm] getCategory:i]Title]];
        
        //catTitle=[catTitle stringByAppendingString:[[[[riskass_forms objectAtIndex:currentForm] categories] objectAtIndex:i] Title]];
        
        
        NSString *catName = @"";
        
        catName=[catName stringByAppendingString:[[[riskass_forms objectAtIndex:currentForm] getCategory:i]Title]];
        //catName=[catName stringByAppendingString:[[[[riskass_forms objectAtIndex:currentForm] categories] objectAtIndex:i] Title]];
        
        
        //NSLog(@"----- setting catName %@", catName);
        
        if (i == 0) {  _cat01.text = catName;   }
        
        if (i == 1) {  _cat02.text = catName;   }
        
        if (i == 2) {  _cat03.text = catName;   }
        
        if (i == 3) {  _cat04.text = catName;   }
        
        if (i == 4) {  _cat05.text = catName;   }
        
        if (i == 5) {  _cat06.text = catName;   }
        
        if (i == 6) {  _cat07.text = catName;   }
        
        if (i == 7) {  _cat08.text = catName;   }
        
        if (i == 8) {  _cat09.text = catName;   }
        
        if (i == 9) {  _cat10.text = catName;   }
        
        
        //NSLog(@"_cat01.text  %@", _cat01.text);
        
        
        
        
        categoryTitle.text = catTitle;
        [categoryTitle setFont:[UIFont boldSystemFontOfSize:26]];
        [contentView addSubview:categoryTitle];
        
        //RISK Title
        
        /*
         frame = CGRectMake(20,73,60,25);
         UILabel *riskTitle = [[UILabel alloc] initWithFrame:frame];
         riskTitle.text=@"RISK";
         [riskTitle setFont:[UIFont boldSystemFontOfSize:17]];
         [contentView addSubview:riskTitle];
         */
        
        //NSLog(@"----- setting cattitle %@", catTitle);
        
        
        
        
        questions_count = [[[[riskass_forms objectAtIndex:currentForm] getCategory:i]questions]count];
        //questions_count = [[[[[riskass_forms objectAtIndex:currentForm] categories] objectAtIndex:i]questions]count];
        int yStart = 74;
        int yInc = 41;
        
        //Calculate the buffer between questions
        yInc=410/questions_count;
        if (yInc>100) {
            yInc=100;
        }
        
        //answers
        for (int j=0; j<questions_count; j++) {
            
            
            //Creating the textfield
            frame = CGRectMake(460,yStart+(yInc*j),350,40);
            UIView* view = [[UIView alloc] initWithFrame:frame];
            view.backgroundColor = [UIColor whiteColor];
            view.layer.cornerRadius = 7;
            view.layer.borderWidth = 1;
            view.layer.borderColor = [UIColor lightGrayColor].CGColor;
            frame = view.bounds;
            frame.origin.x = 5;
            frame.size.width -= 5;
            VDLabelWithDropDown *answer = [[VDLabelWithDropDown alloc] initWithFrame:frame];
            answer.backgroundColor = [UIColor clearColor];
            answer.lineBreakMode = NSLineBreakByWordWrapping;
            answer.numberOfLines = 2;
            //        answer.borderStyle = UITextBorderStyleRoundedRect;
            [answer setFont:[UIFont systemFontOfSize:14]];
            answer.dropDownDelegate = self;
            //        [answer addTarget:self action:@selector(fixedListDidEndEditing:)forControlEvents:UIControlEventEditingDidEndOnExit];
            if (j==(questions_count-1)) {
                [answer setTag:2];
            }
            
            [view addSubview:answer];
            [contentView addSubview:view];
            
            //add textfield object to array answers
            [answers addObject:answer];
            
            answer_count = [[[[[riskass_forms objectAtIndex:currentForm] getCategory:i]getQuestion:j]answers]count];
            //answer_count = [[[[[[[riskass_forms objectAtIndex:currentForm] categories] objectAtIndex:i]questions]objectAtIndex:j]answers]count];
            
            
            NSMutableArray *current_answers = [[NSMutableArray alloc] init];
            [current_answers removeAllObjects];
            for (int k=0; k<answer_count; k++) {
                
                [current_answers addObject:[[[[[riskass_forms objectAtIndex:currentForm] getCategory:i] getQuestion:j] getAnswer:k] Answer]];
                //[current_answers addObject:[[[[[[[[riskass_forms objectAtIndex:currentForm] categories] objectAtIndex:i]questions]objectAtIndex:j]answers]objectAtIndex:k]Answer]];
            }
            
            [questions addObject:[[[riskass_forms objectAtIndex:currentForm] getCategory:i] getQuestion:j]];
            //[questions addObject:[[[[[riskass_forms objectAtIndex:currentForm] categories] objectAtIndex:i] questions] objectAtIndex:j]];
            NSString *cat=[[NSString alloc]initWithFormat:@"%i",i];
            [questions_cat addObject:cat];
            
            
            
            answer.items = current_answers;
            
            
            
            
            
        }
        
        //Questions
        for (int j=0; j<questions_count; j++) {
            
            
            frame = CGRectMake(20,yStart+(yInc*j),500,40);
            UILabel *questionTitle = [[UILabel alloc] initWithFrame:frame];
            questionTitle.text = [[[[riskass_forms objectAtIndex:currentForm] getCategory:i] getQuestion:j] Question];
            //questionTitle.text = [[[[[[riskass_forms objectAtIndex:currentForm] categories] objectAtIndex:i] questions] objectAtIndex:j] Question];
            [questionTitle setFont:[UIFont systemFontOfSize:17]];
            
            
            [questionTitle setNumberOfLines:0];
            [questionTitle sizeToFit];
            
            
            [contentView addSubview:questionTitle];
            
            
        }
        
        //response Title
        /*
         frame = CGRectMake(501,45,366,25);
         UILabel *responseTitle = [[UILabel alloc] initWithFrame:frame];
         responseTitle.text=@"RESPONSE";
         [responseTitle setFont:[UIFont boldSystemFontOfSize:17]];
         [contentView addSubview:responseTitle];
         */
        
        
        [contentView setTag:666];
        [_riskass_view addSubview:contentView];
        
        
        _viewResult.center = CGPointMake(520,(view1PosY + current_y + yInc + 795 -10));
        
        question_no+=1;
    }
}




- (void) createFormButtons {
    
    for(UIView *subview in [_riskass_choice subviews]) {
        [subview removeFromSuperview];
    }
    
    //we create one button per location dynamically in our scrollview
    
    int xCoord=100;
    int yCoord=0;
    int buttonWidth=300;
    int buttonHeight=45;
    int buffer = 10;
    
    
    //we take the locations that are already in our locations array
    
    
    for(int i=0; i<[riskass_forms count]; i++) {
        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        aButton.frame     = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
        [aButton setBackgroundImage:[UIImage imageNamed:@"button generic dark.png"] forState:UIControlStateNormal];
        [aButton.titleLabel setFont:[UIFont systemFontOfSize:18]];
        [aButton setTitleColor:[UIColor colorWithWhite:1.0 alpha:1.0] forState:UIControlStateNormal];
        [aButton setTitle:[[riskass_forms objectAtIndex:i] Title] forState:(UIControlStateNormal)];
        [aButton setTag:i];
        [aButton addTarget:self action:@selector(CreateFormViews:) forControlEvents:UIControlEventTouchUpInside];
        [_riskass_choice addSubview:aButton];
        yCoord += buttonHeight + buffer;
        
    }
    
    
    [_riskass_choice setContentSize:CGSizeMake(200, yCoord)];
    [_riskass_choice setScrollEnabled:YES];
    [_riskass_choice setNeedsDisplay];
    
}

-(void) CreateFormViews:(UIButton*)sender {
    
    currentForm=sender.tag;
    [self createRiskAssViews];
    [_riskass_choice_view setHidden:YES];
    [_scrollViewQuestions setHidden:NO];
}

-(void) clearFormViews {
    
}

    
- (IBAction)loadAnotherForm:(id)sender {
    [self clearFormViews];
    [_riskass_choice_view setHidden:NO];
    [_scrollViewQuestions setHidden:YES];
}









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





// start signature process

- (IBAction)buttonActionSignLoadManifest:(id)sender {
    
    _viewSignature.hidden = NO; [_viewMain bringSubviewToFront: _viewSignature];
    
    
    
    
    
    
}




// delete the signature from the manifest

- (IBAction)buttonActionSignatureDelete:(id)sender {
    
    [ signatureControllerRA clearSignature];
    
    if ( scrollSigRA != nil ){
        [ scrollSigRA removeFromSuperview ];
    }
    
    
    statusSignatureRA = 0;
    
}


//  put signature in manifest

- (IBAction)buttonActionSignatureSign:(id)sender {
    
    _buttonSignRiskAssessment.hidden = YES;
    
    statusSignatureRA = 1;
    
    _viewSignature.hidden = YES;
    
    if ( scrollSigRA != nil ){
        [ scrollSigRA removeFromSuperview ];
    }
    
    UIImage *sigImage = [ signatureControllerRA getSignature];
    
    scrollSigRA = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, sigImage.size.width, sigImage.size.height)];
    [scrollSigRA setImage:sigImage];
    
    float scaleFactor = MIN(100/sigImage.size.height, 1.0);  // was 120
    
    
    scrollSigRA.transform = CGAffineTransformScale(scrollSigRA.transform, scaleFactor, scaleFactor);
    
    //scrollSig.frame = CGRectMake(100, 1175, scrollSig.frame.size.width, scrollSig.frame.size.height);
    
    scrollSigRA.frame = CGRectMake(60, 335, scrollSigRA.frame.size.width, scrollSigRA.frame.size.height);
    [ _viewResultPage addSubview:scrollSigRA ];
    
}

//  close signature view

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

//  clear signature

- (IBAction)buttonActionSignatureClear:(id)sender {
    
    
    statusSignatureRA = 0;
    
    [ signatureControllerRA clearSignature];
    
    
    
}





- (IBAction)actionShowRAresultPage:(id)sender {
    
    _viewMailResult.hidden = NO;
    
    [_viewMain bringSubviewToFront:_viewMailResult];
    
    
}







// save Load Manifest As Image


- (IBAction)actionSaveLoadManifestAsImage:(id)sender {
    
    [self saveImage];
    
    
}



- (void)saveImage {
    
    int pixelWidth = _scrollViewMailResults.contentSize.width*1.6;
    int pixelHeight = _scrollViewMailResults.contentSize.height*0.90;  // set hight of pdf page here (cut off the bottom)
    
    CGSize frame=CGSizeMake(pixelWidth, pixelHeight);
    UIGraphicsBeginImageContext(frame);
    
    
    
    CGPoint savedContentOffset = _scrollViewMailResults.contentOffset;
    CGRect savedFrame = _scrollViewMailResults.frame;
    
    
    
    _scrollViewMailResults.contentOffset = CGPointZero;
    _scrollViewMailResults.frame = CGRectMake(0, 0, pixelWidth, pixelHeight);
    
    
    
    [_scrollViewMailResults.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(image, self,@selector(image:didFinishSavingWithError:contextInfo:), nil);
    
    
    _scrollViewMailResults.contentOffset = savedContentOffset;
    _scrollViewMailResults.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! \nThe Summary 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];
        
        
        
        
    }
}




- (void) makeTimeStamp {
    
    
    // Get current UTC time
    
    NSDate *currentDateTime = [NSDate date];
    
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    
    [dateFormatter setDateFormat:@"HH:mm"];
    
    NSTimeZone *localTZ = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTZ];

    
    
    
    NSString *UTCtime = [dateFormatter stringFromDate:currentDateTime];
    
    
    // vFlightTimeScheduled.text = [ [NSString alloc] initWithFormat:@"%@ UTC", UTCtime];
    
    
    
    
    
    [dateFormatter setDateFormat:@"MM"];    NSString *dateMonth = [dateFormatter stringFromDate:currentDateTime];
    
    [dateFormatter setDateFormat:@"dd"];    NSString *dateDay = [dateFormatter stringFromDate:currentDateTime];
    
    [dateFormatter setDateFormat:@"yy"];  NSString *dateYear = [dateFormatter stringFromDate:currentDateTime];
    
   
    
    
    
    // time stamp for first flight
    
    timeStamp = [NSString stringWithFormat:@"%@/%@/%@, Local Time: %@", dateMonth, dateDay, dateYear, UTCtime];
    
    
    return;
    
}







-(IBAction)actionCheckResultFromOPS:(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 {
    
        NSString *url=@"http://";
        url = [url stringByAppendingString:serverhost];
        url = [url stringByAppendingString:@"/api/default/get_occ_data/1.0/?customer="];
        url = [url stringByAppendingString:customer];
        url = [url stringByAppendingString:@"&request_ID="];
        url = [url stringByAppendingFormat:@"%i",request_ID];
        
    
        //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:@""
                                  message:@"No OPS response found yet."
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            //NSLog(@"%@",error);
        } else {
            
            
            //create helicopter objects and store them in helicopters array
            
            NSArray *allItems = [result objectForKey:@"OCC"];
            
            NSString *status;
            NSString *message;
            
            for (int i=0; i<allItems.count; ++i) {
                NSDictionary *item = [allItems objectAtIndex:i];
                message=[item objectForKey:@"message"];
                status=[item objectForKey:@"status"];
                
            }
            
            
            if ([status isEqualToString:@"APPROVED"]) {
                
                NSString *output=@"Your request was approved by OPS. \n";
                output = [output stringByAppendingString:message];
                
                UIAlertView *alert = [[UIAlertView alloc]
                                      initWithTitle:@"APPROVED"
                                      message:output
                                      delegate:self
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
                [alert show];
                
                _buttonOPSSignAndSendRA.hidden=NO;
                _labelOPSStatus.text = @"RA Approved.";
                _labelOPSStatus.backgroundColor = [UIColor greenColor];
                _labelOPSStatus.textColor = [UIColor blackColor];
                
            }
            
            if ([status isEqualToString:@"DECLINED"]) {
                
                UIAlertView *alert = [[UIAlertView alloc]
                                      initWithTitle:@"DECLINED"
                                      message:message
                                      delegate:self
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
                [alert show];
                
                _buttonOPSSignAndSendRA.hidden=YES;
                _labelOPSStatus.text = @"RA Not Approved!";
                _labelOPSStatus.backgroundColor = [UIColor redColor];
                _labelOPSStatus.textColor = [UIColor whiteColor];
                
            }
            
            waiting_for_OCC=false;
            
            _buttonSendRAtoOPS.hidden=YES;
            _buttonCheckResultFromOPS.hidden=YES;
            
            
            
            NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
            
            [defaults  setInteger: 0        forKey: @"waitingForOCCResponse"];

            //NSLog (@"saving waitingForOCCResponse %@ ", [ [NSString alloc] initWithFormat:@"%d ", 0]);
            
            
            
            
        }

        
    }
}

-(IBAction)actionSendRAtoOPS:(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 {
        
        
        //generate request_ID
        
        if (!(waiting_for_OCC)) {
            request_ID=[[NSDate date] timeIntervalSince1970];
        }
        
        
        
        // save request_ID
        
         NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        
        [defaults  setFloat: request_ID        forKey: @"request_ID"];

         //NSLog (@"saving request_ID %@ ", [ [NSString alloc] initWithFormat:@"%d ", request_ID]);
        
        
        // send request to server
        
        NSString *url=@"http://";
        url = [url stringByAppendingString:serverhost];
        url = [url stringByAppendingString:@"/api/default/upload_occ_data/1.0/?customer="];
        url = [url stringByAppendingString:customer];
        url = [url stringByAppendingString:@"&request_ID="];
        url = [url stringByAppendingFormat:@"%i",request_ID];
        
       
        if (pilotNameGlobal.length > 1) {            
            NSString *pilotNameCleaned = pilotNameGlobal;
            pilotNameCleaned = [ pilotNameCleaned stringByReplacingOccurrencesOfString:@"," withString:@""];
            pilotNameCleaned = [ pilotNameCleaned stringByReplacingOccurrencesOfString:@" " withString:@"_"];            
            NSString *crewString = [NSString stringWithFormat:@"&crew=%@",pilotNameCleaned];           
            url = [url stringByAppendingString:crewString];
            //NSLog(@"adding crew: %@",crewString);
        }else{
            url = [url stringByAppendingString:@"&crew=NameNotAvail"]; 
            //NSLog(@"adding nothing");
        }
     


        //NSLog(@"url: %@",url);
        
        int pixelWidth = _scrollViewMailResults.contentSize.width*1.6;
        int pixelHeight = _scrollViewMailResults.contentSize.height*0.8;
        
        pdfDataRA = [NSMutableData data];
        
        UIGraphicsBeginPDFContextToData( pdfDataRA, CGRectMake(0, 0, pixelWidth, pixelHeight),  nil );
        UIGraphicsBeginPDFPage();
        CGPoint savedContentOffset = _scrollViewMailResults.contentOffset;
        CGRect savedFrame = _scrollViewMailResults.frame;
        
        _scrollViewMailResults.contentOffset = CGPointZero;
        _scrollViewMailResults.frame = CGRectMake(0, 0, pixelWidth, pixelHeight);
        
        [_scrollViewMailResults.layer renderInContext: UIGraphicsGetCurrentContext()];
        
        _scrollViewMailResults.contentOffset = savedContentOffset;
        _scrollViewMailResults.frame = savedFrame;
        
        UIGraphicsEndPDFContext();
        
        
        NSData *myData = [NSData dataWithData:pdfDataRA];
        
        NSURLRequest *urlRequest = [self postRequestWithURL:url
                                                       data:myData
                                                   fileName:@"file"];
        occUploadConnection =[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
        
        
        
        
        
    }
}


-(NSURLRequest *)postRequestWithURL: (NSString *)url
                               data: (NSData *)data
                           fileName: (NSString*)fileName
{
    
    //NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    
    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
    [urlRequest setURL:[NSURL URLWithString:url]];
    [urlRequest setHTTPMethod:@"POST"];
    
    NSString *myboundary = [NSString stringWithFormat:@"%@",@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",myboundary];
    [urlRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    NSMutableData *postData = [NSMutableData data]; //[NSMutableData dataWithCapacity:[data length] + 512];
    [postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", myboundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", fileName]dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:[[NSString stringWithFormat:@"%@",@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:[NSData dataWithData:data]];
    [postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", myboundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [urlRequest setHTTPBody:postData];
    return urlRequest;
}




#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
    
    
        // calculate progress and display
        float current = (float)totalBytesWritten / totalBytesExpectedToWrite;
        int percent = current*100;
        //NSLog(@"percent: %@",[NSString stringWithFormat:@"%i%%",percent]);
        //NSLog(@"progress: %f",current);
    
    
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    //NSLog(@"didReceviceResponse");
    

    
    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];
    //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;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
    
    
    
        
        //NSLog(@"didFinishLoading");
        
        NSString *response=[[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
        if ([response isEqualToString:@"OK"]) {
            
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"OPS Control"
                                  message:@"Request successfully sent to OPS"
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            
            _buttonSendRAtoOPS.hidden=YES;
            _buttonOPSSignAndSendRA.hidden=YES;
            _buttonCheckResultFromOPS.hidden=NO;
            
            _labelOPSStatus.text = @"Approval Pending";
            _labelOPSStatus.backgroundColor = [UIColor clearColor];
            _labelOPSStatus.textColor = [UIColor blackColor];
            
            NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
            
            [defaults  setInteger: 0        forKey: @"waitingForOCCResponse"];
            
            //NSLog (@"saving waitingForOCCResponse %@ ", [ [NSString alloc] initWithFormat:@"%d ", 1]);

            
            
        } else if ([response isEqualToString:@"NOK"]) {
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"ERROR"
                                  message:@"OPS could not receive your data."
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
        }
    
    //NSLog(@"response: %@",response);
    
    
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var
    //NSLog(@"didFailwithError %@",error);
    
    
        
        //NSLog(@"didFailwithError %@",error);
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"ERROR"
                              message:@"Please check your internet connection."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
 
    
}

@end
