//
//  NewAccountViewController.m
//  iDing
//
//  Created by MacBook Pro on 28/01/13.
//  Copyright (c) 2013 Abusamy Ltd.. All rights reserved.
//

#import "NewAccountViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "iDingSettings.h"
@implementation NewAccountViewController
@synthesize urlConnection,mutableData;
@synthesize nameTF,countryTF,addressTF,phoneTF,genderTF,emailTF,passwordTF,newAccountScrollView,newsLetterTF,pickerData,createAccountBtn,currentEditfld,genderBtn,gPickerVw,genderPickerView,doneBtn,donetoolbar;

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.pickerData = [[NSArray alloc]initWithObjects:@"M",@"F", nil];
    [self.addressTxtVw.layer setCornerRadius:8];
    self.mutableData = [NSMutableData data];
    
    if (isForiPad)
    {
      //  [self.newAccountScrollView setFrame:CGRectMake(0, 0, 320, 100)];
        //[self.newAccountScrollView setCenter:self.view.center];
    }else{
       
        
    }
    

}

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

#pragma Textfield Delegates

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.currentEditfld = textField;
    [self doneBtnClicked:nil];

    if (isForiPad) {
        return;
    }
	old_scroll_view_origin = self.newAccountScrollView.contentOffset.y;
	fieldsTag = textField.tag;
	if (textField.tag != 6) {
		
		float originContext = isForiPhone5?180:100;
		if (textField.frame.origin.y >= originContext + self.newAccountScrollView.contentOffset.y ) {
			
			[self.newAccountScrollView setContentOffset:CGPointMake(self.view.frame.origin.x, isForiPhone5?textField.frame.origin.y - 160:textField.frame.origin.y - 100)
								 animated:YES];
           
		}
         [self.newAccountScrollView setContentSize:CGSizeMake(self.view.frame.size.width, isForiPhone5?self.view.frame.size.height+160:self.view.frame.size.height+260)];
	}

    
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.currentEditfld = textField;

}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    self.currentEditfld = textField;

    
    return YES;
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    self.currentEditfld = textView;
    
    if (isForiPad) {
        return;
    }

    [self.newAccountScrollView setContentOffset:CGPointMake(self.view.frame.origin.x, isForiPhone5?textView.frame.origin.y - 30:textView.frame.origin.y - 60) animated:YES];
    
}
#pragma mark -
#pragma mark scrollView delegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
	
    if (isForiPad) {
        return;
    }
	old_scroll_view_origin = scrollView.contentOffset.y;
}

#pragma mark -
#pragma mark pickerview delegate

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    [self.genderBtn setTitle:[self.pickerData objectAtIndex:row] forState:UIControlStateNormal];
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [self.pickerData count];
}
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    return [self.pickerData objectAtIndex:row];
}


-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
-(BOOL)isInternetAvailable
{
    BOOL isAvailable;
    Reachability* reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
    if(remoteHostStatus == NotReachable)
    {
        isAvailable = FALSE;
    }
    else if (remoteHostStatus == ReachableViaWiFi)
    {
        isAvailable = TRUE;
    }
    else if (remoteHostStatus == ReachableViaWWAN)
    {
        isAvailable = TRUE;
    }
    return isAvailable;
}

#pragma mark NSURLConnection Delegates
#pragma mark Connection callbacks

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    //
	[self.mutableData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[self.mutableData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    NSString *response = [[NSString alloc]initWithData:self.mutableData encoding:NSASCIIStringEncoding];
   // NSLog(@"the response is %@",response);
    [self parseRegisterResponse:response];

    
}
-(void)parseRegisterResponse:(NSString *)response
{
   // NSLog(@"the response is %@",response);
    if([response rangeOfString:@"success"].location != NSNotFound)
    {
        UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Account created successfully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [connAlert show];
        [connAlert release];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else if([response rangeOfString:@"error"].location != NSNotFound)
    {
        UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Error" message:response delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [connAlert show];
        [connAlert release];
    }
}

- (void)dealloc {
    [self.nameTF        release];
    [self.countryTF     release];
    [self.areaTF        release];
    [self.addressTF     release];
    [self.phoneTF       release];
    [self.genderTF      release];
    [self.emailTF       release];
    [self.passwordTF    release];
    [self.newsLetterTF  release];
    [self.createAccountBtn release];
    [self.newAccountScrollView release];
    [_addressTxtVw release];
    [super dealloc];
}

- (IBAction)createAccountClicked:(UIButton *)sender {
    // http://mocal.mobi/createUsername.php?name=XX&password=XX
    [self.currentEditfld resignFirstResponder];

    NSString *name      = self.nameTF.text;
    NSString *country   = self.countryTF.text;
    NSString *area      = self.areaTF.text;
    NSString *address   = self.addressTxtVw.text;
    NSString *phone     = self.phoneTF.text;
    NSString *email     = self.emailTF.text;
    NSString *password  = self.passwordTF.text;
    NSString *newsLetter= self.newsLetterTF.text;
    NSString *gender    = self.genderBtn.titleLabel.text;


    if ([name length] >0 && [country length] >0 &&[area length] >0 && [address length] >0&&[phone length] >0 && [email length] >0 &&[password length] >0 && [newsLetter length] >0) {
        
        if  (![[newsLetterTF text]isEqualToString:@"1"]||![[newsLetterTF text]isEqualToString:@"0"]) {
            UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please use 0 or 1 for newsletter" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [connAlert show];
            [connAlert release];
            [self.currentEditfld becomeFirstResponder];

            return;
        }
        
        BOOL isNetAvailable = [self isInternetAvailable];
        
        if (isNetAvailable ==TRUE) {
            
            NSString *formURl = [NSString stringWithFormat:@"http://www.theautoi.com/createUsername.php?name=%@&country=%@&area=%@&adress=%@&phone=%@&gender=%@&email=%@&password=%@&newsletter=%@",name,country,area,address,phone,gender,email,password,newsLetter];
            NSURL *url = [NSURL URLWithString:formURl];
            NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc]initWithURL:url]autorelease];
            if(self.urlConnection != nil)
            {
                [self.urlConnection release];
                self.urlConnection = nil;
            }
            [self.urlConnection setAccessibilityHint:@"Register"];
            self.urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];

            
        }else
        {
            UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Connection Alert" message:@"Please check internet connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [connAlert show];
            [connAlert release];
        }
        
    }else
    {
        
      
            UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter all the details" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [connAlert show];
            [connAlert release];
       

    }
    [self.newAccountScrollView setContentSize:CGSizeMake(self.view.frame.size.width,self.view.frame.size.height)];
    
}
- (IBAction)doneBtnClicked:(UIBarButtonItem *)sender {
   // [self.currentEditfld resignFirstResponder];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.25];
    [self.gPickerVw setFrame:isForiPad?CGRectMake(134, self.view.frame.size.height, self.gPickerVw.frame.size.width, self.gPickerVw.frame.size.height):CGRectMake(0, self.view.frame.size.height, self.gPickerVw.frame.size.width, self.gPickerVw.frame.size.height)];
    [UIView commitAnimations];
    
}
- (IBAction)genderBtnClicked:(UIButton *)sender {
    [self.currentEditfld resignFirstResponder];

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.25];
    [self.gPickerVw setFrame:isForiPad?CGRectMake(134, self.view.frame.size.height-self.gPickerVw.frame.size.height, self.gPickerVw.frame.size.width, self.gPickerVw.frame.size.height): CGRectMake(0, isForiPhone5?265:177, self.gPickerVw.frame.size.width, self.gPickerVw.frame.size.height)];
    [UIView commitAnimations];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
   if ([touch view]  == self.newAccountScrollView) {
        [self.currentEditfld resignFirstResponder];
        
    }
}
@end
