//
//  ftpPage.m
//  AS350B3e
//
//  Created by KulanaMac on 2/17/15.
//
//
/*
 
 
 loadDocumentsFormServer -> showFolder -> showFiles_auth -> showFiles -> loadFile
 
 
 */

#import "DocumentViewer.h"
#import "ViewController.h"
#import "documentFolder.h"
#import "documentFile.h"
#import "Reachability.h"

@interface DocumentViewer ()

@end

float landscapeMode = 0;

@implementation DocumentViewer




/// ================================================================  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];
    }
    
    
}



- (void)willAnimateRotationToInterfaceOrientation:
(UIInterfaceOrientation)toInterfaceOrientation
                                         duration:(NSTimeInterval)duration
{
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
        toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)
    {
        //NSLog(@"switched to Landscape");
        
        [self sortForLandscape];
        
    }
    else
    {
        
        //NSLog(@"switched to Portrait");
        
        [self sortForPortrait];
        
    }
}



- (void) sortForLandscape {
    
    landscapeMode = 1;
    
    
    //NSLog(@"sortForLandscape");
    
    pinchScaleWebView = 0; pinchScaleEndedWebView = 0; moveupDownWebView = 0; moveLeftRightWebView = 0;
    
    
    
    UIImage *background = [UIImage imageNamed:@"Flight_Page.png"];
    [_backgroundMain setImage:background];
    [_backGroundDocViewerMain setImage:background];
    
    _view_documentViewer.frame = CGRectMake( 0, 20, 1024, 1024 ) ;
    
    _backGroundDocViewerMain.frame = CGRectMake( 0, 0, 1024, 748 ) ;
    
    _viewButtonsTop.frame = CGRectMake(579, 0, 452, 50);
    
    _viewDocInfoBottom.frame = CGRectMake(0, 690, 1024, 60);
    
    _lineVertical.frame = CGRectMake(267, 57, 2, 633);
    
    _folder_sview.frame = CGRectMake(19, 148, 230, 515);
    
    _files_sview.frame = CGRectMake(250, 129, 757, 534);
    
    
    
    
    _view_fullscreen.frame = CGRectMake( 0, 20, 1024, 748 ) ;
    
    _backgroundMain.frame = CGRectMake( 0, 0, 1024, 748 ) ;
    
    _files_webview.frame = CGRectMake( 0, 57, 1024, 690 ) ;
    
    _buttonCloseView.frame = CGRectMake(846, 0, 180, 52);
    
    
    
}


- (void) sortForPortrait {
    
    landscapeMode = 0;
    
    //NSLog(@"sortForPortrait");
    
    pinchScaleWebView = 0; pinchScaleEndedWebView = 0; moveupDownWebView = 0; moveLeftRightWebView = 0;
    
    UIImage *background = [UIImage imageNamed:@"Flight_Page.png"];
    [_backgroundMain setImage:background];
    [_backGroundDocViewerMain setImage:background];
        
    _view_documentViewer.frame = CGRectMake( 0, 20, 1024, 1024 ) ;
    
    _backGroundDocViewerMain.frame = CGRectMake( 0, 0, 1024, 748 ) ;
    
    _viewButtonsTop.frame = CGRectMake(579-255, 0, 452, 50);
    
    _viewDocInfoBottom.frame = CGRectMake(0, 1008-60, 1024, 60);
    
    _lineVertical.frame = CGRectMake(267, 57, 2, 1008-60-57);
    
    _folder_sview.frame = CGRectMake(19, 148, 230, 788);
    
    _files_sview.frame = CGRectMake(250, 129, 757, 807);
    
    
    
    _view_fullscreen.frame = CGRectMake( 0, 20, 1024, 748 ) ;
    
    _backgroundMain.frame = CGRectMake( 0, 0, 1024, 748 ) ;
    
    _files_webview.frame = CGRectMake( 0, 57, 769, 949 ) ;
    
    _buttonCloseView.frame = CGRectMake(590, 0, 180, 52);
    
    
    
    
}


- (BOOL)prefersStatusBarHidden {
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    if ([defaults  floatForKey:@"nvgMode"] == 1) {
        return YES;
    }else{
        
        return NO;
        
    }
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    
    UIPinchGestureRecognizer *twoFingerPinch = [[UIPinchGestureRecognizer alloc]
                                                initWithTarget:self
                                                action:@selector(twoFingerPinch:)]
    ;
    
    [[self files_webview] addGestureRecognizer:twoFingerPinch];

    
    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc]
                                             initWithTarget:self
                                             action:@selector(panRecognizer:)]
    ;
    
    [[self files_webview] addGestureRecognizer:panRecognizer];
    
    
    
    UITapGestureRecognizer *singleTapRecognizer = [[UITapGestureRecognizer alloc]
                                                   initWithTarget: self
                                                   action:@selector(handleSingleTapOnView:)];
    
    [singleTapRecognizer setNumberOfTouchesRequired:1];
    [[self files_webview] addGestureRecognizer: singleTapRecognizer];

    
    
    
    
    
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    
    // NVG filter
    
    //NSLog(@"nvgMode %.0f ", [defaults  floatForKey:@"nvgMode"] );
    
    if ([defaults  floatForKey:@"nvgMode"] == 1) {
        
        _viewNVGFilter.hidden = NO;
        
        _viewNVGFilter.alpha = ([defaults  floatForKey:@"_sliderNVG"]/100);
        
        [_viewMain bringSubviewToFront:_viewNVGFilter];
        
        [self prefersStatusBarHidden];
        
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
        
        
    }else{
        
         _viewNVGFilter.hidden = YES;
    }
    
    customer=@"";
    if ([defaults  objectForKey:@"customer"]!=nil) {
        customer=[defaults  objectForKey:@"customer"];
    }
    
    
    
    serverpath=@"http://gyronimo.kulanaserver.com/api/default/";
    serverhost=@"gyronimo.kulanaserver.com";
    serverDocumentPath=@"http://gyronimo.kulanaserver.com/manager/document_files/";
    serverDocumentPath=[serverDocumentPath stringByAppendingString:customer];
    serverDocumentPath=[serverDocumentPath stringByAppendingString:@"/"];
    ACtype=@"AS350B3e";
    
    
    
    [_downloadProgressView setHidden:YES];
    
    allDocuments=[[defaults  objectForKey:@"documentViewMode"] intValue];
    if (allDocuments==0) {
        _label_viewmode.text=@"View Mode: - AC type only -";
    } else {
        _label_viewmode.text=@"View Mode: - All documents -";
    }
    
    
    //init arrays
    folder = [[NSMutableArray alloc]init];
    downloadedFiles = [[NSMutableArray alloc]init];
    downloadedFilesTimestamp = [[NSMutableArray alloc]init];
    openedProtectedFolders = [[NSMutableArray alloc]init];

    
    
    connectedToFleetControl = [defaults floatForKey:@"connectedToFleetControl"];
    
    
    //fleetControl connecton CHECK
    
    if (connectedToFleetControl==1) {
    //fleetControle is connected
        
        
        
        
        
        [_view_notConnected setHidden:true];
        [_view_documentViewer setHidden:false];
        [_view_fullscreen setHidden:true];
        
        if ([defaults  objectForKey:@"documentFolder"]!=nil) {
            
            
            //get saved docFolder
            
            NSData *dataRepresentingSavedArray = [defaults objectForKey:@"documentFolder"];
            if (dataRepresentingSavedArray != nil)
            {
                NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
                if (oldSavedArray != nil)
                    folder = [[NSMutableArray alloc] initWithArray:oldSavedArray];
                else
                    folder = [[NSMutableArray alloc] init];
            }


        }
        
       
        //set downloaded files from default folder array to downloadedFiles array
        for (int i=0; i<folder.count; i++) {
            int filecount=(int)[[[folder objectAtIndex:i]files]count];
            
           //NSLog(@"104 filecount count: %i", filecount);

            
            
            for (int j=0; j<filecount; j++) {
                
                if ([[[[folder objectAtIndex:i]files] objectAtIndex:j]downloaded]==1) {
                    NSString *filename=[[folder objectAtIndex:i]folder];
                    filename=[filename stringByAppendingFormat:@"_%@",[[[[folder objectAtIndex:i]files] objectAtIndex:j]filename]];
                    int lastupdate = [[[[folder objectAtIndex:i]files]objectAtIndex:j]lastupdate];
                    [downloadedFiles addObject:filename];
                    [downloadedFilesTimestamp addObject:[NSString stringWithFormat:@"%i",lastupdate]];
                    
                }
            }
        }
        
        [self showFolder];
        
        
        [self loadDocumentsFromServer];
    
    } else {
        
        //fleetcontrol is not connected
        [_view_notConnected setHidden:false];
        [_view_documentViewer setHidden:true];
        [_view_fullscreen setHidden:true];
    }
    
    
        
}

- (IBAction)actionRefreshData:(id)sender {
    
    [self refreshData];
}



- (void) LoadAllStart {

    
    [self refreshData];
    
    //collecting files
    filesToDownload=[[NSMutableArray alloc] init];
    filesToDownloadFoldertag=[[NSMutableArray alloc] init];
    filesToDownloadTimestamp=[[NSMutableArray alloc] init];
    
    
    for (int i=0; i<folder.count; i++) {
        int filecount=(int) [[[folder objectAtIndex:i]files]count];
        
        for (int j=0; j<filecount; j++) {
            
            if ([[[[folder objectAtIndex:i]files] objectAtIndex:j]downloaded]==0) {
                NSString *filename=[[folder objectAtIndex:i]folder];
                filename=[filename stringByAppendingFormat:@"_%@",[[[[folder objectAtIndex:i]files] objectAtIndex:j]filename]];
                [filesToDownload addObject:filename];
                [filesToDownloadFoldertag addObject:[NSString stringWithFormat:@"%i",i]];
                [filesToDownloadTimestamp addObject:[NSString stringWithFormat:@"%i",[[[[folder objectAtIndex:i]files] objectAtIndex:j]lastupdate]]];
                
            }
        }
    }
    
    if (filesToDownload.count>0) {
        
        multipleDownload=YES;
        filesToDownloadMax=(int)filesToDownload.count;
        filesToDownloadCurrent=0;
        
        _downloadProgressAll.text=[NSString stringWithFormat:@"%i of %i files",0,filesToDownloadMax];
        _downloadProgressBarAll.progress=0.0;
        [_downloadProgressBarAll setHidden:NO];
        
        NSString *downloadURL=[serverDocumentPath stringByAppendingString:[filesToDownload objectAtIndex:0]];
        downloadFileTimestamp=[[filesToDownloadTimestamp objectAtIndex:0]intValue];
        
        downloadFileFoldertag=[[filesToDownloadFoldertag objectAtIndex:0]intValue];
        
        [_downloadProgressView setHidden:NO];
        _downloadProgressBar.progress=0.0;
        _downloadProgress.text=@"";
        [_viewMain bringSubviewToFront:_downloadProgressView];
        
        [_viewMain bringSubviewToFront:_viewNVGFilter];
        
        downloadURL= [downloadURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:downloadURL];
        
        
        downloadRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
        downloadConnection = [[NSURLConnection alloc]initWithRequest:downloadRequest delegate:self startImmediately:YES ];
        [_downloadProgressSpinner startAnimating];
        
        
    } else {
        
        NSString *msg;
        if (allDocuments==1) {
            msg=@"All files are up to date.";
        } else {
            msg=@"All files for the current AC type are up to date.";
        }
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Loading files"
                              message:msg
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        
    }
    
}


- (IBAction)actionLoadAll:(id)sender {
    
    
    if (!([self is_online])) {
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Device offline"
                              message:@"Please make sure that this device is online."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        
    } else {
    
        if (allDocuments==1) {
            
            
            UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Loading files"
                              message:@"Your View Mode shows documents for ALL helictoper types. Do you really want to download all files for all AC types onto this device? \n\n If not, please change View Mode to\n- AC Type Only -."
                              delegate:self
                              cancelButtonTitle:@"CANCEL"
                              otherButtonTitles:@"LOAD ALL DOCUMENTS", nil];

            alertFlag = 2;
            [alert show];
            
            
            
            
        } else {
            
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Loading files"
                                  message:@"Your View Mode shows documents for the current AC type only. If you want to download ALL available fies regardless of the AC type, please change the View Mode to\n- All documents - "
                                  delegate:self
                                  cancelButtonTitle:@"CANCEL"
                                  otherButtonTitles:@"LOAD AC TYPE ONLY", nil];
            
            alertFlag = 3;
            [alert show];

            
            
            
            
            
            
            
            
        }
    
    
    }
}






-(void) refreshData {
    
    if (!([self is_online])) {
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Device offline"
                              message:@"Please make sure that this device is online."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        
    } else {
        
        
        if (allDocuments) {
            _label_viewmode.text=@"View Mode: - All documents -";
            allDocuments=1;
        } else {
            _label_viewmode.text=@"View Mode: - AC type only -";
            allDocuments=0;
        }
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        [defaults setObject:[[NSString alloc]initWithFormat:@"%i",allDocuments] forKey:@"documentViewMode"];
        
        [self loadDocumentsFromServer];
        
    }
    
    
    
    for(UIView *subview in [_files_sview subviews]) {
        [subview removeFromSuperview];
    }
    
    
    [self showFiles_auth:openFolder];
    
    
    
    
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}





//--------------------------------
//functions for connection


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    downloadData = [[NSMutableData alloc]init];
    downloadSize = [response expectedContentLength];
    downloadFilename = [response suggestedFilename];
    
   
    
    //NSLog(@"downloading file: %@",downloadFilename);
}
- (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data
{
    [downloadData appendData: data];
    float progress=((float) [downloadData length] / (float) downloadSize);
    _downloadProgressBar.progress = progress;
    progress=progress*100;
    _downloadProgress.text=[[NSString alloc]initWithFormat:@"%.0f %%",progress];
    
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat: @"%@/%@", applicationDocumentsDir, downloadFilename];
    [downloadData writeToFile:filePath atomically:YES];
    
    //add filename to downloaded array
    //NSLog(@"write file into downloadedfiles: %@",downloadFilename);
    [downloadedFiles addObject:downloadFilename];
    [downloadedFilesTimestamp addObject:[NSString stringWithFormat:@"%i",downloadFileTimestamp]];
    
    
    
    //get current folder tag if multiple download
    currentFolderTag=downloadFileFoldertag;
    
    
    
    //set downloaded flag to file in folder array
    for (int i=0; i<[[[folder objectAtIndex:currentFolderTag] files] count]; i++) {
        NSString *fullpath=[[folder objectAtIndex:currentFolderTag] folder];
        fullpath = [fullpath stringByAppendingFormat:@"_%@",[[[[folder objectAtIndex:currentFolderTag] files]objectAtIndex:i] filename]];
        
        if ([fullpath isEqual:downloadFilename]) {
            
            [[[[folder objectAtIndex:currentFolderTag] files]objectAtIndex:i] setDownloaded];
            [[[[folder objectAtIndex:currentFolderTag] files]objectAtIndex:i] setLastupdate:downloadFileTimestamp];
        }
    }
    
    
    
    //NSLog(@"241 files count: %i",(int)downloadedFiles.count);
    
     _labelDocumentsDownloaded.text = [ [NSString alloc] initWithFormat:@"%d", (int)downloadedFiles.count ] ;
    
    if (downloadedFiles.count == allFilesCount) {
        _labelDocumentsDownloaded.text = @"ALL"; _labelDocumentsDownloaded.textColor = [UIColor greenColor];
    }else{
        
        _labelDocumentsDownloaded.textColor = [UIColor whiteColor];
        
    }
    
    
    
    
    
    
    if (multipleDownload) {
        
        //remove downloaded file from array
        [filesToDownload removeObjectAtIndex:0];
        [filesToDownloadFoldertag removeObjectAtIndex:0];
        [filesToDownloadTimestamp removeObjectAtIndex:0];
        
        filesToDownloadCurrent+=1;
        
        float progress=((float)filesToDownloadCurrent/(float)filesToDownloadMax);
        _downloadProgressBarAll.progress=progress;
        progress=progress*100;
        _downloadProgressAll.text=[NSString stringWithFormat:@"%i of %i files (%i %%)",filesToDownloadCurrent,filesToDownloadMax,(int)progress];
        
        
        
        
        if (filesToDownload.count==0) {
            
            NSString *msg;
            if (allDocuments==1) {
                msg=@"All files were successfully downloaded.";
            } else {
                msg=@"All files for the current AC type were successfully downloaded.";
            }
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Loading files"
                                  message:msg
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            
        }
    }
    
    //check if there are still files to download
    if (filesToDownload.count>0) {
        
        //download next file
        
        NSString *downloadURL=[serverDocumentPath stringByAppendingString:[filesToDownload objectAtIndex:0]];
        downloadFileTimestamp=[[filesToDownloadTimestamp objectAtIndex:0]intValue];
        downloadFileFoldertag=[[filesToDownloadFoldertag objectAtIndex:0]intValue];
        
        
        
        _downloadProgressBar.progress=0.0;
        _downloadProgress.text=@"";
        
        downloadURL= [downloadURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:downloadURL];
        
        downloadRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
        downloadConnection = [[NSURLConnection alloc]initWithRequest:downloadRequest delegate:self startImmediately:YES ];
        [_downloadProgressSpinner startAnimating];
        
        
    } else {
    
    //download process end
        
    [_downloadProgressView setHidden:YES];
    [self showFiles:currentFolderTag];
    
    //save to defaults
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:folder] forKey:@"documentFolder"];
    
        //if single download -> display file
        
        if (multipleDownload==NO) {
            NSURL *targetURL = [NSURL fileURLWithPath:filePath];
            NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
            [_files_webview loadRequest:request];
    
            [self maximize];
        }
    
    }
    
}

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






-(void) actionShowFiles: (UIButton*)sender {
    
    
    openFolder = (int)sender.tag;

    
    for(UIView *subview in [_files_sview subviews]) {
        [subview removeFromSuperview];
    }
    
    
    [self showFiles_auth:(int)sender.tag];
    
    
    
}

-(void) showFiles_auth: (int)tag{
    
    
    currentFolderTag=tag;
    
    //NSLog(@"currentFolderTag %i",currentFolderTag);
    
    bool alreadyOpened=false;
    for (int i=0; i<openedProtectedFolders.count; i++) {
        if ([[[folder objectAtIndex:currentFolderTag] folder] isEqual:[openedProtectedFolders objectAtIndex:i]]) {
            alreadyOpened=true;
        }
    }
    
    if ((!([[[folder objectAtIndex:tag]password]isEqual:@""]))&&(!(alreadyOpened))) {
 
        UIAlertController *alertController = [UIAlertController
                                              alertControllerWithTitle:@"Authorization"
                                              message:@"Please enter the password."
                                              preferredStyle:UIAlertControllerStyleAlert];
        
        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField)
         {
             textField.placeholder = NSLocalizedString(@"Password", @"Password");
             textField.secureTextEntry = YES;
         }];
        
        UIAlertAction *okAction = [UIAlertAction
                                   actionWithTitle:NSLocalizedString(@"OK", @"OK action")
                                   style:UIAlertActionStyleDefault
                                   handler:^(UIAlertAction *action)
                                   {
                                       UITextField *password = alertController.textFields.lastObject;
                                       NSString *password_txt=password.text;
                                       //NSLog(@"%@",password_txt);
                                       if ([password_txt isEqual:[[folder objectAtIndex:currentFolderTag]password]]) {
                                           //NSLog(@"correct");
                                           [self showFiles:currentFolderTag];
                                           
                                           //NSLog(@"show protected file tag %i",tag);
                                           
                                           // position the arrow
                                           
                                           [UIView beginAnimations:nil context:nil];
                                           [UIView setAnimationDuration:0.15];
                                           
                                           
                                           UIImageView* arrow = (UIImageView*)[_folder_sview viewWithTag: 1000 ];
                                           arrow.frame = CGRectMake(18, 34 + (66 * tag), 343, 67);
                                           [UIView commitAnimations];
                                           
                                           
                                           
                                           [openedProtectedFolders addObject:[[folder objectAtIndex:currentFolderTag] folder]];
                                           
   
                                       }
                                   }];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    } else {
        [self showFiles:currentFolderTag];
    }

}

- (void) showFiles: (int)tag {
    
    

    int xCoord=38;
    int yCoord=30;
    int buttonWidth=400;
    int buttonHeight=45;
    int buffer = 66;
    int i=0;
    
    for(UIView *subview in [_files_sview subviews]) {
        [subview removeFromSuperview];
    }
    
    
    for (int j=0; j<[[[folder objectAtIndex:tag] files] count]; j++) {
        
        if (!([[[[[folder objectAtIndex:tag] files] objectAtIndex:j] filename] isEqual:@""])) {
        
        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        aButton.frame     = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
        NSString *title=@" ";
        title=[title stringByAppendingString:[[[[folder objectAtIndex:tag] files] objectAtIndex:j] filename]];
        [aButton setTitle:title  forState:(UIControlStateNormal)];
        [aButton setTag:j];
        [aButton setTitleEdgeInsets:UIEdgeInsetsMake(5.0, 20.0, 5.0, 5.0)];
        [aButton addTarget:self action:@selector(load_file:) forControlEvents:UIControlEventTouchUpInside];
        [_files_sview addSubview:aButton];
        [aButton setBackgroundImage:[UIImage imageNamed: @"button long generic dark.png"] forState:UIControlStateNormal];
        [aButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            
            
        
        aButton.titleLabel.font = [UIFont systemFontOfSize:16];
        aButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            
            
//            // make file symbol
//            
//            
//            UIImageView *fileSymbol =[[UIImageView alloc] initWithFrame:CGRectMake(15, yCoord-4, 15, 30) ];
//            
//            fileSymbol.image=[UIImage imageNamed:@"txt_icon_big.png"];
//            
//            fileSymbol.alpha = 0.9;
//            
//            
//            [_files_sview addSubview:fileSymbol];
            


           
            
        if ([[[[folder objectAtIndex:tag] files] objectAtIndex:j] downloaded]==1) {
            
            UIButton *dButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            dButton.frame     = CGRectMake(xCoord+buttonWidth+15, yCoord+5,35,35);
            
            //[dButton setTitle:@"X"  forState:(UIControlStateNormal)];
            
            [dButton setBackgroundImage:[UIImage imageNamed: @"Checkmark.png"] forState:UIControlStateNormal];
            
            [dButton setTag:j];
            [dButton addTarget:self action:@selector(delete_file:) forControlEvents:UIControlEventTouchUpInside];
            [_files_sview addSubview:dButton];
            dButton.tintColor = [UIColor redColor];
            dButton.titleLabel.font = [UIFont systemFontOfSize:18];
            
           
            
           
            
        }
        
        i+=1;
        yCoord+=buffer;
        
        }
        
    }
    
    
    //NSLog(@"show file tag %i",tag);
    
    // position the arrow
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.15];
    
    UIImageView* arrow = (UIImageView*)[_folder_sview viewWithTag: 1000 ];
    arrow.frame = CGRectMake(18, 34 + (buffer * tag), 343, 67);
    [UIView commitAnimations];
    
    [_files_sview setContentSize:CGSizeMake(592, yCoord+buffer)];
    
    
    
    
    [_files_sview setScrollEnabled:YES];
        
}

- (void) showFolder {
    
    int xCoord=38;
    int yCoord=30;
    int buttonWidth=240;
    int buttonHeight=65;
    int buffer = 66;
    int i=0;
    
    for(UIView *subview in [_files_sview subviews]) {
        [subview removeFromSuperview];
    }
    for(UIView *subview in [_folder_sview subviews]) {
        [subview removeFromSuperview];
    }
    
   
    

    
    for (int j=0; j<folder.count; j++) {
        
        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        aButton.frame     = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
        
        aButton.titleLabel. numberOfLines = 2;
        
        aButton.showsTouchWhenHighlighted = YES;
        
        //aButton.titleLabel.lineBreakMode = NSLineBreakByClipping;
        

        NSString *title= @"";
        title=[title stringByAppendingString:[[folder objectAtIndex:j] folderName]];
        
  
        [aButton setTitle:title  forState:(UIControlStateNormal)];
        [aButton setTag:j];
        [aButton addTarget:self action:@selector(actionShowFiles:) forControlEvents:UIControlEventTouchUpInside];
        [_folder_sview addSubview:aButton];
        

        if ([[[folder objectAtIndex:j] password] isEqual:@""]) {
            
            [aButton setImage: [[UIImage imageNamed: @"folder_icon.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal] forState: UIControlStateNormal];
            
            
        } else {
            [aButton setImage: [[UIImage imageNamed: @"folder_protected_icon.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal] forState: UIControlStateNormal];
            }
        aButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        aButton.titleLabel.font = [UIFont systemFontOfSize:18];
        [aButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        
        i+=1;
        yCoord+=buffer;
        
    }
    
    
    // make arrow
    
    
    UIImageView *arrow =[[UIImageView alloc] initWithFrame:CGRectMake(18, -90, 343, 67) ];
    
    arrow.image=[UIImage imageNamed:@"Arrow for folders-01.png"];
    
    arrow.alpha = 0.8;
    
    arrow.tag = 1000;
    
    [_folder_sview addSubview:arrow];

    
    
    
    [_folder_sview setContentSize:CGSizeMake(230, yCoord+buffer)];
    [_folder_sview setScrollEnabled:YES];
    
}


static UIDocumentInteractionController* docController;


- (IBAction)actionCopyToGoodReader:(id)sender {
    
    

        
    NSURL *targetURL = targetURLTransfer;
    
        NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
        [_files_webview loadRequest:request];
        
        [self maximize];
        [_view_fullscreen setHidden:false];
        [_view_documentViewer setHidden:true];
        
        docController = [UIDocumentInteractionController interactionControllerWithURL:targetURL];
        
        //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.
        
        //[docController presentOpenInMenuFromRect:[self.view convertRect:sender.frame fromView:sender.superview] inView:self.view animated:YES];
    
    [docController presentOpenInMenuFromRect:[_files_webview convertRect:_files_webview.frame fromView:_files_webview.superview] inView:_files_webview animated:YES];
        
        //[docController presentOpenInMenuFromRect:[_view1 convertRect:sender.frame fromView:_view1] inView:_view1 animated:YES];

        
        
        
   
    
    
}

-(void)load_file: (UIButton*)sender {
    
    //NSLog(@"load_file");
    
    if (landscapeMode == 1) {
        _files_webview.frame = CGRectMake( 0 , 57, 1024, 690 ) ;  //NSLog(@"handleSingleTapOnView landscapeMode");
    }else{
        _files_webview.frame = CGRectMake( 0, 57, 769, 949 ) ;  //NSLog(@"handleSingleTapOnView portrait");
        
    }
    
    pinchScaleWebView = 0; pinchScaleEndedWebView = 0; moveupDownWebView = 0; moveLeftRightWebView = 0;
    
    int tag=(int)sender.tag;
    
    NSString *currentFileName=[[folder objectAtIndex:currentFolderTag]folder];
    currentFileName=[currentFileName stringByAppendingFormat:@"_%@",[[[[folder objectAtIndex:currentFolderTag]files]objectAtIndex:tag]filename]];
    
    int lastupdate = [[[[folder objectAtIndex:currentFolderTag]files]objectAtIndex:tag]lastupdate];
    downloadFileTimestamp=lastupdate;
    
    if ([[[[folder objectAtIndex:currentFolderTag]files]objectAtIndex:tag]downloaded]==1) {
        
        
        
        //display directly when already downloaded
        //NSLog(@"already downloaded");
        NSString *html = @"<html><p align=""center"" style=""font-family:Helvetica""><br/><br/>Opening file...</p></html>";
        [_files_webview loadHTMLString:html baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]bundlePath]]];
        
        NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat: @"%@/%@", applicationDocumentsDir, currentFileName];
        //NSLog(@"file: %@",currentFileName);
        
        NSURL *targetURL = [NSURL fileURLWithPath:filePath];
        NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
        [_files_webview loadRequest:request];
        
        [self maximize];
        [_view_fullscreen setHidden:false];
        [_view_documentViewer setHidden:true];
        
        //docController = [UIDocumentInteractionController interactionControllerWithURL:targetURL];
        
        //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.
        
        //[docController presentOpenInMenuFromRect:[self.view convertRect:sender.frame fromView:sender.superview] inView:self.view animated:YES];
        
      
        
        targetURLTransfer = targetURL;
        
    } else {
        
    //try to download
        
        if (!([self is_online])) {
            
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Device offline"
                                  message:@"This document is only available online. Please make sure that this device is connected to the internet."
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            
        } else {
        
        //NSLog(@"need to download");
        NSString *downloadURL=[serverDocumentPath stringByAppendingString:currentFileName];
        
        multipleDownload=NO;
            
        [_downloadProgressView setHidden:NO];
        
        //hide multiple file progress bar
        _downloadProgressAll.text=@"";
        [_downloadProgressBarAll setHidden:YES];
            
        _downloadProgressBar.progress=0.0;
        _downloadProgress.text=@"";
        [_viewMain bringSubviewToFront:_downloadProgressView];
            
            [_viewMain bringSubviewToFront:_viewNVGFilter];
        
        downloadURL= [downloadURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:downloadURL];
        
        
        downloadRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
        downloadConnection = [[NSURLConnection alloc]initWithRequest:downloadRequest delegate:self startImmediately:YES ];
        [_downloadProgressSpinner startAnimating];
            
    
            
        }
    }
    
   
    
}

-(void)delete_file: (UIButton*)sender {
    
    
    tagForwarded =(int)sender.tag;
    
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Delete File"
                          message:@"Do you want to delete this file from this iPad? It will no longer be avaialble in offline mode. However, the file will still be available for download from the Fleet Control server."
                          delegate:self
                          cancelButtonTitle:@"CANCEL"
                          otherButtonTitles:@"DELETE", nil];

    alertFlag = 1;

    [alert show];
    
    
    
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
   
    
    if (alertFlag == 1) {
        
        if (buttonIndex == 0) {
            
            //NSLog (@"OK  ");
            
           
            
        }
        
        
        if (buttonIndex == 1) {
            
          
            int tag= tagForwarded;
            
            //NSLog(@"delete %i",tag);
            
            NSString *currentFilename=[[folder objectAtIndex:currentFolderTag]folder];
            currentFilename=[currentFilename stringByAppendingFormat:@"_%@",[[[[folder objectAtIndex:currentFolderTag]files]objectAtIndex:tag]filename]];
            
            NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *filePath = [NSString stringWithFormat: @"%@/%@", applicationDocumentsDir, currentFilename];
            
            [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
            
            //change downloaded flag in folder array
            [[[[folder objectAtIndex:currentFolderTag]files]objectAtIndex:tag] unsetDownloaded];
            
            //delete from downlaoded array
            for (int i=0; i<downloadedFiles.count;i++) {
                if ([[downloadedFiles objectAtIndex:i] isEqual:currentFilename]) {
                    [downloadedFiles removeObjectAtIndex:i];
                    [downloadedFilesTimestamp removeObjectAtIndex:i];
                }
            }
            
            //save to defaults
            NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
            [defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:folder] forKey:@"documentFolder"];
            
            [self showFiles:currentFolderTag];
            
            
            _labelDocumentsDownloaded.text = [ [NSString alloc] initWithFormat:@"%i", (int)downloadedFiles.count ] ;
            
            if (downloadedFiles.count == allFilesCount) {
                _labelDocumentsDownloaded.text = @"ALL"; _labelDocumentsDownloaded.textColor = [UIColor greenColor];
            }else{
                
                _labelDocumentsDownloaded.textColor = [UIColor whiteColor];
                
            }

            
            
            
            
        }
        
    }
    
    
    if (alertFlag==2) {
        
        if (buttonIndex == 0) {
            //NSLog (@"Nothing  ");
        }
        
        if (buttonIndex == 1) {
            [self LoadAllStart];
        }
    }
    
    if (alertFlag==3) {
        
        if (buttonIndex == 0) {
            //NSLog (@"Nothing  ");
        }
        
        if (buttonIndex == 1) {
            [self LoadAllStart];
        }
    }
    
    
    
    

}




- (IBAction)go_back:(id)sender {
    
              
    
    [self dismissViewControllerAnimated:YES completion:nil];
        
    
}

- (void)maximize {
   
    [_view_fullscreen setHidden:false];
    [_view_documentViewer setHidden:true];
    
}

- (IBAction)minimize:(id)sender {
    
    [_view_fullscreen setHidden:true];
    [_view_documentViewer setHidden:false];
}





- (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;
    }
    
}


- (void)loadDocumentsFromServer {
    
    //Check if server reachable
    
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    customer    = [defaults  stringForKey:@"customer"];
    

    NSMutableArray *folderOfUpdatedFiles = [[NSMutableArray alloc] init];
    
    NSMutableArray *filestodelete = [[NSMutableArray alloc]init];
    NSMutableArray *timestampstodelete = [[NSMutableArray alloc]init];
    
    
    // fleet control
    
    if (!([self is_online])) {
        
        
    } else {
        
        
        
        
        // send request to server
        
        NSString *url=serverpath;
        url = [url stringByAppendingString:@"get_documents/1.0/?customer="];
        url = [url stringByAppendingString:customer];
        
        if (allDocuments==0) {
            url = [url stringByAppendingString:@"&type="];
            url = [url stringByAppendingString:ACtype];
        }
            
        
        //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 {
            
            

            [folder removeAllObjects];
            
            
            NSArray *allItems = [result objectForKey:@"folderData"];
            
            //NSLog(@"folder count: %i", allItems.count);
            
            
            
            
            
            //folder
            for (int i=0; i<allItems.count; i++) {
                
                NSDictionary *item = [allItems objectAtIndex:i];
                NSString *TheFolder=[item objectForKey:@"folder"];
                NSString *TheFolderName=[item objectForKey:@"folderName"];
                NSString *TheACtype=[item objectForKey:@"ACtype"];
                NSString *ThePassword=[item objectForKey:@"password"];
                NSArray *TheFilesArray=[item objectForKey:@"files"];
                NSMutableArray *TheFiles = [[NSMutableArray alloc] init];
                int filecount = [[item objectForKey:@"filecount"]intValue];
                
                if (filecount>0) {
                //files
                for (int j=0; j<TheFilesArray.count;j++){
                    NSDictionary *Fitem = [TheFilesArray objectAtIndex:j];
                    NSString *currentFile =[Fitem objectForKey:@"filename"];
                    NSString *currentPath =TheFolder;
                    currentPath=[currentPath stringByAppendingFormat:@"_%@",currentFile];
                    int lastupdate=[[Fitem objectForKey:@"lastupdate"]intValue];
                    int downloaded=0;
                    
                    
                    
                    //check if file was already downloaded
                    //and if stil current or out of date
                    
                    for (int k=0; k<downloadedFiles.count; k++) {
                        if ([[downloadedFiles objectAtIndex:k] isEqual:currentPath]) {
                            
                            //NSLog(@"FC  file timestamp :%i",lastupdate);
                            //NSLog(@"APP file timestamp: %i",[[downloadedFilesTimestamp objectAtIndex:k] intValue]);
                            if ([[downloadedFilesTimestamp objectAtIndex:k] intValue]==lastupdate) {
                                
                                // downloaded file still current
                                
                                downloaded=1;
                            } else {
                                
                                //file out of date
                                // -> delete file in app
                                // -> don't set downloaded flag
                                
                                NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                                NSString *filePath = [NSString stringWithFormat: @"%@/%@", applicationDocumentsDir, currentPath];
                                [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
                                
                                //NSLog(@"filePath: %@",filePath);
                                
                                //delete objekt from downloadedfiles array
                                [filestodelete addObject:[downloadedFiles objectAtIndex:k]];
                                [timestampstodelete addObject:[downloadedFilesTimestamp objectAtIndex:k]];
                                
                                //collect folder of updated files
                                
                                NSArray *stringArray = [currentPath componentsSeparatedByString: @"_"];
                                NSString *currentFolderString=[stringArray objectAtIndex:0];
                                
                                if (!([folderOfUpdatedFiles containsObject:currentFolderString])) {
                                    [folderOfUpdatedFiles addObject:currentFolderString];
                                }
                                
                                
                            }
                            
                        }
                    }
                    
                    //add file to file array of current folder
                    [TheFiles addObject:[[documentFile alloc] initWithFilename:currentFile AndLastupdate:lastupdate AndDownloaded:downloaded]];
                }
                }
                
                //add folder to folder array
                [folder addObject:[[documentFolder alloc] initWithFolder:TheFolder AndFolderName:TheFolderName AndACtype:TheACtype AndPassword:ThePassword AndFiles:TheFiles]];
            }
            
            //check downloaded files
            //mark files in folderarray as downloaded and delete downloaded files that are not in folderarray any more
            
            NSString *currentfolder;
            NSString *currentfile;
            
            
            for (int i=0; i<downloadedFiles.count; i++) {
                bool exists=false;
                for (int j=0; j<folder.count; j++) {
                    currentfolder=[[folder objectAtIndex:j]folder];
                    int filecount=(int)[[[folder objectAtIndex:j]files]count];
                    for (int k=0; k<filecount; k++) {
                        currentfile=[currentfolder stringByAppendingFormat:@"_%@",[[[[folder objectAtIndex:j]files]objectAtIndex:k]filename]];
                        if ([[downloadedFiles objectAtIndex:i] isEqual:currentfile]) {
                            exists=true;
                        }
                    }
                }
                if (exists) {
                    
                } else {
                    
                    
                    if (allDocuments==1) {
                    //NSLog(@"bestehendes file wird gelöscht.");
                    NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                    NSString *filePath = [NSString stringWithFormat: @"%@/%@", applicationDocumentsDir, [downloadedFiles objectAtIndex:i]];
                    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
                    
                    [filestodelete addObject:[downloadedFiles objectAtIndex:i]];
                        [timestampstodelete addObject:[downloadedFilesTimestamp objectAtIndex:i]];
                    }

                }
            }
            
            
            [downloadedFiles removeObjectsInArray:filestodelete];
            [downloadedFilesTimestamp removeObjectsInArray:timestampstodelete];
            
            
        
            
            
             allFilesCount=0;
            
            for (int i=0; i<folder.count; i++) {
                
                allFilesCount+=[[[folder objectAtIndex:i]files]count];
                
                
                //NSLog(@"folder objectAtIndex %i",  [[[folder objectAtIndex:i]files]count] );
                
            }
            
            
           //NSLog(@"943 folder.count: %i", (int)folder.count );

            _labelDocumentsAvailable.text = [ [NSString alloc] initWithFormat:@"%d", allFilesCount ] ;
            

            
            //save to defaults
            [defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:folder] forKey:@"documentFolder"];
            
            //show folder
            [self showFolder];
            
            
             _labelDocumentsDownloaded.text = [ [NSString alloc] initWithFormat:@"%i", (int)downloadedFiles.count ] ;
            
            if (downloadedFiles.count >= allFilesCount) {
                _labelDocumentsDownloaded.text = @"ALL"; _labelDocumentsDownloaded.textColor = [UIColor greenColor];
            }else{
                
                _labelDocumentsDownloaded.textColor = [UIColor whiteColor];
                
            }

            
            
            
            
        }
    }

    
    if (folderOfUpdatedFiles.count>0) {
        
        NSString *folders = @"At least one file was out of date and therefore deleted on your device. The following folder(s) contain changes: ";
        for (int i=0; i<folderOfUpdatedFiles.count; i++) {
            if (i>0) {
                folders = [folders stringByAppendingFormat:@", "];
            }
            folders = [folders stringByAppendingFormat:@"%@",[folderOfUpdatedFiles objectAtIndex:i]];
        }
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Update Check"
                              message:folders
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        
    }
    
    
    //LIST all documents in App's document directory
    NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //NSLog(@"%@", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:applicationDocumentsDir error:nil]);
    
}


- (IBAction)switch_viewMode:(id)sender {
    if (!([self is_online])) {
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Device offline"
                              message:@"Please make sure that this device is online."
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        
    } else {
        
        
        if (allDocuments) {
            _label_viewmode.text=@"View Mode: - AC type only -";
            allDocuments=0;
        } else {
            _label_viewmode.text=@"View Mode: - All documents -";
            allDocuments=1;
        }
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        [defaults setObject:[[NSString alloc]initWithFormat:@"%i",allDocuments] forKey:@"documentViewMode"];
        
        [self loadDocumentsFromServer];
        
    }

}







- (IBAction)cancelDownload:(id)sender {
    
    [filesToDownload removeAllObjects];
    [filesToDownloadFoldertag removeAllObjects];
    [filesToDownloadTimestamp removeAllObjects];
    
    //downloadConnection = [[NSURLConnection alloc] initWithRequest: downloadRequest delegate:self];
    [downloadConnection cancel];
    
    [_downloadProgressView setHidden:YES];
    [self showFiles:currentFolderTag];
    
    //save to defaults
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:folder] forKey:@"documentFolder"];

}







// perf chart zoom

- (void)twoFingerPinch:(UIPinchGestureRecognizer *)recognizer {
    
     //NSLog(@"twoFingerPinch ");
    
    pinchScaleWebView =  ((recognizer.scale-1) * 2) + pinchScaleEndedWebView;
    
    
    //NSLog(@"pinchScaleWebView ");
    
    if (pinchScaleWebView <= 0) {
        
         //NSLog(@"yep ");
        
        pinchScaleWebView= 0; moveLeftRightWebView = 0; moveupDownWebView= 0;
        
        _files_webview.frame = CGRectMake( 0, 0, _files_webview.frame.size.width, _files_webview.frame.size.height);
        
        
        
        
    }else{
        
        if (pinchScaleWebView > 8.0) {
            pinchScaleWebView = 8.0;
        }
        
        float pixel = pinchScaleWebView * 400;
        
        if (landscapeMode == 1) {
            
            float newWidth = 1024 + pixel;
            
            _files_webview.frame = CGRectMake( 0 - (pixel/2), 57, newWidth, 690 ) ;
            

        }else{
            
            float newWidth = 769 + pixel;
            
            _files_webview.frame = CGRectMake( 0 - (pixel/2), 57, newWidth, 949 ) ;

            
        }
        
        
        
        
        
    }
    
    
    
    if(recognizer.state == UIGestureRecognizerStateEnded)
    {
        pinchScaleEndedWebView = pinchScaleWebView;
        
    }
    
    
}



- (void)panRecognizer:(UIPanGestureRecognizer *)recognizer {
    
   
    CGPoint translation = [recognizer translationInView:self.view];
    
    //moveupDownWebView =  moveupDownWebView + (translation.y / 1);
    
    moveLeftRightWebView = moveLeftRightWebView + (translation.x / 1);
    
    
     //_files_webview.center =  CGPointMake( _files_webview.center.x + moveLeftRightWebView, _files_webview.center.y + moveupDownWebView);
    


    
    _files_webview.frame = CGRectMake( moveLeftRightWebView - (1 * (pinchScaleWebView-1)), moveupDownWebView - (1 * (pinchScaleWebView-1)), _files_webview.frame.size.width, _files_webview.frame.size.height);
    
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];


    
    
    
}


- (void)handleSingleTapOnView:(UIPanGestureRecognizer *)recognizer {
    
   //NSLog(@"handleSingleTapOnView ");
    
    
    if (landscapeMode == 1) {
         _files_webview.frame = CGRectMake( 0 , 57, 1024, 690 ) ;  //NSLog(@"handleSingleTapOnView landscapeMode");
    }else{
        _files_webview.frame = CGRectMake( 0, 57, 769, 949 ) ;  //NSLog(@"handleSingleTapOnView portrait");
        
    }
    
    
    
    
    pinchScaleWebView = 0; pinchScaleEndedWebView = 0; moveupDownWebView = 0; moveLeftRightWebView = 0;
}








@end
