//
//  PlayerViewController.m
//  Allzic
//
//  Created by Alia Bourouis on 24/03/14.
//  Copyright (c) 2014 Alia Bourouis. All rights reserved.
//

#import "PlayerViewController.h"
#import "AppDelegate.h"



@interface PlayerViewController ()

@end

@implementation PlayerViewController

#define remoteControlPlayButtonTapped  @"remoteControlPlayButtonTapped"
#define remoteControlPauseButtonTapped  @"remoteControlPauseButtonTapped"
#define remoteControlStopButtonTapped  @"remoteControlStopButtonTapped"
#define remoteControlForwardButtonTapped  @"remoteControlForwardButtonTapped"
#define remoteControlBackwardButtonTapped  @"remoteControlBackwardButtonTapped"
#define remoteControlOtherButtonTapped  @"remoteControlOtherButtonTapped"
#define remoteControlTogglePlayPauseButtonTapped  @"remoteControlTogglePlayPauseButtonTapped"

@synthesize player,scrollview,isAudioAdToPlay,isDisplayAdToPlay;

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.title = self.screenName = @"player";
    
    /*
    NSMutableDictionary *event;
    event = [[GAIDictionaryBuilder createEventWithCategory:@"UI"
                                                    action:@"navigation"
                                                     label:@"player"
                                                     value:nil] build];
    [[GAI sharedInstance].defaultTracker send:event];
    [[GAI sharedInstance] dispatch];
    */
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self displayBackView];
        
        isDisplayAdToPlay = NO;
        isAudioAdToPlay = NO;
        
        radioLogoDownloader = [[IconDownloader alloc] init];
        radioLogoDownloader.delegate = self;
        radioCoverDownloader = [[IconDownloader alloc] init];
        radioCoverDownloader.delegate = self;
        radioHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, navigationView.frame.origin.y + navigationView.frame.size.height, appDelegate.screenBounds.size.width, 100.0f)];
        CAGradientLayer *gradient = [CAGradientLayer layer];
        gradient.frame = radioHeaderView.bounds;
        gradient.colors = [NSArray arrayWithObjects:
                           (id)[[UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1.0f] CGColor]
                           , (id)[[UIColor colorWithRed:228.0f/255.0f green:228.0f/255.0f blue:228.0f/255.0f alpha:1.0f] CGColor], nil];
        [radioHeaderView.layer insertSublayer:gradient atIndex:0];
        [self.view addSubview:radioHeaderView];
        
        headerReadMoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [headerReadMoreButton setFrame:CGRectMake(0.0f, 0.0f, radioHeaderView.frame.size.width, radioHeaderView.frame.size.height)];
        [headerReadMoreButton addTarget:self action:@selector(displayRadioDescription) forControlEvents:UIControlEventTouchUpInside];
        [radioHeaderView addSubview:headerReadMoreButton];
        
        radioImage = [[UIImageView alloc] initWithFrame:CGRectMake(5.0f, 5.0f, radioHeaderView.frame.size.height - 10.0f, radioHeaderView.frame.size.height - 10.0f)];
        [radioImage setContentMode:UIViewContentModeScaleAspectFit];
        [radioImage setClipsToBounds:YES];
        [radioHeaderView addSubview:radioImage];
        
        radioTitle = [[UILabel alloc] initWithFrame:CGRectMake(radioImage.frame.origin.x + radioImage.frame.size.width + 5.0f, 5.0f, radioHeaderView.frame.size.width - radioImage.frame.origin.x - radioImage.frame.size.width - 10.0f, 20.0f)];
        [radioTitle setFont:[UIFont boldSystemFontOfSize:16]];
        [radioTitle setNumberOfLines:1];
        [radioTitle setBackgroundColor:[UIColor clearColor]];
        [radioTitle setTextColor:[UIColor blackColor]];
        [radioHeaderView addSubview:radioTitle];
        
        descriptionScrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(radioTitle.frame.origin.x, radioTitle.frame.origin.y + radioTitle.frame.size.height, radioTitle.frame.size.width, radioHeaderView.frame.size.height - 60.0f)];
        [descriptionScrollview setBackgroundColor:[UIColor clearColor]];
        [radioHeaderView addSubview:descriptionScrollview];
        
        radioDescription = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, descriptionScrollview.frame.size.width, descriptionScrollview.frame.size.height)];
        [radioDescription setFont:[UIFont systemFontOfSize:14]];
        [radioDescription setNumberOfLines:99];
        [radioDescription setBackgroundColor:[UIColor clearColor]];
        [radioDescription setTextColor:[UIColor blackColor]];
        [descriptionScrollview addSubview:radioDescription];
        
        displayHideDescriptionButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [displayHideDescriptionButton setFrame:CGRectMake(0.0f, 0.0f, descriptionScrollview.frame.size.width, descriptionScrollview.frame.size.height)];
        [displayHideDescriptionButton addTarget:self action:@selector(displayRadioDescription) forControlEvents:UIControlEventTouchUpInside];
        [descriptionScrollview addSubview:displayHideDescriptionButton];
        
        headerReadMoreLabel = [[UILabel alloc] initWithFrame:CGRectMake(descriptionScrollview.frame.origin.x, descriptionScrollview.frame.origin.y + descriptionScrollview.frame.size.height, descriptionScrollview.frame.size.width, 30.0f)];
        [headerReadMoreLabel setFont:[UIFont boldSystemFontOfSize:16]];
        [headerReadMoreLabel setText:@"> Lire la suite"];
        [headerReadMoreLabel setBackgroundColor:[UIColor clearColor]];
        [headerReadMoreLabel setTextColor:[UIColor colorWithRed:39.0f/255.0f green:138.0f/255.0f blue:183.0f/255.0f alpha:1.0f]];
        [radioHeaderView addSubview:headerReadMoreLabel];
        
        playerControlView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, appDelegate.screenBounds.size.height - 100.0f, appDelegate.screenBounds.size.width, 100.0f)];
        if (appDelegate.systemVersion < 7.0) {
            [playerControlView setFrame:CGRectMake(0.0f, appDelegate.screenBounds.size.height - 100.0f - 20.0f, appDelegate.screenBounds.size.width, 100.0f)];
        }
        [playerControlView setBackgroundColor:[UIColor colorWithRed:32.0f/255.0f green:56.0f/255.0f blue:66.0f/255.0f alpha:1.0f]];
        [self.view addSubview:playerControlView];
        
        playStopImage = [[UIImageView alloc] initWithFrame:CGRectMake(25.0f, 7.0f, 30.0f, 30.0f)];
        [playStopImage setImage:[UIImage imageNamed:@"playButton"]];
        [playStopImage setContentMode:UIViewContentModeScaleAspectFit];
        [playStopImage setClipsToBounds:YES];
        [playerControlView addSubview:playStopImage];
        
        playStopButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [playStopButton setFrame:playStopImage.frame];
        [playStopButton setShowsTouchWhenHighlighted:YES];
        [playStopButton addTarget:self action:@selector(startRadio) forControlEvents:UIControlEventTouchUpInside];
        [playerControlView addSubview:playStopButton];
        
        UIImageView *volumeImage = [[UIImageView alloc] initWithFrame:CGRectMake(playStopButton.frame.origin.x + playStopButton.frame.size.width + 10.0f, 12.0f, 20.0f, 20.0f)];
        [volumeImage setImage:[UIImage imageNamed:@"volume"]];
        [volumeImage setContentMode:UIViewContentModeScaleAspectFit];
        [volumeImage setClipsToBounds:YES];
        [playerControlView addSubview:volumeImage];
        
        MPVolumeView *volumeSlider = [[MPVolumeView alloc] initWithFrame:CGRectMake(volumeImage.frame.origin.x + volumeImage.frame.size.width + 5.0f, volumeImage.frame.origin.y, playerControlView.frame.size.width - volumeImage.frame.origin.x - volumeImage.frame.size.width - 25.0f, volumeImage.frame.size.height)];
        [playerControlView addSubview:volumeSlider];
        
        likeRadioImage = [[UIImageView alloc] initWithFrame:CGRectMake(volumeImage.frame.origin.x, playStopButton.frame.origin.y + playStopButton.frame.size.height + 7.0f, 35.0f, 35.0f)];
        [likeRadioImage setImage:[UIImage imageNamed:@"likeRadio"]];
        [likeRadioImage setContentMode:UIViewContentModeScaleAspectFit];
        [likeRadioImage setClipsToBounds:YES];
        [playerControlView addSubview:likeRadioImage];
        
        likeRadioButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [likeRadioButton setFrame:likeRadioImage.frame];
        [likeRadioButton setShowsTouchWhenHighlighted:YES];
        [playerControlView addSubview:likeRadioButton];
        
        UIImageView *facebookRadioImage = [[UIImageView alloc] initWithFrame:CGRectMake(likeRadioImage.frame.origin.x + (volumeSlider.frame.origin.x + volumeSlider.frame.size.width - likeRadioImage.frame.origin.x - 35.0f) / 2, likeRadioImage.frame.origin.y, 35.0f, 35.0f)];
        [facebookRadioImage setImage:[UIImage imageNamed:@"facebook"]];
        [facebookRadioImage setContentMode:UIViewContentModeScaleAspectFit];
        [facebookRadioImage setClipsToBounds:YES];
        [playerControlView addSubview:facebookRadioImage];
        
        UIButton *facebookRadioButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [facebookRadioButton setFrame:facebookRadioImage.frame];
        [facebookRadioButton setShowsTouchWhenHighlighted:YES];
        [facebookRadioButton addTarget:self action:@selector(facebookButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        [playerControlView addSubview:facebookRadioButton];
        
        UIImageView *twitterRadioImage = [[UIImageView alloc] initWithFrame:CGRectMake(playerControlView.frame.size.width - 35.0f - 20.0f, likeRadioImage.frame.origin.y, 35.0f, 35.0f)];
        [twitterRadioImage setImage:[UIImage imageNamed:@"twitter"]];
        [twitterRadioImage setContentMode:UIViewContentModeScaleAspectFit];
        [twitterRadioImage setClipsToBounds:YES];
        [playerControlView addSubview:twitterRadioImage];
        
        UIButton *twitterRadioButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [twitterRadioButton setFrame:twitterRadioImage.frame];
        [twitterRadioButton setShowsTouchWhenHighlighted:YES];
        [twitterRadioButton addTarget:self action:@selector(twitterButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        [playerControlView addSubview:twitterRadioButton];
        
        scrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0.0f, radioHeaderView.frame.origin.y + radioHeaderView.frame.size.height, appDelegate.screenBounds.size.width, playerControlView.frame.origin.y - radioHeaderView.frame.origin.y - radioHeaderView.frame.size.height)];
        [scrollview setPagingEnabled:YES];
        [scrollview setDelegate:self];
        [self.view addSubview:scrollview];
        scrollview.backgroundColor = [UIColor whiteColor];
        
        coverImage = [[UIImageView alloc] initWithFrame:CGRectMake((scrollview.frame.size.width - 200.0f) / 2, (scrollview.frame.size.height - 200.0f) / 2, 200.0f, 200.0f)];
        [coverImage setImage:[UIImage imageNamed:@"cd"]];
        [coverImage setContentMode:UIViewContentModeScaleAspectFit];
        [coverImage setClipsToBounds:YES];
        [scrollview addSubview:coverImage];
        
        tempCoverLeft = [[UIView alloc] initWithFrame:coverImage.frame];
        [tempCoverLeft setBackgroundColor:[UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0f]];
        [scrollview addSubview:tempCoverLeft];
        
        tempCoverRight = [[UIView alloc] initWithFrame:coverImage.frame];
        [tempCoverRight setBackgroundColor:[UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0f]];
        [scrollview addSubview:tempCoverRight];
        [scrollview addSubview:coverImage];
        
        hideDescriptionButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [hideDescriptionButton setFrame:CGRectMake(0.0f, 0.0f, scrollview.frame.size.width, scrollview.frame.origin.y + scrollview.frame.size.height)];
        [hideDescriptionButton setBackgroundColor:[UIColor colorWithWhite:1.0f alpha:0.4f]];
        [hideDescriptionButton addTarget:self action:@selector(hideRadioDescription) forControlEvents:UIControlEventTouchUpInside];
        [hideDescriptionButton setHidden:YES];
        [self.view addSubview:hideDescriptionButton];
        
        loadingView = [[UIView alloc] initWithFrame:CGRectMake(coverImage.frame.origin.x, scrollview.frame.origin.y + coverImage.frame.origin.y, coverImage.frame.size.width, coverImage.frame.size.height)];
        [loadingView setBackgroundColor:[UIColor colorWithWhite:1.0f alpha:0.8f]];
        [loadingView setHidden:YES];
        [self.view addSubview:loadingView];
        
        UIView *loadingBackground = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, loadingView.frame.size.width, loadingView.frame.size.height)];
        [loadingBackground setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.8]];
        loadingBackground.layer.cornerRadius = 5;
        loadingBackground.layer.masksToBounds = YES;
        [loadingView addSubview:loadingBackground];
        
        UIActivityIndicatorView *loadingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [loadingWheel setFrame:CGRectMake(((loadingView.frame.size.width - loadingWheel.frame.size.width)/2), ((loadingView.frame.size.height - loadingWheel.frame.size.height)/2), loadingWheel.frame.size.width, loadingWheel.frame.size.height)];
        [loadingWheel startAnimating];
        [loadingView addSubview:loadingWheel];
        
        UILabel *loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, loadingWheel.frame.origin.y + loadingWheel.frame.size.height + 10.0f, loadingView.frame.size.width, 20.0f)];
        [loadingLabel setTextAlignment:NSTextAlignmentCenter];
        [loadingLabel setText:@"La musique arrive"];
        [loadingLabel setTextColor:[UIColor whiteColor]];
        [loadingLabel setBackgroundColor:[UIColor clearColor]];
        [loadingLabel setFont:[UIFont boldSystemFontOfSize:18.0f]];
        [loadingView addSubview:loadingLabel];
        
        previousIndicator = [[UIImageView alloc] initWithFrame:CGRectMake(10.0f, scrollview.frame.origin.y + (scrollview.frame.size.height/2), 20.0f, 20.0f)];
        [previousIndicator setImage:[UIImage imageNamed:@"prev_radio"]];
        [previousIndicator setContentMode:UIViewContentModeScaleAspectFit];
        [previousIndicator setClipsToBounds:YES];
        [self.view addSubview:previousIndicator];
        
        nextIndicator = [[UIImageView alloc] initWithFrame:CGRectMake(appDelegate.screenBounds.size.width - 30.0f, scrollview.frame.origin.y + (scrollview.frame.size.height/2), 20.0f, 20.0f)];
        [nextIndicator setImage:[UIImage imageNamed:@"next_radio"]];
        [nextIndicator setContentMode:UIViewContentModeScaleAspectFit];
        [nextIndicator setClipsToBounds:YES];
        [self.view addSubview:nextIndicator];
        
        songInfoBackground = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, coverImage.frame.size.height - 75.0f, coverImage.frame.size.width, 75.0f)];
        [songInfoBackground setImage:[UIImage imageNamed:@"songInfoBackground"]];
        [songInfoBackground setContentMode:UIViewContentModeScaleAspectFit];
        [songInfoBackground setClipsToBounds:YES];
        [coverImage addSubview:songInfoBackground];
        
        songSinger = [[UILabel alloc] initWithFrame:CGRectMake(5.0f, 15.0f, songInfoBackground.frame.size.width - 10.0f, (songInfoBackground.frame.size.height - 20.0f) / 2)];
        [songSinger setTextAlignment:NSTextAlignmentCenter];
        [songSinger setFont:[UIFont boldSystemFontOfSize:11]];
        [songSinger setNumberOfLines:2];
        [songSinger setBackgroundColor:[UIColor clearColor]];
        [songSinger setTextColor:[UIColor whiteColor]];
        [songInfoBackground addSubview:songSinger];
        
        songTitle = [[UILabel alloc] initWithFrame:CGRectMake(songSinger.frame.origin.x, songSinger.frame.origin.y + songSinger.frame.size.height, songSinger.frame.size.width, songSinger.frame.size.height)];
        [songTitle setTextAlignment:NSTextAlignmentCenter];
        [songTitle setFont:[UIFont systemFontOfSize:12]];
        [songTitle setNumberOfLines:2];
        [songTitle setBackgroundColor:[UIColor clearColor]];
        [songTitle setTextColor:[UIColor whiteColor]];
        [songInfoBackground addSubview:songTitle];
        
        player = [[MPMoviePlayerController alloc] init];
        if (player) {
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(moviePlayBackStateDidChange:)
                                                         name:MPMoviePlayerPlaybackStateDidChangeNotification
                                                       object:player];
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(moviePlayBackDidFinish:)
                                                         name:MPMoviePlayerPlaybackDidFinishNotification
                                                       object:player];
            
            // If you specify the movie type before playing the movie it can result in faster load time
            [player setMovieSourceType:MPMovieSourceTypeStreaming];
            
            
            // Insert the movie frame in the parent view frame
            [[player view] setFrame:CGRectZero];
            [player view].backgroundColor = [UIColor clearColor];
            [player setControlStyle:MPMovieControlStyleNone];
            [playerControlView addSubview:[player view]];
            
            //Pour l'icone play dans la barre de status
            //[player setUseApplicationAudioSession:NO];
            if([player respondsToSelector:@selector(setAllowsAirPlay:)]) {
                [player setAllowsAirPlay:YES];
            }
            [player setShouldAutoplay:YES];
            [player prepareToPlay];
            
            
            
            
////////////////////////////////////
            /*
            [[AVAudioSession sharedInstance] setDelegate: self];
            NSError *myErr;
            //initialize the AVAudioSession here
            if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&myErr]) {
                //Handle the error here
                NSLog(@"Audio Session error %@, %@", myErr, [myErr userInfo]);
            } else {
                // Since there were no errors initializing the session, we'll allow begin receiving remote control events
                [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
            }
            */
/////////////////////////////////////
            
            
            
        }
        [self initAdBanner];
        [self initAdInterstitial];
        
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:remoteControlPlayButtonTapped object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:remoteControlPauseButtonTapped object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:remoteControlStopButtonTapped object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:remoteControlForwardButtonTapped object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:remoteControlBackwardButtonTapped object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:remoteControlOtherButtonTapped object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:remoteControlTogglePlayPauseButtonTapped object:nil];
        
    }
    return self;
}

- (void)backToParentView {
    
    if (appDelegate.isSearching == YES) {
        [appDelegate.window setRootViewController:appDelegate.searchVC];
    } else {
        [appDelegate.window setRootViewController:appDelegate.oldVC];
    }
}

- (void)selectRadio:(NSDictionary *)radio {
    
    isNewsRadio = NO;
    if ([currentRadio objectForKey:@"id"] != [radio objectForKey:@"id"]) {
        currentRadio = radio;
        isNewsRadio = YES;
        isAacError = NO;
        isMp3Error = NO;
        [songSinger setText:@""];
        [songTitle setText:@""];
        [radioImage setImage:nil];
        [coverImage setImage:[UIImage imageNamed:@"cd"]];
        [self loadImageWithType:0];
        [radioTitle setText:[currentRadio objectForKey:@"title"]];
        NSString *description = [currentRadio objectForKey:@"subtitle"];
        description = [description stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        description = [description stringByReplacingOccurrencesOfString:@"<p>" withString:@""];
        description = [description stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
        [self stopRadio];
        [self startRadio];
        
//////////////////
        NSMutableDictionary *event;
        event = [[GAIDictionaryBuilder createEventWithCategory:@"traffic"
                                                        action:@"radio"
                                                         label:[currentRadio objectForKey:@"title"]
                                                         value:nil] build];
        [[GAI sharedInstance].defaultTracker send:event];
        [[GAI sharedInstance] dispatch];
//////////////////
        
        CGSize textWithin  = CGSizeMake(radioDescription.frame.size.width, 1000);
        NSString *textStr  = description;
        CGSize textSize    = [textStr sizeWithFont:radioDescription.font constrainedToSize:textWithin];
        [radioDescription setText:description];
        
        NSLog(@"RADIO DESCR TEXT HEIGHT : %0.0f ORIGIN.Y : %0.0f RADIO HEADER VIEW HEIGHT : %0.0f",textSize.height,descriptionScrollview.frame.origin.y,radioHeaderView.frame.size.height);
        if (descriptionScrollview.frame.origin.y + textSize.height > radioHeaderView.frame.size.height) {
            [radioDescription setFrame:CGRectMake(radioDescription.frame.origin.x, radioDescription.frame.origin.y, radioDescription.frame.size.width, radioHeaderView.frame.size.height - 60.0f)];
            [descriptionScrollview setFrame:CGRectMake(descriptionScrollview.frame.origin.x, descriptionScrollview.frame.origin.y, descriptionScrollview.frame.size.width, radioDescription.frame.size.height)];
            [descriptionScrollview setContentSize:CGSizeMake(descriptionScrollview.frame.size.width, descriptionScrollview.frame.size.height)];
            [headerReadMoreLabel setHidden:NO];
            [headerReadMoreButton setHidden:NO];
            [displayHideDescriptionButton setHidden:NO];
        } else {
            [radioDescription setFrame:CGRectMake(radioDescription.frame.origin.x, radioDescription.frame.origin.y, radioDescription.frame.size.width, textSize.height)];
            [descriptionScrollview setFrame:CGRectMake(descriptionScrollview.frame.origin.x, descriptionScrollview.frame.origin.y, descriptionScrollview.frame.size.width, radioDescription.frame.size.height)];
            [descriptionScrollview setContentSize:CGSizeMake(descriptionScrollview.frame.size.width, descriptionScrollview.frame.size.height)];
            [headerReadMoreLabel setHidden:YES];
            [headerReadMoreButton setHidden:YES];
            [displayHideDescriptionButton setHidden:YES];
        }
        
        if ([appDelegate.dataController isFavoriteRadioWithId:[radio objectForKey:@"id"]] == NO) {
            [likeRadioButton removeTarget:self action:@selector(unlikeRadioButtonPressed) forControlEvents:UIControlEventTouchUpInside];
            [likeRadioButton addTarget:self action:@selector(likeRadioButtonPressed) forControlEvents:UIControlEventTouchUpInside];
            [likeRadioImage setImage:[UIImage imageNamed:@"likeRadio"]];
        } else {
            [likeRadioButton removeTarget:self action:@selector(likeRadioButtonPressed) forControlEvents:UIControlEventTouchUpInside];
            [likeRadioButton addTarget:self action:@selector(unlikeRadioButtonPressed) forControlEvents:UIControlEventTouchUpInside];
            [likeRadioImage setImage:[UIImage imageNamed:@"likeRadioSelected"]];
        }
    }
    
    if (playlistTimer != nil) {
        [playlistTimer invalidate];
        playlistTimer = nil;
    }
    playlistTimer = [NSTimer scheduledTimerWithTimeInterval:5
                                                     target:appDelegate.dataController
                                                   selector:@selector(parsePlaylist)
                                                   userInfo:nil
                                                    repeats:YES];
    [playlistTimer fire];
    
    [coverImage setFrame:CGRectMake((appDelegate.dataController.currentRadioIndex * scrollview.frame.size.width) + ((scrollview.frame.size.width - 200.0f) / 2), (scrollview.frame.size.height - 200.0f) / 2, 200.0f, 200.0f)];
    [scrollview setContentOffset:CGPointMake((appDelegate.dataController.currentRadioIndex * scrollview.frame.size.width), 0.0f) animated:NO];
    [scrollview setDelegate:self];
    
    if (appDelegate.dataController.currentRadioIndex > 0) {
        [tempCoverLeft setFrame:CGRectMake(coverImage.frame.origin.x - scrollview.frame.size.width, coverImage.frame.origin.y, coverImage.frame.size.width, coverImage.frame.size.height)];
        [self.view addSubview:previousIndicator];
    } else {
        [previousIndicator removeFromSuperview];
    }
    if (appDelegate.dataController.currentRadioIndex < (appDelegate.dataController.currentRadioArray.count - 1)) {
        [tempCoverRight setFrame:CGRectMake(coverImage.frame.origin.x + scrollview.frame.size.width, coverImage.frame.origin.y, coverImage.frame.size.width, coverImage.frame.size.height)];
        [self.view addSubview:nextIndicator];
    } else {
        [nextIndicator removeFromSuperview];
    }
    [scrollview setContentSize:CGSizeMake((appDelegate.dataController.currentRadioArray.count * scrollview.frame.size.width), scrollview.frame.size.height)];
}

- (void)displayRadioDescription {
    
    [self.view addSubview:radioHeaderView];
    [hideDescriptionButton setHidden:NO];
    
    CGSize textWithin  = CGSizeMake(radioDescription.frame.size.width, 1000);
    NSString *textStr  = [radioDescription text];
    CGSize textSize    = [textStr sizeWithFont:radioDescription.font constrainedToSize:textWithin];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationDelegate:self];
    
    CGRect descriptionRect = radioDescription.frame;
    descriptionRect.size.height = textSize.height;
    [radioDescription setFrame:descriptionRect];
    
    CGRect scrollviewRect = descriptionScrollview.frame;
    scrollviewRect.size.height = (descriptionRect.size.height < 300.0f)?descriptionRect.size.height:300.0f;
    [descriptionScrollview setFrame:scrollviewRect];
    [descriptionScrollview setContentSize:CGSizeMake(descriptionScrollview.frame.size.width, textSize.height)];
    
    CGRect headerRect = radioHeaderView.frame;
    headerRect.size.height = scrollviewRect.origin.y + scrollviewRect.size.height + 40.0f;
    [radioHeaderView setFrame:headerRect];
    if ([radioHeaderView.layer sublayers] != nil && [[radioHeaderView.layer sublayers] count] > 0) {
        CAGradientLayer *gradient = [[radioHeaderView.layer sublayers] objectAtIndex:0];
        gradient.frame = radioHeaderView.bounds;
    }
    
    CGRect readMoreRect = headerReadMoreLabel.frame;
    readMoreRect.origin.y = scrollviewRect.origin.y + scrollviewRect.size.height;
    [headerReadMoreLabel setText:@"> Masquer"];
    [headerReadMoreLabel setFrame:readMoreRect];
    
    [displayHideDescriptionButton setFrame:CGRectMake(0.0f, 0.0f, scrollviewRect.size.width, scrollviewRect.size.height)];
    [displayHideDescriptionButton removeTarget:self action:@selector(displayRadioDescription) forControlEvents:UIControlEventTouchUpInside];
    [displayHideDescriptionButton addTarget:self action:@selector(hideRadioDescription) forControlEvents:UIControlEventTouchUpInside];
    
    [headerReadMoreButton setFrame:CGRectMake(0.0f, 0.0f, headerRect.size.width, headerRect.size.height)];
    [headerReadMoreButton removeTarget:self action:@selector(displayRadioDescription) forControlEvents:UIControlEventTouchUpInside];
    [headerReadMoreButton addTarget:self action:@selector(hideRadioDescription) forControlEvents:UIControlEventTouchUpInside];
    
    [UIView commitAnimations];
}

- (void)hideRadioDescription {
    
    [hideDescriptionButton setHidden:YES];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationDelegate:self];
    
    CGRect headerRect = radioHeaderView.frame;
    headerRect.size.height = 100.0f;
    [radioHeaderView setFrame:headerRect];
    if ([radioHeaderView.layer sublayers] != nil && [[radioHeaderView.layer sublayers] count] > 0) {
        CAGradientLayer *gradient = [[radioHeaderView.layer sublayers] objectAtIndex:0];
        gradient.frame = radioHeaderView.bounds;
    }
    
    CGRect descriptionRect = radioDescription.frame;
    descriptionRect.size.height = radioHeaderView.frame.size.height - 60.0f;
    [radioDescription setFrame:descriptionRect];
    
    CGRect scrollviewRect = descriptionScrollview.frame;
    scrollviewRect.size.height = radioDescription.frame.size.height;
    [descriptionScrollview setFrame:scrollviewRect];
    [descriptionScrollview setContentSize:CGSizeMake(descriptionScrollview.frame.size.width, descriptionScrollview.frame.size.height)];
    
    CGRect readMoreRect = headerReadMoreLabel.frame;
    readMoreRect.origin.y = scrollviewRect.origin.y + scrollviewRect.size.height;
    [headerReadMoreLabel setText:@"> Lire la suite"];
    [headerReadMoreLabel setFrame:readMoreRect];
    
    [displayHideDescriptionButton setFrame:CGRectMake(0.0f, 0.0f, scrollviewRect.size.width, scrollviewRect.size.height)];
    [displayHideDescriptionButton removeTarget:self action:@selector(hideRadioDescription) forControlEvents:UIControlEventTouchUpInside];
    [displayHideDescriptionButton addTarget:self action:@selector(displayRadioDescription) forControlEvents:UIControlEventTouchUpInside];
    
    [headerReadMoreButton setFrame:CGRectMake(0.0f, 0.0f, headerRect.size.width, headerRect.size.height)];
    [headerReadMoreButton removeTarget:self action:@selector(hideRadioDescription) forControlEvents:UIControlEventTouchUpInside];
    [headerReadMoreButton addTarget:self action:@selector(displayRadioDescription) forControlEvents:UIControlEventTouchUpInside];
    
    [UIView commitAnimations];
}

- (void)startRadio {
    
    //si on a change de radio on lance les pubs audio et display
    if (isNewsRadio == YES) {
        isDisplayAdToPlay = YES;
        isAudioAdToPlay = YES;
        [appDelegate.dataController parseAdswizz];
    }
    //si on est sur la meme radio on lance directement le flux
    else {
        [self playRadio];
    }
}

- (void)playAudioAd {
    
    //on joue la pub audio et la radio sera lancee lorsque moviePlayBackStateDidChange == MPMoviePlaybackStatePaused
    [player setMovieSourceType:MPMovieSourceTypeFile];
    [player setContentURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"audioMp3"]]];
    [player play];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"impression"]]];
    [[NSURLConnection alloc] initWithRequest:request delegate:nil];
}

- (void)playRadio {
    
    radioUrlToPlay = @"";
    if (isAacError == NO && [currentRadio objectForKey:@"flux_aac"] != nil && [[currentRadio objectForKey:@"flux_aac"] length] > 0) {
        radioUrlToPlay = [currentRadio objectForKey:@"flux_aac"];
    }
    else if (isMp3Error == NO && [currentRadio objectForKey:@"flux_mp3"] != nil && [[currentRadio objectForKey:@"flux_mp3"] length] > 0) {
        radioUrlToPlay = [currentRadio objectForKey:@"flux_mp3"];
    }
    NSLog(@"PLAY RADIO AT URL : %@",radioUrlToPlay);
    isNewsRadio = NO;
    NSString *playingInfo = [currentRadio objectForKey:@"title"];
    [appDelegate.allzicVC refreshNowPlayingViewWithTitle:playingInfo];
    [appDelegate.categoriesVC refreshNowPlayingViewWithTitle:playingInfo];
    [appDelegate.categoriesRadiosVC refreshNowPlayingViewWithTitle:playingInfo];
    [appDelegate.exploreVC refreshNowPlayingViewWithTitle:playingInfo];
    [appDelegate.lastRadiosVC refreshNowPlayingViewWithTitle:playingInfo];
    [appDelegate.randomRadioVC refreshNowPlayingViewWithTitle:playingInfo];
    [appDelegate.topRadioVC refreshNowPlayingViewWithTitle:playingInfo];
    [appDelegate.favoriteVC refreshNowPlayingViewWithTitle:playingInfo];
    [appDelegate.searchVC refreshNowPlayingViewWithTitle:playingInfo];
    
    [appDelegate.allzicVC startMiniPlayer];
    [appDelegate.categoriesVC startMiniPlayer];
    [appDelegate.categoriesRadiosVC startMiniPlayer];
    [appDelegate.exploreVC startMiniPlayer];
    [appDelegate.lastRadiosVC startMiniPlayer];
    [appDelegate.randomRadioVC startMiniPlayer];
    [appDelegate.topRadioVC startMiniPlayer];
    [appDelegate.favoriteVC startMiniPlayer];
    [appDelegate.searchVC startMiniPlayer];
    
    [loadingView setHidden:NO];
    [playStopImage setImage:[UIImage imageNamed:@"stopButton"]];
    [playStopButton removeTarget:self action:@selector(startRadio) forControlEvents:UIControlEventTouchUpInside];
    [playStopButton addTarget:self action:@selector(stopRadio) forControlEvents:UIControlEventTouchUpInside];
    
    [player setMovieSourceType:MPMovieSourceTypeStreaming];
    [player setContentURL:[NSURL URLWithString:radioUrlToPlay]];
    [player play];
    
    NSLog(@"\n\n> > >>> >>> >> PLAY RADIO AT URL : %@\n\n",radioUrlToPlay);
    
    if (radioLoadingTimeout != nil && [radioLoadingTimeout isValid]) {
        [radioLoadingTimeout invalidate];
    }
    radioLoadingTimeout = [NSTimer scheduledTimerWithTimeInterval:15.0
                                                           target:self
                                                         selector:@selector(checkPlayerState)
                                                         userInfo:nil
                                                          repeats:NO];
}

- (void)stopRadio {
    
    [loadingView setHidden:YES];
    [player stop];
    [playStopImage setImage:[UIImage imageNamed:@"playButton"]];
    [playStopButton removeTarget:self action:@selector(stopRadio) forControlEvents:UIControlEventTouchUpInside];
    [playStopButton addTarget:self action:@selector(startRadio) forControlEvents:UIControlEventTouchUpInside];
    
    if (radioLoadingTimeout != nil && [radioLoadingTimeout isValid]) {
        [radioLoadingTimeout invalidate];
    }
    
    [appDelegate.allzicVC stopMiniPlayer];
    [appDelegate.categoriesVC stopMiniPlayer];
    [appDelegate.categoriesRadiosVC stopMiniPlayer];
    [appDelegate.exploreVC stopMiniPlayer];
    [appDelegate.lastRadiosVC stopMiniPlayer];
    [appDelegate.randomRadioVC stopMiniPlayer];
    [appDelegate.topRadioVC stopMiniPlayer];
    [appDelegate.favoriteVC stopMiniPlayer];
    [appDelegate.searchVC stopMiniPlayer];
    
    Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
    if (playingInfoCenter) {
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:nil];
    }
}

- (void)checkPlayerState {
    
    if ([player playbackState] != MPMoviePlaybackStatePlaying) {
        NSLog(@"PLAYER not PLAYING");
        [self stopRadio];
        UIAlertView *alert = [[UIAlertView alloc] init];
        [alert setTitle:@"Problème d'écoute"];
        [alert setMessage:@"Désolé, la radio que vous essayez d'écouter est indisponible pour le moment"];
        [alert addButtonWithTitle:@"OK"];
        [alert show];
    } else {
        NSLog(@"PLAYER is PLAYING");
    }
}

- (void)moviePlayBackStateDidChange:(NSNotification*)notification {
    
	MPMoviePlayerController *playerObject = notification.object;
    if (playerObject.playbackState == MPMoviePlaybackStatePlaying) {
        //NSLog(@"\n\n> > > > MOVIE PLAYBACK STATE DID CHANGE : PLAYING\n\n");
        //[loadingWheel setHidden:YES];
        [loadingView setHidden:YES];
        if (isAudioAdToPlay == YES) {
            isAudioAdToPlay = NO;
            adTrackingIndex = 0;
            CGFloat nbSecond = 0.0f;
            NSString *duration = [appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"audioDuration"];
            if (duration != nil && duration.length == 8) {
                nbSecond = ([[duration substringToIndex:2] floatValue] * 3600) + ([[[duration substringFromIndex:3] substringToIndex:2] floatValue] * 60) + [[[duration substringFromIndex:6] substringToIndex:2] floatValue];
            }
            
            CGFloat trackingDelay = nbSecond / 4;
            adTrackingTimer  = [NSTimer scheduledTimerWithTimeInterval:trackingDelay
                                                                target:self
                                                              selector:@selector(sendAudioAdTracking)
                                                              userInfo:nil
                                                               repeats:YES];
            [adTrackingTimer fire];
        }
    } else if (playerObject.playbackState == MPMoviePlaybackStateInterrupted) {
        //NSLog(@"\n\n> > > > MOVIE PLAYBACK STATE DID CHANGE : INTERRUPTED\n\n");
    } else if (playerObject.playbackState == MPMoviePlaybackStatePaused) {
        //NSLog(@"\n\n> > > > MOVIE PLAYBACK STATE DID CHANGE : PAUSED\n\n");
        [[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name:MPMoviePlayerPlaybackStateDidChangeNotification
                                                      object:player];
        [player stop];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(moviePlayBackStateDidChange:)
                                                     name:MPMoviePlayerPlaybackStateDidChangeNotification
                                                   object:player];
        [self playRadio];
    } else if (playerObject.playbackState == MPMoviePlaybackStateSeekingBackward) {
        //NSLog(@"\n\n> > > > MOVIE PLAYBACK STATE DID CHANGE : SEEKING BACKWARD\n\n");
    } else if (playerObject.playbackState == MPMoviePlaybackStateSeekingForward) {
        //NSLog(@"\n\n> > > > MOVIE PLAYBACK STATE DID CHANGE : SEEKING FORWARD\n\n");
    } else if (playerObject.playbackState == MPMoviePlaybackStateStopped) {
        //NSLog(@"\n\n> > > > MOVIE PLAYBACK STATE DID CHANGE : STOPPED\n\n");
        if (adTrackingTimer != nil) {
            [adTrackingTimer invalidate];
            adTrackingTimer = nil;
        }
    }
}

- (void)moviePlayBackDidFinish:(NSNotification*)notification {
    
    NSNumber *reason = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
	switch ([reason integerValue]) {
		case MPMovieFinishReasonPlaybackEnded:
			break;
		case MPMovieFinishReasonPlaybackError: {
            [self stopRadio];
            NSData *connect = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
            if (connect != nil) {
                if (isAacError == NO) {
                    isAacError = YES;
                    [self playRadio];
                } else {
                    isMp3Error = YES;
                    UIAlertView *alert = [[UIAlertView alloc] init];
                    [alert setTitle:@"Problème d'écoute"];
                    [alert setMessage:@"Désolé, la radio que vous essayez d'écouter est indisponible pour le moment"];
                    [alert addButtonWithTitle:@"OK"];
                    [alert show];
                }
            }
            else {
                UIAlertView *alert = [[UIAlertView alloc] init];
                [alert setTitle:@"Problème d'écoute"];
                [alert setMessage:@"Désolé, votre connexion internet est insuffisante pour écouter la radio"];
                [alert addButtonWithTitle:@"OK"];
                [alert show];
            }
            return;
        }
			break;
            /* The user stopped playback. */
		case MPMovieFinishReasonUserExited:
			break;
		default:
			break;
	}
    /*if(!destroying) {
     [self.navigationController popViewControllerAnimated:YES];
     }*/
}

- (void)handleNotification:(NSNotification *)notification {
    
    if ([notification.name isEqualToString:remoteControlPlayButtonTapped]) {
        NSLog(@"Play remote event recieved.");
        [player play];
    } else  if ([notification.name isEqualToString:remoteControlPauseButtonTapped]) {
        NSLog(@"Pause remote event recieved.");
        [player stop];
    } else if ([notification.name isEqualToString:remoteControlStopButtonTapped]) {
        NSLog(@"Stop remote event recieved.");
        [player stop];
    } else if ([notification.name isEqualToString:remoteControlForwardButtonTapped]) {
        NSLog(@"Forward remote event recieved.");
    } else if ([notification.name isEqualToString:remoteControlBackwardButtonTapped]) {
        NSLog(@"Back remote event recieved.");
    } else if ([notification.name isEqualToString:remoteControlTogglePlayPauseButtonTapped]) {
        NSLog(@"Toggle play / pause remote event recieved.");
        if ([playStopImage.image isEqual:[UIImage imageNamed:@"playButton"]]) {
            [self startRadio];
        } else {
            [self stopRadio];
        }
    } else {
        NSLog(@"Unknown remote event recieved.");
    }
}


//-----------------------------------------
//		ScrollView Delegate
//-----------------------------------------

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
	
	CGFloat pageWidth = scrollView.frame.size.width;
    float fractionalPage = scrollView.contentOffset.x / pageWidth;
    NSInteger page = lround(fractionalPage);
    [scrollview setDelegate:nil];
    //NSLog(@"\n\n\n> > > scrollViewDidEndDecelerating - CHANGED PAGE : %d\n\n\n",page);
    [appDelegate selectRadioWithData:appDelegate.dataController.currentRadioArray atIndex:page];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
	if (!decelerate) {
		CGFloat pageWidth = scrollView.frame.size.width;
        float fractionalPage = scrollView.contentOffset.x / pageWidth;
        NSInteger page = lround(fractionalPage);
        [scrollview setDelegate:nil];
        //NSLog(@"\n\n\n> > > scrollViewDidEndDragging - CHANGED PAGE : %d\n\n\n",page);
        [appDelegate selectRadioWithData:appDelegate.dataController.currentRadioArray atIndex:page];
    }
}

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

- (void)refreshPlaylistWithData:(NSArray *)data {
    
    if (data != nil && data.count > 0) {
        playlistData = [data objectAtIndex:0];
        [songSinger performSelectorOnMainThread:@selector(setText:) withObject:[playlistData objectForKey:@"artist"] waitUntilDone:YES];
        [songTitle performSelectorOnMainThread:@selector(setText:) withObject:[playlistData objectForKey:@"title"] waitUntilDone:YES];
        [self loadImageWithType:1];
        
        NSString *playingInfo = @"";
        if ([playlistData objectForKey:@"artist"] != nil && [[playlistData objectForKey:@"artist"] length] > 0 && [playlistData objectForKey:@"title"] != nil && [[playlistData objectForKey:@"title"] length] > 0) {
            playingInfo = [NSString stringWithFormat:@"%@ - %@",[playlistData objectForKey:@"artist"],[playlistData objectForKey:@"title"]];
        } else if ([playlistData objectForKey:@"artist"] != nil && [[playlistData objectForKey:@"artist"] length] > 0 ) {
            playingInfo = [NSString stringWithFormat:@"%@ - %@",[currentRadio objectForKey:@"title"],[playlistData objectForKey:@"artist"]];
        } else if ([playlistData objectForKey:@"title"] != nil && [[playlistData objectForKey:@"title"] length] > 0 ) {
            playingInfo = [NSString stringWithFormat:@"%@ - %@",[currentRadio objectForKey:@"title"],[playlistData objectForKey:@"title"]];
        } else {
            playingInfo = [currentRadio objectForKey:@"title"];
        }
        [appDelegate.allzicVC refreshNowPlayingViewWithTitle:playingInfo];
        [appDelegate.categoriesVC refreshNowPlayingViewWithTitle:playingInfo];
        [appDelegate.categoriesRadiosVC refreshNowPlayingViewWithTitle:playingInfo];
        [appDelegate.exploreVC refreshNowPlayingViewWithTitle:playingInfo];
        [appDelegate.lastRadiosVC refreshNowPlayingViewWithTitle:playingInfo];
        [appDelegate.randomRadioVC refreshNowPlayingViewWithTitle:playingInfo];
        [appDelegate.topRadioVC refreshNowPlayingViewWithTitle:playingInfo];
        [appDelegate.favoriteVC refreshNowPlayingViewWithTitle:playingInfo];
        [appDelegate.searchVC refreshNowPlayingViewWithTitle:playingInfo];
        Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
        if (playingInfoCenter) {
            MPMediaItemArtwork *songCover;
            NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[currentRadio objectForKey:@"thumb"]]]];
            if (image != nil) {
                songCover = [[MPMediaItemArtwork alloc] initWithImage:image];
                [songInfo setObject:songCover forKey:MPMediaItemPropertyArtwork];
            }
            [songInfo setObject:[currentRadio objectForKey:@"title"] forKey:MPMediaItemPropertyAlbumTitle];
            [songInfo setObject:[playlistData objectForKey:@"title"] forKey:MPMediaItemPropertyTitle];
            [songInfo setObject:[playlistData objectForKey:@"artist"] forKey:MPMediaItemPropertyArtist];
            [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
        }
    }
}

- (void)loadImageWithType:(int)imageType {
    
    //radio image
    if (imageType == 0) {
        //[radioImage setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[currentRadio objectForKey:@"thumb"]]]]];
        
        
        if(radioLogoDownloader.iconUrl != nil && [radioLogoDownloader.iconUrl isEqualToString:[currentRadio objectForKey:@"thumb"]]) {
            [radioImage setImage:radioLogoDownloader.appIcon];
        } else {
            [radioLogoDownloader cancelDownload];
            [radioLogoDownloader startDownloadAtUrl:[currentRadio objectForKey:@"thumb"] withMaxSize:radioImage.frame.size.height*2];
        }
        
        
        
    }//cover image
    else if (imageType == 1) {
        /*NSString *cover_url = [playlistData objectForKey:@"cover"];
        NSLog(@"COVER URL : %@",cover_url);
        if (cover_url != nil && cover_url.length > 0) {
            [coverImage setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[playlistData objectForKey:@"cover"]]]]];
        }*/
        
        
        if(radioCoverDownloader.iconUrl != nil && [radioCoverDownloader.iconUrl isEqualToString:[playlistData objectForKey:@"cover"]]) {
            if (radioCoverDownloader.appIcon != nil) {
                [coverImage setImage:radioCoverDownloader.appIcon];
            }
        } else {
            [radioCoverDownloader cancelDownload];
            [radioCoverDownloader startDownloadAtUrl:[playlistData objectForKey:@"cover"] withMaxSize:coverImage.frame.size.height*2];
        }
    }
}

- (void)likeRadioButtonPressed {
    
    [appDelegate likeRadio];
    [likeRadioButton removeTarget:self action:@selector(likeRadioButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [likeRadioButton addTarget:self action:@selector(unlikeRadioButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [likeRadioImage setImage:[UIImage imageNamed:@"likeRadioSelected"]];
}

- (void)unlikeRadioButtonPressed {
    
    [appDelegate unlikeRadio];
    [likeRadioButton removeTarget:self action:@selector(unlikeRadioButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [likeRadioButton addTarget:self action:@selector(likeRadioButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [likeRadioImage setImage:[UIImage imageNamed:@"likeRadio"]];
}

- (void)refreshRadioWithFavorite:(BOOL)isFavorite {
    
    if (isFavorite == YES) {
        [likeRadioButton removeTarget:self action:@selector(likeRadioButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        [likeRadioButton addTarget:self action:@selector(unlikeRadioButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        [likeRadioImage setImage:[UIImage imageNamed:@"likeRadioSelected"]];
    } else {
        [likeRadioButton removeTarget:self action:@selector(unlikeRadioButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        [likeRadioButton addTarget:self action:@selector(likeRadioButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        [likeRadioImage setImage:[UIImage imageNamed:@"likeRadio"]];
    }
}

- (void)facebookButtonPressed {
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   [NSString stringWithFormat:@"En ce moment j'écoute %@ sur Allzicradio.com, des milliers de webradios disponibles gratuitement", [playlistData objectForKey:@"title"]], @"name",
                                   [NSString stringWithFormat:@"L'application Allzicradio est disponible gratuitement sur iOS et Android"], @"caption",
                                   @"", @"description",
                                   @"http://www.allzicradio.com", @"link",
                                   [playlistData objectForKey:@"cover"], @"picture",
                                   nil];
    NSLog(@"SHARE ON FACEBOOK WITH PARAMS : %@",params);
    [appDelegate shareOnFacebookWithData:params];
}

- (void)twitterButtonPressed {
    
    NSString *sharingText = [NSString stringWithFormat:@"En ce moment j'écoute %@ sur Allzicradio.com, des milliers de webradios disponibles gratuitement", [playlistData objectForKey:@"title"]];
    
    NSMutableDictionary *sharingData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                        sharingText, @"description",
                                        @"", @"link",
                                        [playlistData objectForKey:@"cover"], @"picture",
                                        nil];
    [appDelegate shareOnTwitterWithData:sharingData];
}



//-----------------------------------------
//		IconDownloader Delegate
//-----------------------------------------

- (void)initAdBanner {
    
    adView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, playerControlView.frame.origin.y + playerControlView.frame.size.height, appDelegate.screenBounds.size.width, 70.0f)];
    [adView setBackgroundColor:[UIColor darkGrayColor]];
    [self.view addSubview:adView];
    
    adBannerWebview = [[UIWebView alloc] initWithFrame:CGRectMake(0.0f, 20.0f, appDelegate.screenBounds.size.width, 50.0f)];
    [adBannerWebview setBackgroundColor:[UIColor colorWithRed:8.0f/255.0f green:41.0f/255.0f blue:55.0f/255.0f alpha:1.0f]];
    [adBannerWebview setScalesPageToFit:YES];
    [adBannerWebview setDelegate:self];
    [adBannerWebview setTag:0];
    [adView addSubview:adBannerWebview];
    
    adBannerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [adBannerButton setFrame:adBannerWebview.frame];
    [adBannerButton addTarget:self action:@selector(adButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [adBannerButton setTag:0];
    [adView addSubview:adBannerButton];
    
    adBar = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, appDelegate.screenBounds.size.width, 20.0f)];
    [adBar setBackgroundColor:[UIColor blackColor]];
    [adView addSubview:adBar];
    
    adLabel = [[UILabel alloc] initWithFrame:adBar.frame];
    [adLabel setBackgroundColor:[UIColor clearColor]];
    [adLabel setTextColor:[UIColor whiteColor]];
    [adLabel setFont:[UIFont boldSystemFontOfSize:12]];
    [adLabel setText:@"   Publicité"];
    [adView addSubview:adLabel];
    
    adButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [adButton setFrame:adBar.frame];
    [adButton addTarget:self action:@selector(displayAdBanner) forControlEvents:UIControlEventTouchUpInside];
    [adView addSubview:adButton];
}

- (void)loadAdBanner {
    
    if (isAdOpen) {
        [self hideAdBanner];
    }
    isAdLoaded = NO;
    [adBannerWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"bannerImage"]]]];
}

- (void)displayAdBanner {
    
    adBannerAdjustedHeight = ([[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"bannerHeight"] intValue] * appDelegate.screenBounds.size.width) / [[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"bannerWidth"] intValue];
    
    [adView setFrame:CGRectMake(adView.frame.origin.x, adView.frame.origin.y, adView.frame.size.width, adBar.frame.size.height + adBannerAdjustedHeight)];
    [adBannerWebview setFrame:CGRectMake(adBannerWebview.frame.origin.x, adBannerWebview.frame.origin.y, adBannerWebview.frame.size.width, adBannerAdjustedHeight)];
    
    if (!isAdOpen) {
        isAdOpen = YES;
        CGRect rect = adView.frame;
        rect.origin.y = playerControlView.frame.origin.y + playerControlView.frame.size.height - 20.0f;
        CGFloat margin = adBannerAdjustedHeight;
        if (isAdLoaded == NO) {
            margin = adBar.frame.size.height + adBannerAdjustedHeight;
            isAdLoaded = YES;
            rect.origin.y = playerControlView.frame.origin.y + playerControlView.frame.size.height;
        }
        [adView setFrame:rect];
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.6];
        adView.frame = CGRectMake(adView.frame.origin.x,
                                  adView.frame.origin.y - margin,
                                  adView.frame.size.width,
                                  adView.frame.size.height);
        [UIView commitAnimations];
        
        if (adDisplayTimer != nil) {
            [adDisplayTimer invalidate];
            adDisplayTimer = nil;
        }
        adDisplayTimer = [NSTimer scheduledTimerWithTimeInterval:8
                                                          target:self
                                                        selector:@selector(hideAdBanner)
                                                        userInfo:nil
                                                         repeats:NO];
    }
}

- (void)hideAdBanner {
	
	[UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.6];
	adView.frame = CGRectMake(adView.frame.origin.x,
                              adView.frame.origin.y + adBannerAdjustedHeight,
                              adView.frame.size.width,
                              adView.frame.size.height);
    [UIView commitAnimations];
    isAdOpen = NO;
    isDisplayAdToPlay = NO;
}

- (void)initAdInterstitial {
    
    adInterstitialWebview = [[UIWebView alloc] initWithFrame:CGRectMake(0.0f, 20.0f, appDelegate.screenBounds.size.width, appDelegate.screenBounds.size.height - 20.0f)];
    if (appDelegate.systemVersion < 7.0) {
        [adInterstitialWebview setFrame:CGRectMake(0.0f, 20.0f, appDelegate.screenBounds.size.width, appDelegate.screenBounds.size.height - 20.0f)];
    }
    [adInterstitialWebview setDelegate:self];
    [adInterstitialWebview setScalesPageToFit:YES];
    [adInterstitialWebview setBackgroundColor:[UIColor greenColor]];
    [adInterstitialWebview setTag:1];
    
    adInterstitialButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [adInterstitialButton setFrame:CGRectMake(0.0f, 0.0f, adInterstitialWebview.frame.size.width, adInterstitialWebview.frame.size.height)];
    [adInterstitialButton addTarget:self action:@selector(adButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [adInterstitialButton setTag:1];
    [adInterstitialWebview addSubview:adInterstitialButton];
}

- (void)loadAdInterstitial {
    
    [adInterstitialWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"interstitialImage"]]]];
}

- (void)displayAdInterstitial {
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.8];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:appDelegate.window cache:YES];
    [appDelegate.window addSubview:adInterstitialWebview];
    [UIView commitAnimations];
    [self performSelector:@selector(hideAdInterstitial) withObject:nil afterDelay:5.0f];
}

- (void)hideAdInterstitial {
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.8];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:appDelegate.window cache:YES];
    [adInterstitialWebview removeFromSuperview];
    [UIView commitAnimations];
    isDisplayAdToPlay = NO;
}

- (void)adButtonPressed:(UIButton *)button {
    
    if (button.tag == 0) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"bannerLink"]]];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"bannerTracking"]]];
        [[NSURLConnection alloc] initWithRequest:request delegate:nil];
    } else if (button.tag == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"interstitialLink"]]];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"interstitialTracking"]]];
        [[NSURLConnection alloc] initWithRequest:request delegate:nil];
    }
}

- (void)sendAudioAdTracking {
    
    switch (adTrackingIndex) {
        case 0: {
            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"audioTrackingStart"]]];
            [[NSURLConnection alloc] initWithRequest:request delegate:nil];
            //NSLog(@"> > > ADSWIZZ audioTrackingStart");
        }
            break;
        case 1: {
            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"audioTrackingFirstQuartile"]]];
            [[NSURLConnection alloc] initWithRequest:request delegate:nil];
            //NSLog(@"> > > ADSWIZZ audioTrackingFirstQuartile");
        }
            break;
        case 2: {
            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"audioTrackingMidpoint"]]];
            [[NSURLConnection alloc] initWithRequest:request delegate:nil];
            //NSLog(@"> > > ADSWIZZ audioTrackingMidpoint");
        }
            break;
        case 3: {
            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"audioTrackingThirdQuartile"]]];
            [[NSURLConnection alloc] initWithRequest:request delegate:nil];
            //NSLog(@"> > > ADSWIZZ audioTrackingThirdQuartile");
        }
            break;
        case 4: {
            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[appDelegate.dataController.adswizzParser.dataDictionary objectForKey:@"audioTrackingComplete"]]];
            [[NSURLConnection alloc] initWithRequest:request delegate:nil];
            isAudioAdToPlay = NO;
            //NSLog(@"> > > ADSWIZZ audioTrackingComplete");
            if (adTrackingTimer != nil) {
                [adTrackingTimer invalidate];
                adTrackingTimer = nil;
            }
        }
            break;
        default:
            break;
    }
    adTrackingIndex++;
}

- (void)appImageDidLoad:(IconDownloader *)downloader {
    
    if ([downloader isEqual:radioLogoDownloader]) {
        if ([downloader.iconUrl isEqualToString:[currentRadio objectForKey:@"thumb"]]) {
            [radioImage setImage:downloader.appIcon];
        }
    } else if ([downloader isEqual:radioCoverDownloader]) {
        if ([downloader.iconUrl isEqualToString:[playlistData objectForKey:@"cover"]]) {
            [coverImage setImage:downloader.appIcon];
        }
    }
}


//-----------------------------------------
//		UIWebView Delegate
//-----------------------------------------

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
	
	if(navigationType == UIWebViewNavigationTypeLinkClicked) {
		NSURL *URL = [request URL];
		if ([[URL scheme] isEqualToString:@"http"]) {
			[[UIApplication sharedApplication] openURL: URL];
		}
		return NO;
	}
	return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
	
    if (webView.tag == 0) {
        [self displayAdBanner];
    } else if (webView.tag == 1) {
        [self displayAdInterstitial];
    }
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
	
	NSLog(@"Error while loading ad : %@",error);
}




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

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

@end
