//
//  ViewController.m
//  NG911
//
//  Created by Mason Silber on 9/9/11.
//  Copyright (c) 2011 Columbia University. All rights reserved.
//



#import "IMViewController.h"
#import "AboutViewController.h"
#import <CFNetwork/CFNetwork.h>
#import "QuartzCore/QuartzCore.h"

#define Keyboard_Offset 215

#define UIColorFromRGB(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]  

#define kLostDomainKey  @"lostdomain"


@implementation IMViewController
@synthesize messageArray;
@synthesize sendCell;
@synthesize receiveCell;

-(void)dealloc
{
    
    NSLog(@"ViewController dealloc called");
    
    
    // remove self as notification observer
    
    [messageTextBox release];
    [locationManager release];
    [messageArray release];
    [messageTable release];
    [hideKeyboard release];
    [clearConvo release];
    
    [pjclient destroy];
    
    [pjclient release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
    [IMViewController cancelPreviousPerformRequestsWithTarget:self];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{    
    //Initialize view
    self = [super initWithNibName:nil bundle:nil];
    
    [[self navigationController] setNavigationBarHidden:NO];
    messageHasBeenSent = NO;
    
    messageArray = [[NSMutableArray alloc] init];
    
    hideKeyboard = [[UIBarButtonItem alloc] initWithTitle:@"Hide Keyboard" style:UIBarButtonItemStyleBordered target:self action:@selector(hideKeyboard:)];
    
    clearConvo = [[UIBarButtonItem alloc] initWithTitle:@"Clear" style:UIBarButtonItemStylePlain target:self action:@selector(clearConvo:)];
    [[self navigationItem] setRightBarButtonItem:clearConvo];
    
    if( [messageArray count] == 0 ) {
        [clearConvo setEnabled:FALSE];
    } else {
        [clearConvo setEnabled:TRUE];
    }
    
    UIBarButtonItem *quickMessage = [[UIBarButtonItem alloc] initWithTitle:@"Quick Response" style:UIBarButtonItemStyleBordered target:self action:@selector(createQuickResponse:)];
    [[self navigationItem] setLeftBarButtonItem:quickMessage];
    [quickMessage release];
    
    [[self view] setBackgroundColor:[UIColor whiteColor]];
    
    textView = [[UIView alloc] initWithFrame:CGRectMake(0, 376, self.view.frame.size.width, 40)];
    [textView setBackgroundColor:[UIColor underPageBackgroundColor]];
    [[self view] addSubview:textView];
    
    locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager startUpdatingLocation];
    
    NSLog(@"%f,%f",currentLocationCoordinates.latitude, currentLocationCoordinates.longitude);
    
    messageTextBox = [[UITextView alloc] initWithFrame:CGRectMake(50, 5, 200, 30)];
    [messageTextBox setBackgroundColor:[UIColor whiteColor]];
    [[messageTextBox layer] setCornerRadius:6.0];
    [messageTextBox setFont:[UIFont fontWithName:[[messageTextBox font] fontName] size:[(AppDelegate *)[[UIApplication sharedApplication] delegate] textSize]]];
    [messageTextBox setAutocorrectionType:UITextAutocorrectionTypeNo];
    [messageTextBox setAutocapitalizationType:UITextAutocapitalizationTypeSentences];
    [messageTextBox setDelegate:self];
    [textView addSubview:messageTextBox];
    
    messageTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 376) style:UITableViewStylePlain];
    [messageTable setDelegate:self];
    [messageTable setDataSource:self];
    [messageTable setSeparatorColor:[UIColor clearColor]];
    [[self view] addSubview:messageTable];
    
    send = [UIButton buttonWithType:UIButtonTypeCustom];
    [send setFrame:CGRectMake(260, 7, 50, 26)];
    [send setBackgroundImage:[UIImage imageNamed:@"sendbutton@2x.png"] forState:UIControlStateNormal];
    [send addTarget:self action:@selector(sendText:) forControlEvents:UIControlEventTouchUpInside];
    [send setEnabled:NO];
    [textView addSubview:send];
    
    UIButton *photo = [UIButton buttonWithType:UIButtonTypeCustom];
    [photo setFrame:CGRectMake(10, 2, 35, 35)];
    [photo setBackgroundImage:[UIImage imageNamed:@"camera2.png"] forState:UIControlStateNormal];
    [photo addTarget:self action:@selector(getPhoto:) forControlEvents:UIControlEventTouchUpInside];
    [textView addSubview:photo];
    
    numberOfTimesLocationUpdated = 0;
    return self;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"Count: %d",[messageArray count]);
    return [messageArray count];
}

//Use this method to determine the height of the table view cell in order to accommodate 
//multiline messages, as well as images
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Message *messageInUse = [messageArray objectAtIndex:indexPath.row];
    
    if(messageInUse.message != nil && ![[messageInUse message] isEqualToString:@""])
    {
        CGSize size = [[messageInUse message] sizeWithFont:[UIFont systemFontOfSize:[(AppDelegate *)[[UIApplication sharedApplication] delegate] textSize]] constrainedToSize:CGSizeMake([messageTable frame].size.width, [messageTable frame].size.height) lineBreakMode:UILineBreakModeWordWrap];
        return size.height + 34;
    }
    else if(messageInUse.image != nil)
    {
        return 170;
    }
    else return 0;
}

//Display the messages in the cell accordingly. See comments within for details
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *receiveCellIndentifier = @"receiveCell";
    static NSString *sendCellIdentifier = @"sendCell";
    
    Message *messageInUse = [[[messageArray objectAtIndex:indexPath.row] retain] autorelease];
    
    //Sent message
    if ([messageInUse sent]) {
        
        UITableViewCell *sCell = [tableView dequeueReusableCellWithIdentifier:sendCellIdentifier];
        
        if (sCell == nil) {
            [[NSBundle mainBundle] loadNibNamed:@"sendCell" owner:self options:nil];
            sCell = sendCell;
            self.sendCell = nil;
        }
        
        UILabel *msgLabel = (UILabel *) [sCell viewWithTag:1];
        UILabel *dateLabel = (UILabel *) [sCell viewWithTag:2];
        NSLog(@"Text");
        
        [msgLabel setFont:[UIFont systemFontOfSize:[(AppDelegate *)[[UIApplication sharedApplication] delegate] textSize]]];
        msgLabel.text = [messageInUse message];
        
        CGSize size = [[messageInUse message] sizeWithFont:[UIFont systemFontOfSize:[(AppDelegate *)[[UIApplication sharedApplication] delegate] textSize]] constrainedToSize:CGSizeMake([messageTable frame].size.width, [messageTable frame].size.height) lineBreakMode:UILineBreakModeWordWrap];
        [msgLabel setFrame:CGRectMake(0, msgLabel.frame.origin.y, 315, size.height)];
        
        dateLabel.text = messageInUse.timeStamp;
        
        //Set frame of the text label and the time stamp in order to look good in the cell given a variable message size
        CGFloat A = sCell.frame.size.height;
        CGFloat B = msgLabel.frame.size.height;
        CGFloat C = msgLabel.frame.origin.y;
        CGFloat dateLabelY = (A + B + C - 10)/2;
        
        [dateLabel setFrame:CGRectMake(0, dateLabelY , 315, 10)];
        
        return sCell;
    } 

    // received message
    else 
    {
        UITableViewCell *rCell = [tableView dequeueReusableCellWithIdentifier:receiveCellIndentifier];
        if (rCell == nil) {
            [[NSBundle mainBundle] loadNibNamed:@"receiveCell" owner:self options:nil];
            rCell = receiveCell;
            self.receiveCell = nil;
        }
        
        UILabel *msgLabel = (UILabel *) [rCell viewWithTag:1];
        UILabel *dateLabel = (UILabel *) [rCell viewWithTag:2];
        [msgLabel setFont:[UIFont systemFontOfSize:[(AppDelegate *)[[UIApplication sharedApplication] delegate] textSize]]];
        
        msgLabel.text = [messageInUse message];
        CGSize size = [[messageInUse message] sizeWithFont:[UIFont systemFontOfSize:[(AppDelegate *)[[UIApplication sharedApplication] delegate] textSize]] constrainedToSize:CGSizeMake([messageTable frame].size.width, [messageTable frame].size.height) lineBreakMode:UILineBreakModeWordWrap];
        [msgLabel setFrame:CGRectMake(5, msgLabel.frame.origin.y, 315, size.height)];
        
        dateLabel.text = messageInUse.timeStamp;
        
        //Set label sizes in order to accommodate varying length messages
        CGFloat A = rCell.frame.size.height;
        CGFloat B = msgLabel.frame.size.height;
        CGFloat C = msgLabel.frame.origin.y;
        CGFloat dateLabelY = (A + B + C - 10);
        
        NSLog(@"%@\n%@\n%f\n%f\n%f\n%f\n",rCell,dateLabel,A,B,C,dateLabelY);
        
        [dateLabel setFrame:CGRectMake(5, A+B-30 , 315, 10)];
        
        return rCell;
        
    }
}

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    cell.layer.cornerRadius = 12;
    
}

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    currentLocationCoordinates = newLocation.coordinate;
    
    // Use LoST to get closes SIP server
    if (oldLocation == nil){
        [self performSelectorInBackground:@selector(initLostRequest) withObject:nil];    
    }
    
    //Check how many times location has been received
    //Once it's been received a few times, only track significant changes in order to
    //conserve battery life
    if(numberOfTimesLocationUpdated < 3)
    {
        numberOfTimesLocationUpdated++;
    }
    else
    {
        [locationManager stopUpdatingLocation];
        [locationManager startMonitoringSignificantLocationChanges];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    NSLog(@"View will appear");
    [messageTextBox resignFirstResponder];
}

//When the user clicks the text box to begin typing
-(void)textViewDidBeginEditing:(UITextField *)textField
{
    //Animation that is in sync with the keyboard emerging
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationCurveEaseInOut animations:^
     {
         CGRect frame = [messageTable frame];
         frame.size.height -= Keyboard_Offset;
         [messageTable setFrame:frame];
         
         frame = [textView frame];
         frame.origin.y -= Keyboard_Offset;
         [textView setFrame:frame];
         
     }
                     completion:NULL];
    
    //Scroll to the bottom of the message thread (i.e. the latest message)
    if([messageArray count] == 0)
    {
        [messageTable setContentOffset:CGPointMake(0, 0)];
    }
    else
    {
        [messageTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:([messageArray count] - 1) inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
    //Change navigation bar button
    [[self navigationItem] setRightBarButtonItem:hideKeyboard];
}

//When the user clicks the "Hide keyboard" button
-(void)textViewDidEndEditing:(UITextField *)textField
{
    //Animation that is in sync with the keyboard moving off the screen
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationCurveEaseInOut animations:^
     {
         CGRect frame = [messageTable frame];
         frame.size.height += Keyboard_Offset;
         [messageTable setFrame:frame];
         
         frame = [textView frame];
         frame.origin.y += Keyboard_Offset;
         [textView setFrame:frame];
         
     }
                     completion:NULL];
    [[self navigationItem] setRightBarButtonItem:clearConvo];
    
    //Scroll to the bottom message in the text conversation
    if([messageTable contentSize].height > [messageTable frame].size.height)
    {
        [messageTable setContentOffset:CGPointMake(0, [messageTable contentSize].height - [messageTable frame].size.height)];
    }
    else
    {
        [messageTable setContentOffset:CGPointMake(0, 0)];
    }
    
}

//Detect whether the "send" button should be enabled based on whether there is 
//text in the send message box or not
-(void)textViewDidChange:(UITextView *)textField
{
    if(![[textField text] isEqualToString:@""])
    {
        [send setEnabled:YES];
    } 
    else {
        [send setEnabled:NO];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if(interfaceOrientation == UIInterfaceOrientationPortrait) return YES;
    else return NO;
}

//Method that returns a UI component
//It returns a label that contains the current date and time formatted correctly
-(UILabel *)labelWithDate
{
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMM dd, yyyy h:mm:ss a"];
    NSString *dateString = [formatter stringFromDate:currentDate];
    [formatter release];
    
    UILabel *dateLabel = [[[UILabel alloc] init] autorelease];
    [dateLabel setText:dateString];
    [dateLabel setTextAlignment:UITextAlignmentCenter];
    
    return dateLabel;
}

//Method to format the date into a string correctly
-(NSString *)getFormattedDate
{
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"MMM dd, yyyy h:mm:ss a"];
    NSString *dateString = [formatter stringFromDate:currentDate];
    return dateString;
}

//Send method
-(void)sendText:(id)sender
{
    NSLog(@"Send text called.");
    Message *newMessage;
    
    if([sender isKindOfClass:[UIButton class]])
    {
        newMessage = [[Message alloc] initWithMessage:[messageTextBox text]];
    }
    else
    {
        newMessage = [[Message alloc] initWithMessage:[(Message *)sender message]];
    }
    
    //Send location via a PIDF object
    CLLocation *location = [[CLLocation alloc] initWithLatitude:currentLocationCoordinates.latitude longitude:currentLocationCoordinates.longitude];
    PIDF_LO_Client *PIDFClient = [[PIDF_LO_Client alloc] initWithLocation:location];
    [newMessage setPIDFClient:PIDFClient];
    [newMessage setSent:YES];
    [PIDFClient release];
    [location release];
    
    //Add the message to the UI
    [messageArray addObject:newMessage];
    [messageTable reloadData];
    [messageTable setContentOffset:CGPointMake(0, [messageTable frame].size.height - 376)];
    [messageTextBox setText:@""];
    [send setEnabled:NO];
    [clearConvo setEnabled:TRUE];
    
    //Resize table based on number of messages
    if([messageTable contentSize].height > [messageTable frame].size.height)
    {
        [messageTable setContentOffset:CGPointMake(0, [messageTable contentSize].height - [messageTable frame].size.height)];
    }
    else
    {
        [messageTable setContentOffset:CGPointMake(0, 0)];
    }
    
    // send the message
    [pjclient sendMsg:newMessage to:@"ng911"];
    [newMessage release];
    
    //Scroll to the messsage that was just sent
    NSIndexPath *last = [NSIndexPath indexPathForRow:([messageArray count] - 1) inSection:0];
    [messageTable scrollToRowAtIndexPath:last atScrollPosition:UITableViewScrollPositionNone animated:YES];
}

//Display menu to either take new photo or send an existing one in the user's photo album
-(void)getPhoto:(id)sender
{
    [messageTextBox resignFirstResponder];
    UIActionSheet *photoOptions = [[UIActionSheet alloc] initWithTitle:nil 
                                                              delegate:self 
                                                     cancelButtonTitle:@"Cancel" 
                                                destructiveButtonTitle:nil 
                                                     otherButtonTitles:@"Take Photo", @"Choose Existing", nil];
    [photoOptions setTag:0];
    
    [photoOptions showInView:[self view]];
    [photoOptions release];
}

//Display menu to clear conversation on the user's screen (won't delete messages)
-(void)clearConvo:(id)sender
{
    UIActionSheet *clearActionSheet = [[UIActionSheet alloc] initWithTitle:@"Are you sure you want to clear the conversation?" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Clear" otherButtonTitles:nil, nil];
    [clearActionSheet setTag:1];
    [clearActionSheet showInView:[self view]];
    [clearActionSheet release];
}

//Method to hide keyboard
-(void)hideKeyboard:(id)sender
{
    for(UIView *view in [textView subviews])
    {
        if([view isMemberOfClass:[UITextView class]])
        {
            [view resignFirstResponder];
        }
    }
}

-(void)about:(id)sender
{
    AboutViewController *aboutViewController = [[AboutViewController alloc] init];
    [aboutViewController setTitle:@"About NG911"];
    [[self navigationController] pushViewController:aboutViewController animated:YES];
    [aboutViewController release];
}

//Create and display a quick response view to send a quick response message
-(void)createQuickResponse:(id)sender
{
    QuickResponseViewController *quickResponse = [[QuickResponseViewController alloc] initWithNibName:nil bundle:nil];
    [quickResponse setMyDelegate:self];
    [quickResponse setTitle:@"Quick Response"];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:quickResponse];
    [self presentModalViewController:nav animated:YES];
    [quickResponse release];
    [nav release];
}

//QuickResponseDelegate method
-(void)quickResponseDismissed:(NSString *)typeOfResponse
{
    if([typeOfResponse isEqualToString:@"Cancel"])
    {
        NSLog(@"Cancel");
        return;
    }
    
    //Need to create special messages here
    Message *quickTextMessage = [[Message alloc] initWithMessage:[NSString stringWithFormat:@"Quick response: %@",typeOfResponse]];
    
    [self sendText:quickTextMessage];
    [quickTextMessage release];
}

//ActionSheet delegate method
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //Choose photo
    if(actionSheet.tag == 0)
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        
        //Take new photo
        if(buttonIndex == 0)
        {
            if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                UIAlertView *noCameraAlert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                        message:@"This device does not support a camera"
                                                                       delegate:nil
                                                              cancelButtonTitle:@"OK"
                                                              otherButtonTitles:nil, nil];
                [noCameraAlert setTag:1];
                [noCameraAlert show];
                [noCameraAlert release];
                return;
            }
            
            [picker setSourceType:UIImagePickerControllerSourceTypeCamera];
            [picker setCameraFlashMode:UIImagePickerControllerCameraFlashModeOff];
            [picker setShowsCameraControls:YES];
            [picker setAllowsEditing:NO];
            [self presentModalViewController:picker animated:YES];
            
        }
        //Choose existing photo
        else if(buttonIndex == 1)
        {
            if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
            {
                UIAlertView *noCameraAlert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                        message:@"This device does not support a photo library"
                                                                       delegate:nil
                                                              cancelButtonTitle:@"OK"
                                                              otherButtonTitles:nil, nil];
                [noCameraAlert setTag:2];
                [noCameraAlert show];
                [noCameraAlert release];
                return;
            }
            
            [picker setSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
            
            [picker setAllowsEditing:NO];
            [self presentModalViewController:picker animated:YES];
        }
        else if(buttonIndex != [actionSheet cancelButtonIndex])
        {
            NSLog(@"Error");
        }
        
        [picker release];
    }
    //Clear conversation
    else if(actionSheet.tag == 1)
    {
        if(buttonIndex != [actionSheet cancelButtonIndex])
        {
            
            [messageArray removeAllObjects];
            [messageTable reloadData];
            
            // disable the clear button
            [clearConvo setEnabled:FALSE];
        }
    }
}

//What to do when finished choosing the image to send
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    imageSending = [[LoadingViewController alloc] init];
    [[imageSending loadingLabel] setText:@"Sending..."];
    [[imageSending view] setFrame:CGRectMake(85, 100, 150, 180)];
    
    //Image hosting stuff
    ImgurUploader *uploader = [[ImgurUploader alloc] init];
    [uploader setDelegate:self];
    [uploader uploadImage:[info objectForKey:@"UIImagePickerControllerOriginalImage"]];
    
    NSLog(@"Finished picking media with info");
    Message *imageMessage = [[Message alloc] initWithImage:[info objectForKey:@"UIImagePickerControllerOriginalImage"]];
    [imageMessage setSent:YES];
    [imageMessage setMessage:@""]; // blank text
    
    [messageArray addObject:imageMessage];
    
    [imageMessage release];
    
    [messageTable reloadData];
    [clearConvo setEnabled:TRUE];
    [picker dismissModalViewControllerAnimated:NO];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 
{
    [picker dismissModalViewControllerAnimated:YES];
}

//Receiving a message and displaying it correctly
-(void) messageReceivedFrom:(NSString *)sender WithContent:(id)content {
    
    Message *incomingMessage = [[Message alloc] initWithMessage:(NSString *)content];
    [incomingMessage setSent:NO];
    [messageArray addObject:incomingMessage];
    [messageTable performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
    [clearConvo setEnabled:TRUE];
    
    NSIndexPath *last = [NSIndexPath indexPathForRow:([messageArray count] - 1) inSection:0];
    [messageTable scrollToRowAtIndexPath:last atScrollPosition:UITableViewScrollPositionNone animated:YES];
    
    [incomingMessage release];
    
}

//PJClient finished loading with status
-(void) didFinishLoadingWithStatus:(int)status {
    if (status == 0) {
        // success
        
        printf("PJClient loaded successfully with status: %d\n", status);
        
        
    } else {
        // failed
    }
    
}

//Initialize LOST request
-(void) initLostRequest 
{
    
    LostClient *client = [[LostClient alloc] init];
    
    NSLog(@"Lat: %f, Long: %f", currentLocationCoordinates.latitude, currentLocationCoordinates.longitude);
    
    
    sip_uri = [client lostRequestWithLatitude:currentLocationCoordinates.latitude longitude:currentLocationCoordinates.longitude];
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"SIP URI" message:sip_uri delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    
    //    [alertView performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:NO];
    [alertView release];
    
    [client release];
    
    // set the sip domain URI
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:sip_uri forKey:kLostDomainKey];
    
    // start the pjsip client
    
    pjclient = [PJClient sharedPJClient];
    pjclient.delegate = self;
    
    
    NSOperationQueue *queue = [NSOperationQueue new];
    
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:pjclient selector:@selector(initClientWithLocation:) object:locationManager.location];
    
    //    NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:pjclient selector:@selector(initMedia) object:nil];
    
    [queue addOperation:operation];
    // [queue addOperation:operation2];
    [operation release];
    //    [operation2 release];
    
    [queue release];
    
}

//Having uploaded the image to imgur. Now we can send the link to the other user
-(void)imageUploadedWithURLString:(NSString*)urlString
{
    imgurURL = urlString;
    Message *messageToSend = [[Message alloc] init];
    // send the message
    
    [messageToSend setMessage:imgurURL];
    
    [pjclient sendMsg:messageToSend to:@"ng911"];
    
    [messageToSend release];
    NSLog(@"Uploaded URL: %@",urlString);
    [[imageSending view] removeFromSuperview];
    [imageSending release];
}

//Keeping track of upload
-(void)uploadProgressedToPercentage:(CGFloat)percentage
{
    NSLog(@"Percentage: %2f", percentage);
}

-(void)uploadFailedWithError:(NSError*)error;
{
    NSLog(@"Error uploading: %@",[error description]);
}

@end



