Saturday, September 14, 2013

CustomScrollBarDelegate


CustomScrollBarDelegate.h


@protocol CustomScrollBarDelegate

@required
- (void)touchesEndedScroll:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesBeganScroll:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMovedScroll:(NSSet *)touches withEvent:(UIEvent *)event;

@optional

@end

CustomScrollBar

CustomScrollBar.h


#import <UIKit/UIKit.h>

#import "CustomScrollBarDelegate.h"

@interface CustomScrollBar : UIScrollView {
@public
NSObject<CustomScrollBarDelegate> *del;
}
@property (nonatomic, assign) NSObject<CustomScrollBarDelegate> *del;

@end

CustomScrollBar.m

#import "CustomScrollBar.h"

@implementation CustomScrollBar

@synthesize del;

#pragma mark -
#pragma mark Touch Delegate methods 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if ([del respondsToSelector:@selector(touchesBeganScroll:withEvent:)]) {
        [del touchesBeganScroll:touches withEvent:event];
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if ([del respondsToSelector:@selector(touchesMovedScroll:withEvent:)]) {
        [del touchesMovedScroll:touches withEvent:event];
    }
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if ([del respondsToSelector:@selector(touchesEndedScroll:withEvent:)]) {
        [del touchesEndedScroll:touches withEvent:event];
    }
}

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


@end

EmergencyContact

#define HelveticaRegular(s) [UIFont fontWithName:@"Helvetica" size:s]

#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "Emergency_Contact.h"

EmergencyContact.h

@interface EmergencyContact : UIViewController<UITableViewDelegate,UITableViewDataSource,ABPeoplePickerNavigationControllerDelegate>{

     
    IBOutlet UITextField *txtName;
    IBOutlet UITextField *txtEmail, *txtPhone;
    IBOutlet UITableView *tblContact;
    
    IBOutlet UIScrollView *scrView;
    
    NSMutableArray *tempArray;
    IBOutlet UIButton *btnSave;
}
@property(nonatomic,strong) NSString *strAllInfo;
@property(nonatomic,retain)Emergency_Contact *objEmergencybean;
@property (nonatomic, retain) NSMutableArray *contactsArray;
@property (nonatomic, retain) ABPeoplePickerNavigationController *contacts;
@property(nonatomic,retain)IBOutlet UIScrollView *scrView;

@end

EmergencyContact.m


#import "EmergencyContact.h"
#import "AppDelegate.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>


@interface EmergencyContact ()

@end

@implementation EmergencyContact

AppDelegate *appDelegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Emergency Contact";
       
    UIBarButtonItem *btnadd = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addContact)];
    self.navigationItem.rightBarButtonItem = btnadd;
    [btnadd release];
    
}

-(void)addContact{
    
    contacts = [[ABPeoplePickerNavigationController alloc] init];
   [contacts setPeoplePickerDelegate:self];
    
   [contacts setDisplayedProperties:[NSArray arrayWithObject:[NSNumber numberWithInt:kABPersonEmailProperty]]];
    [contacts setDisplayedProperties:[NSArray arrayWithObject:[NSNumber numberWithInt:kABPersonPhoneProperty]]];
  
[self presentModalViewController:contacts animated:YES];
}

#pragma mark - AddressBook Delegate Methods

-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person{
    return YES;
}
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
    
     NSString *firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString *lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    
         
    // Compose the full name.
    NSString *fullName = @"";
    // Before adding the first and the last name in the fullName string make sure that these values are filled in.
    if (firstName != nil) {
        fullName = [fullName stringByAppendingString:firstName];
    }
    if (lastName != nil) {
        fullName = [fullName stringByAppendingString:@" "];
        fullName = [fullName stringByAppendingString:lastName];
    }

    tempArray = [[NSMutableArray alloc] init];
    [tempArray addObject:fullName];
    
    NSArray *phones = (NSArray *)ABMultiValueCopyArrayOfAllValues(ABRecordCopyValue(person, kABPersonPhoneProperty));
    NSArray *emails = (NSArray *)ABMultiValueCopyArrayOfAllValues(ABRecordCopyValue(person, kABPersonEmailProperty));
    
      // Make sure that the selected contact has one phone at least filled in.
    if ([phones count] > 0) {
            [tempArray addObject:[phones objectAtIndex:0]];
    }
    else{
        [tempArray addObject:@"No phone number was set."];
    }
    
    // Do the same for the e-mails.
    // Make sure that the selected contact has one email at least filled in.
    if ([emails count] > 0) {
        [tempArray addObject:[emails objectAtIndex:0]];
    }
    else{
        [tempArray addObject:@"No e-mail was set."];
    }
   
    txtName.text =[tempArray objectAtIndex:0];
    txtPhone.text =[tempArray objectAtIndex:1];
    txtEmail.text =[tempArray objectAtIndex:2];
    
    [tempArray release];
    [contacts dismissModalViewControllerAnimated:YES];
    [contacts release];
    
return YES;
}
-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
[contacts dismissModalViewControllerAnimated:YES];
[contacts release];
}


- (BOOL)validateEmailWithString:(NSString*)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

AsyncImage


AsyncImage.h

#import <UIKit/UIKit.h>

#import "ASIHTTPRequest.h"
#import "CustomScrollBar.h"
#import <QuartzCore/QuartzCore.h>


@protocol AsyncImageDelegate

@optional
- (void) reSetFrame:(UIView *)newView;
@end

@interface AsyncImage : UIView<CustomScrollBarDelegate,UIScrollViewDelegate>
{
    NSURLConnection* connection; 
NSMutableData* data; 
UIImageView *image;
    UIImageView *imageView;
UIActivityIndicatorView *scrollingWheel;
    NSString *imgName;
    NSString *strImgurl;
    
    CGRect fullFrame;
    NSString *entryId;

    ASIHTTPRequest *request;
    CustomScrollBar *scroller;
    
    float heightNew;
    float imgWidth, imgHeight;
    
    NSObject<AsyncImageDelegate> *delegate;
}
@property(nonatomic,retain) NSString *entryId;
@property(nonatomic,retain)UIImageView *image;
@property(nonatomic,retain) NSURLConnection* connection;
@property (nonatomic, assign) NSObject<AsyncImageDelegate> *delegate;

-(void)loadImageFromString:(NSString*)url dict:(NSDictionary *)dict;
-(id) initWithFrame:(CGRect)frame;
-(NSString *)applicationDocumentsDirectory;
-(void)cancelConnection;
- (void)loadImageWhileSetObject:(NSString*)url;
-(float)getHeight : (UIImage *)img;
-(UIImage *)resizeImage:(UIImage *)image;
-(void)loadImageForVisibleCell:(NSString*)url dict:(NSDictionary *)dict;
@end

AsyncImage.m

#import "AsyncImage.h"
#import "FishbowlAppDelegate.h"

@implementation AsyncImage
FishbowlAppDelegate *appDelegate;

@synthesize entryId;
@synthesize image;
@synthesize connection;

@synthesize delegate;


- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        
       imageView = [[UIImageView alloc] init];
        
        appDelegate = [FishbowlAppDelegate sharedAppDelegate];

scroller = [[CustomScrollBar alloc] initWithFrame:frame];
        //         scroller = [[CustomScrollBar alloc] initWithFrame:CGRectMake(0, 0, 480, 320)];
scroller.maximumZoomScale = 4.0;
scroller.minimumZoomScale = 1.0;
scroller.clipsToBounds = YES;
// a page is the width of the scroll view
//scroller.backgroundColor = [UIColor redColor];
scroller.scrollEnabled = YES;
scroller.multipleTouchEnabled = YES;
scroller.userInteractionEnabled = YES;
scroller.showsHorizontalScrollIndicator = YES;
scroller.showsVerticalScrollIndicator = YES;
scroller.scrollsToTop = NO;
scroller.delegate = self;
scroller.del = self;
scroller.contentSize = frame.size;

  scrollingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
float x = self.bounds.size.width/2;
float y = self.bounds.size.height/2;
scrollingWheel.center = CGPointMake(x, y);
scrollingWheel.hidesWhenStopped = YES;
       // [scroller addSubview:scrollingWheel];
       // self.clipsToBounds = YES;
        
[self addSubview:scrollingWheel];
        imageView.center = CGPointMake(x, y);
      //  [scroller addSubview:imageView];
        [self addSubview:scroller];
self.clipsToBounds = YES;
        
       // [scroller addSubview:imageView];
        }
    return self;
}
-(void)loadImageFromString:(NSString*)url dict:(NSDictionary *)dict;
{
    scrollingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    float x = self.bounds.size.width/2;
    float y = self.bounds.size.height/2;
    scrollingWheel.center = CGPointMake(x, y);
    scrollingWheel.hidesWhenStopped = YES;
    [self addSubview:scrollingWheel];

  [scrollingWheel startAnimating];
if (connection!=nil) {
        [connection cancel];
[connection release];
        
connection = nil;
        
}
    
    if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}

    if(dict == nil)
    {
        imgName =[[[url componentsSeparatedByString:@"/"] lastObject]retain];
    }
    else
    {
         imgName =[NSString stringWithFormat:@"%@_%@",[[[url componentsSeparatedByString:@"/"] lastObject]retain],[dict objectForKey:@"FacebookId"]];
    
    }
    NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
    
    [imgName retain];
    
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if ([fileManager fileExistsAtPath:imagePath]==NO)
    {
        image.frame = self.bounds;
        image.layer.cornerRadius =5.0f;
    
        NSURLRequest* urequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:urequest delegate:self];
    }
    else
    {
        UIImage *img = [UIImage imageWithContentsOfFile:imagePath];
         [UIImage imageWithContentsOfFile:imagePath];
        
     //   image = [[[UIImageView alloc] initWithImage:img] autorelease];
        image =[[UIImageView alloc] initWithImage:img];
        image.contentMode = UIViewContentModeScaleAspectFit;
        image.frame = self.bounds;
         image.layer.cornerRadius =5.0f;
[self addSubview:image];
    [scrollingWheel stopAnimating];
    }
}

-(void)loadImageForVisibleCell:(NSString*)url dict:(NSDictionary *)dict;
{
    scrollingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    float x = self.bounds.size.width/2;
    float y = self.bounds.size.height/2;
    scrollingWheel.center = CGPointMake(x, y);
    scrollingWheel.hidesWhenStopped = YES;
    [self addSubview:scrollingWheel];
    
  [scrollingWheel startAnimating];
if (connection!=nil) {
        [connection cancel];
[connection release];
        
connection = nil;
}
    
    if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
    
    if(dict == nil)
    {
        imgName =[[[url componentsSeparatedByString:@"/"] lastObject]retain];
    }
    else
    {
        imgName =[NSString stringWithFormat:@"%@_%@",[[[url componentsSeparatedByString:@"/"] lastObject]retain],[dict objectForKey:@"FacebookId"]];
        
    }
    NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
    
    [imgName retain];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:imagePath]==NO)
    {
        image.frame = self.bounds;
        image.layer.cornerRadius =5.0f;
        
        NSURLRequest* urequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:urequest delegate:self];
    }
    else
    {
        UIImage *img = [UIImage imageWithContentsOfFile:imagePath];
        [UIImage imageWithContentsOfFile:imagePath];
        
        //   image = [[[UIImageView alloc] initWithImage:img] autorelease];
        image =[[UIImageView alloc] initWithImage:img];
        image.contentMode = UIViewContentModeScaleAspectFit;
        image.frame = self.bounds;
        image.layer.cornerRadius =5.0f;
[self addSubview:image];
    [scrollingWheel stopAnimating];
    }
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [data release]; 
data=nil;
    [scrollingWheel stopAnimating];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
data = [[NSMutableData data] retain];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataObj {
[data appendData:dataObj];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)theConnection 
{
[connection release];
connection=nil;

     NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
    
    [data writeToFile:imagePath atomically:YES];
    
image = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
  //  image =[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]];
image.contentMode = UIViewContentModeScaleToFill;
    [image setClipsToBounds:YES];
    
  image.frame = self.bounds;
[self addSubview:image];
    
[data release]; 
data=nil;
[scrollingWheel stopAnimating];
    [imgName release];
}
-(NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
-(void)cancelConnection{
    
    if (connection !=nil) {
        [connection cancel];
        connection=nil;
    }
    if(data!=nil){
        [data release]; 
        data=nil;
    }
    
[scrollingWheel stopAnimating];
}
-(void)asyncImageSet:(UIImage *)img
{
    [scrollingWheel startAnimating];
if (connection!=nil) {
[connection release];
connection = nil;
}
if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
    
    image = [[[UIImageView alloc] initWithImage:img] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
    [image setClipsToBounds:YES];
    
    image.frame = self.bounds;
    
    [self addSubview:image];
    [scrollingWheel stopAnimating];
}
#pragma mark -
#pragma mark scrollView Delegate Methods
-(UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return image;
}
#pragma mark -
#pragma mark Touch Delegate Methods
- (void)touchesBeganScroll:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesMovedScroll:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesEndedScroll:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 1) {
        
        [scroller setZoomScale:1.0];
        
        [self setViewAnimation:CGRectMake(0,0, self.bounds.size.width, self.bounds.size.height)];
    }
}
-(void) setViewAnimation:(CGRect)frame {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
    image.frame = self.frame;
    scroller.contentSize = self.frame.size;
    [UIView commitAnimations];
}

- (void)dealloc {
 //   [imgName release];
[scrollingWheel release];
    [super dealloc];
}
@end

Sunday, September 8, 2013

TabBar

TabBar.h


#import <UIKit/UIKit.h>

#define tabBarFrame CGRectMake(0, 768, 1024, 48)

@interface TabBarIphone : UITabBarController <UITabBarControllerDelegate, UITabBarDelegate> {
@public
UIView *view;

}
-(void)setFor:(NSString*)str;

- (void) loadBookContent;

-(void) addCustomElements;
-(void) selectTab:(int)tabID;


@end


#import "TabBarIphone.h"
#import <QuartzCore/QuartzCore.h>
#import "AppDelegate.h"

@implementation TabBarIphone
AppDelegate *appDelegate;

NSString *strForPurpose;
NSString *strAdd;

#pragma mark -
#pragma mark Custom Methods

/*-(void) onClickSave {
[appDelegate saveAction]; 
}*/

TabBar.m

#pragma mark -
#pragma mark Init Methods

-(id) init {
[super init];
    
appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;

self.delegate = self;
self.customizableViewControllers = nil;
        
return self;
}

#pragma mark -
#pragma mark View Methods

- (void)viewDidLoad {
    
    [super viewDidLoad];
self.navigationController.navigationBar.hidden = FALSE;
    
    self.tabBar.backgroundColor = [UIColor whiteColor];
}
- (void)viewWillAppear:(BOOL)animated {
    
[super viewWillAppear:animated];
[self tabBar].hidden = FALSE;
}
-(void)setFor:(NSString*)str {
strAdd=str;
}
- (BOOL)tabBarController:(UITabBarController *)tabBarController 
shouldSelectViewController:(UIViewController *)viewController {
//NSLog(@"didSelectItem:(UITabBarItem *)item  %@ ",viewController);
     return TRUE;
}
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    [appDelegate.navHome popToRootViewControllerAnimated:YES];
    [appDelegate.navNotes popToRootViewControllerAnimated:YES];
    [appDelegate.navUpload popToRootViewControllerAnimated:YES];
    [appDelegate.navResearch popToRootViewControllerAnimated:YES];
    [appDelegate.navForum popToRootViewControllerAnimated:YES];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
[self setSelectedIndex:0];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark Memory Management
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
[super dealloc];
}
@end

AppDelegate

AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate,MBProgressHUDDelegate>
{
    
    UIImageView *splashView;
    UIView *loadView;
    
    UIActivityIndicatorView *spinningWheel;
    NSMutableDictionary *dirUserInfo;
    
    HomeViewController *objHomeView;
    UINavigationController *navHome;
    
    NotesView *objNotesView;
    UINavigationController *navNotes;
    
    UploadView *objUploadView;
    UINavigationController *navUpload;
    
    ResearchView *objResearchView;
    UINavigationController *navResearch;
    
    ForumView *objForumView;
    UINavigationController *navForum;
    
    RecordDetailView *objRecordDet;
    UINavigationController *navRecordDet;
    
    TabBarIphone *tabBarController;
    DBHelper *objHelper;
    
}

AppDelegate.m


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   // [[UIApplication sharedApplication] setStatusBarHidden:YES];
    NSLog(@"appp started");
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
     objHelper = [[DBHelper alloc] init];
        
    // Override point for customization after application launch.
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {

         if (isiPhone5) {
            splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
            splashView.image = [UIImage imageNamed:@"Default-568h@2x"];
        }
        else
        {
            splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
            splashView.image = [UIImage imageNamed:@"Default"];
        }
      
        [self.window addSubview:splashView];
        [self.window makeKeyAndVisible];
        [self performSelector:@selector(loadViewIphone) withObject:nil afterDelay:2.0];
    }
    else 
    {
        splashView = [[UIImageView alloc] initWithFrame:ipadFrame];
        splashView.image = [UIImage imageNamed:@"Default_iPad"];
        [self.window addSubview:splashView];
        [self.window makeKeyAndVisible];
        [self performSelector:@selector(loadViewIpad) withObject:nil afterDelay:2.0];
    }
    [self.window makeKeyAndVisible];
    return YES;
}
-(BOOL)application:(UIApplication *)application
           openURL:(NSURL *)url
 sourceApplication:(NSString *)sourceApplication
        annotation:(id)annotation
{
    // Make sure url indicates a file (as opposed to, e.g., http://)
    if (url != nil && [url isFileURL]) {
        // Tell our OfflineReaderViewController to process the URL
        
        [self attributesForFile:url];
        [self saveFileToDocuments:url];
        [objUploadView handleDocumentOpenURL:url];
    }
        // Indicate that we have successfully opened the URL
    return YES;
}
-(void)loadViewIphone 
{
    [splashView removeFromSuperview];
    LoginView *objLoginView = [[[LoginView alloc] initWithNibName:@"LoginView" bundle:nil] autorelease];
    self.navigationController = [[[UINavigationController alloc] initWithRootViewController:objLoginView] autorelease];
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    CATransition *animation = [CATransition animation];
[animation setDelegate:self];
[animation setType:kCATransitionFade];
[animation setDuration:0.5];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:
  kCAMediaTimingFunctionEaseInEaseOut]];
[[self.window layer] addAnimation:animation forKey:kAnimationKey];
}
-(void)loadViewIpad 
{
    [splashView removeFromSuperview];
    MasterViewController *masterViewController = [[[MasterViewController alloc] initWithNibName:@"MasterViewController_iPad" bundle:nil] autorelease];
    UINavigationController *masterNavigationController = [[[UINavigationController alloc] initWithRootViewController:masterViewController] autorelease];
    
    self.window.rootViewController = masterNavigationController;
    [self.window makeKeyAndVisible];
    CATransition *animation = [CATransition animation];
[animation setDelegate:self];
[animation setType:kCATransitionFade];
[animation setDuration:0.5];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:
  kCAMediaTimingFunctionEaseInEaseOut]];
[[self.window layer] addAnimation:animation forKey:kAnimationKey];
}
-(void)initializeTabbar
{
    UIImage *img;
    
    img = [UIImage imageNamed:@"profile.png"];
    objHomeView = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    navHome = [[UINavigationController alloc] initWithRootViewController:objHomeView];    
    [objHomeView.tabBarItem initWithTitle:@"Home" image:img tag:1];
    
    img = [UIImage imageNamed:@"note.png"];
    objNotesView = [[NotesView alloc] initWithNibName:@"NotesView" bundle:nil];
    navNotes = [[UINavigationController alloc] initWithRootViewController:objNotesView];
    [objNotesView.tabBarItem initWithTitle:@"Notes" image:img tag:2];

    img = [UIImage imageNamed:@"iPhoto.png"];
    objUploadView = [[UploadView alloc] initWithNibName:@"UploadView" bundle:nil];
    navUpload = [[UINavigationController alloc] initWithRootViewController:objUploadView];
    [objUploadView.tabBarItem initWithTitle:@"Upload" image:img tag:3];

    img = [UIImage imageNamed:@"search.png"];
    objResearchView = [[ResearchView alloc] initWithNibName:@"ResearchView" bundle:nil];
    navResearch = [[UINavigationController alloc] initWithRootViewController:objResearchView];
    [objResearchView.tabBarItem initWithTitle:@"Research" image:img tag:4];
    
    img = [UIImage imageNamed:@"Forum1.png"];
    objForumView = [[ForumView alloc] initWithNibName:@"ForumView" bundle:nil];
    navForum = [[UINavigationController alloc] initWithRootViewController:objForumView];
    [objForumView.tabBarItem initWithTitle:@"Forum" image:img tag:5];
    
    tabBarController =[[TabBarIphone alloc] init];
    tabBarController.viewControllers = [NSArray arrayWithObjects:
                                        [self sideMenu].navigationController,
                                        self.navNotes,
                                        self.navUpload,
                                        self.navResearch,
                                        self.navForum,
                                        nil];
}



- (void) showAlertWithTitle:(NSString *)title message:(NSString *)message {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
+(NSDate *) dateFromString:(NSString *)string
{
    NSDateFormatter *formater = [[[NSDateFormatter alloc] init] autorelease];
    [formater setDateFormat:@"yyyy-MM-dd"];
    return [formater dateFromString:string];
}
+(NSString *) stringFromDate:(NSDate *)date
{
    NSDateFormatter *formater = [[[NSDateFormatter alloc] init] autorelease];
    [formater setDateFormat:@"yyyy-MM-dd"];
    return [formater stringFromDate:date];
}
-(NSDate *)convertStringToDate:(NSString *) date format:(NSString *)format {
    
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setDateFormat:format];
nowDate = [formatter dateFromString:date];
    
return nowDate;
}
+(AppDelegate *)sharedAppDelegate {
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
-(NSString*) trimString:(NSString *)theString {
NSString *theStringTrimmed = [theString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
return theStringTrimmed;
}
-(NSString *) removeNull:(NSString *) string {    
    
NSRange range = [string rangeOfString:@"null"];
    //NSLog(@"in removeNull : %d  >>>> %@",range.length, string);
if (range.length > 0 || string == nil) {
string = @"";
}
string = [self trimString:string];
return string;
}

-(UIToolbar *)getNumberKeyboardToolbarWithTarget:(id)target
                                    DoneSelector:(SEL)doneSelector
                                  CancelSelector:(SEL)cancelSelector
{
    UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    numberToolbar.barStyle = UIBarStyleBlackTranslucent;
    numberToolbar.items = [NSArray arrayWithObjects:
                           [[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:target action:cancelSelector],
                           [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                           [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:target action:doneSelector],
                           nil];
    [numberToolbar sizeToFit];
    return numberToolbar;
}
-(void) setDatePickerForTextField:(UITextField *)textfield
                   datePickerMode:(UIDatePickerMode)mode
                           Target:(id)target
                     DoneSelector:(SEL)doneSelector
                   CancelSelector:(SEL)cancelSelector
{
    UIDatePicker *picker = [[[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 216)] autorelease];
    picker.datePickerMode = mode;
    
    if(mode == UIDatePickerModeTime)
        picker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"NL"];
    else
        picker.locale = nil;
    
   // textfield.inputAccessoryView = [self getNumberKeyboardToolbarWithTarget:target DoneSelector:doneSelector CancelSelector:cancelSelector];
    textfield.inputView = picker;
}
-(NSString *) stringFromDate:(NSDate *)date
{
    NSDateFormatter *formater = [[[NSDateFormatter alloc] init] autorelease];
    [formater setDateFormat:@"dd-MM-yyyy"];
    return [formater stringFromDate:date];
}
-(NSString *) timeStringFromDate:(NSDate *)date
{
    NSDateFormatter *formater = [[[NSDateFormatter alloc] init] autorelease];
    [formater setDateFormat:@"HH:mm"];
    return [formater stringFromDate:date];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}
- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}
- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil)
    {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
        {
            /*
             Replace this implementation with code to handle the error appropriately.
             
             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}
#pragma mark - Core Data stack
/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil)
    {
        return __managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}
/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil)
    {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"stratus" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    
    return __managedObjectModel;
    
}
/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"stratus.sqlite"];
        
    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
    {
        /*
         Replace this implementation with code to handle the error appropriately.
         
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    
    return __persistentStoreCoordinator;
}
-(NSString *)saveFileToDocuments:(NSURL *)url {
    
     NSLog(@">>>>>>>>>>>>>>>>>>>>>>>>>>>> to save");
      
    fileName = [url lastPathComponent];
    storePath =[[self applicationDocumentCacheDirectory]stringByAppendingPathComponent:fileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:storePath] == YES) {
        NSLog(@"removeItemAtPath >>>>>>>>>>>>>>>>>> saveFileToDocuments 1 :%@", storePath);
        [[NSFileManager defaultManager] removeItemAtPath:storePath error:NULL];
    }
    
    NSError * error = nil;
    if (url == nil) {
        return nil;
    }
    
    [[NSFileManager defaultManager] copyItemAtURL:url
                                            toURL:[NSURL fileURLWithPath:storePath]
                                            error:&error];
    
    
    if ( error ) {
        NSLog(@"%@", error);
        NSLog(@"removeItemAtPath >>>>>>>>>>>>>>>>>> saveVideoToDocuments 2 :%@", storePath);
        [[NSFileManager defaultManager] removeItemAtPath:storePath error:NULL];
        return nil;
    }
    
    NSData * DocData = [NSData dataWithContentsOfURL:url];
    [DocData writeToFile:storePath atomically:YES];
    [storePath retain];

  //  [objUploadView ReloadView];
    return storePath;
}


#pragma mark - Application's Documents directory
#pragma mark - Document Directory Path
-(NSString *)applicationDocumentCacheDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

}