  //
//  editingView.m
//  melody app
//
//  Created by Odin on 12/09/2016.
//  Copyright © 2016 demain un autre jour. All rights reserved.
//

// !!! DO NOT TYPE CODE AFTER THE END OF FILE TAG !

/*
 
 +---------------------------------------------------------------+
 | This is the third view related class                          |
 +---------------------------------------------------------------+ 
 | - editing option implementation								 |
 +---------------------------------------------------------------+
 | - category xml management									 |
 +---------------------------------------------------------------+
 | - category canal management									 |
 +---------------------------------------------------------------+
 | - article sending											 |
 +---------------------------------------------------------------+

 
*/

#import "editingView.h"
#import "DBmanager.h"
#import "viewInfo.h"
#import "ZipArchive.h"
#import "XPathQuery.h"
#import "popupViewViewController.h"
#import "melody_app-Swift.h"
#import "sql/ZIMSqlSdk.h"
#import "sql/ZIMOrmSdk.h"
#import "sql/ZIMDbSdk.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <CommonCrypto/CommonDigest.h>
#import "XMLWriter/XMLWriter.h"
#import <MediaPlayer/MPMediaPickerController.h>
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetReader.h>
#import <AVFoundation/AVAssetReaderOutput.h>
#import <AVFoundation/AVAudioSettings.h>
#import "soundManagerViewController.h"


@interface editingView () <RichEditorDelegate> {
    NSArray *contents;
	NSString *cat;
	NSString *catValue;
	long	 matchCont;
	int		 keyValue;
	tableViewDelegate *tvd;
	searchBarDelegate *svd;
	searchViewDelegate *searchDelegate;
	themSearchBarDelegate *tsbd;
	NSInteger lastDecalage;
	NSInteger themLastDecalage;
	NSInteger originalDisplaySearchSize;
	NSInteger originalThemDisplaySearchSize;
	NSString* currentMediaTypePicking;
	BOOL fileMustBeInsertedIntoLibrary;
	BOOL soundBeingTreated;
	BOOL articleIsEmergency;
	NSArray* authorizedPhotoTypes;
	NSInteger finalFileMaxUploadSize;
}

@end

@interface infos : NSObject

@property (nonatomic, copy) NSString *nomlc;
@property (nonatomic, copy) NSString *id;

@end


//ATTENTION MODIF A FAIRE AUSSI SUR viewcontroller.m
//LOCAL//////////////////////////////////////////////////////////////////////
//static NSString *_BO_URL= @"http://web.daj.demainunautrejour.com/gp/Melody/BackOffice/trunk/";
//PREPROLML//////////////////////////////////////////////////////////////////////
//static NSString *_BO_URL= @"http://melody.preprodlml.demainunautrejour.com/";
//DEV//////////////////////////////////////////////////////////////////////
static NSString *_BO_URL= @"http://melodyjournal.daj.toulouse/";
//PROD//////////////////////////////////////////////////////////////////////
//static NSString *_BO_URL= @"http://correspondant.lamanchelibre.fr/";

@implementation editingView
@synthesize collecView,searchBar, activityIndicator, webView, keyboardManager, tagView, tableImage;
- (void)viewDidLoad
{
	[super viewDidLoad];
	self.scrollView.contentSize=CGSizeMake(320, 1325);
	self.automaticallyAdjustsScrollViewInsets = false;
	self.scrollView.contentInset = UIEdgeInsetsZero;
	self.scrollView.scrollIndicatorInsets = UIEdgeInsetsZero;
	self.scrollView.contentOffset = CGPointMake(0.0, 0.0);
	self.scrollView.delegate = self;
	self.tagView.delegate = self;
	self.themTagView.delegate = self;
	self.themTagView.dataSource = self;
	self.tagView.dataSource = self;
	self.collecView.delegate = self;
	self.editorView.autoresizingMask = YES;
	self.editorView.autoresizesSubviews = YES;
	[self.activityIndicator setHidden:YES];
	UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
																		  action:@selector(dismissKeyboard)];
	tap.cancelsTouchesInView = NO;
	
	[self.view addGestureRecognizer:tap];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardDidShow:)
												 name:UIKeyboardDidShowNotification
											   object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"PhotoTerminated" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAddSoundToArticleNotification:) name:@"addSoundToArticle" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSetEmergencyEvent:) name:@"setArticleEmergency" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(releaseSound:) name:@"releaseSound" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTagNotif:) name:@"reloadTags" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moveDown:) name:@"editingTag" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushArticle:) name:@"pushArticle" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enteringTagSearchBar:) name:@"enteringTagSearchBar" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitingTagSearchBar:) name:@"exitingTagSearchBar" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enteringThemTagSearchBar:) name:@"enteringThemTagSearchBar" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitingThemTagSearchBar:) name:@"exitingThemTagSearchBar" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(displayArticleProgress:) name:@"canalChoosen" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardDidHide:)
												 name:UIKeyboardDidHideNotification
											   object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(orientationChanged:)
												 name:UIDeviceOrientationDidChangeNotification
											   object:nil];
	self.editorView.layer.borderColor = [[UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1.0] CGColor];
	self.editorView.layer.borderWidth = 0.5;
	self.chapoZone.layer.borderColor = [[UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1.0] CGColor];
	self.chapoZone.layer.borderWidth = 0.5;
	self.chapoZone.layer.cornerRadius = 5.0;
    self.content.layer.borderWidth = 1.0f;
    self.content.layer.borderColor = [[UIColor grayColor] CGColor];
    self.otherInfos.layer.borderWidth = 1.0f;
    self.otherInfos.layer.borderColor = [[UIColor grayColor] CGColor];
    // Make self the delegate of the textfields.
    self.content.delegate = self;
    self.titleZone.delegate = self;
	self.chapoZone.delegate = self;
    self.otherInfos.delegate = self;
    self.dbManager = [[DBManager alloc] initWithDatabaseFilename:@"baseData.sql"];
    // Check if should load specific record for editing.
    if (self.recordIDToEdit != -1) {
        // Load the record with the specific ID from the database.
        [self loadInfoToEdit];
		if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
		}
	}
	contents = [self getArticleContent];

	//get the category xml doc
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"cat.xml"]];
	NSError *error;
	cat = [NSString stringWithContentsOfFile:fullPath encoding:NSUTF8StringEncoding error:&error];
	if (error)
		//NSLog(@"Error reading file: %@", error.localizedDescription);
	contentList = [[NSMutableArray alloc] init];
	filteredContentList = [[NSMutableArray alloc] init];
	keyValue = 0;
	// Prepare the query string.
	// If the recordIDToEdit property has value other than -1, then create an update query. Otherwise create an insert query.
	NSString *query;
	//NSLog(@"lastInsertedRowId %lld", self.dbManager.lastInsertedRowID);
	if (self.recordIDToEdit <= 0) {
		// create article image folder*/
		query = @"insert into article (titleZone, content, otherInfo, chapo) values('', '', '', '')";
		[self.dbManager executeQuery:query];
		self.recordIDToEdit = (int)self.dbManager.lastInsertedRowID;
	}
	else{
		[self loadInfoToEdit];
		NSString *contentHtml = [self.editorView getHTML];
		NSString *contentString = [self.editorView getText];
		ZIMSqlUpdateStatement *myUpdatequery = [[ZIMSqlUpdateStatement alloc] init];
		id myId = [NSNumber numberWithInteger: self.recordIDToEdit];
		[myUpdatequery table:@"article"];
		[myUpdatequery where:@"fileInfoID" operator:@"=" value:myId];
		[myUpdatequery column:@"titleZone" value:self.titleZone.text];
		[myUpdatequery column:@"chapo" value:self.chapoZone.text];
		[myUpdatequery column:@"content" value:contentHtml];
		[myUpdatequery column:@"otherInfo" value:contentString];
		query = myUpdatequery.statement;
		//NSLog(@"query is here :%@", myUpdatequery.statement);
		[self.dbManager executeQuery:query];
	}
	// If the query was successfully executed then pop the view controller.
	if (self.dbManager.affectedRows != 0) {
		//NSLog(@"Query was executed successfully. Affected rows = %d", self.dbManager.affectedRows);
		// Inform the delegate that the editing was finished.
		[self.delegate editingInfoWasFinished];
	}
	else{
		//NSLog(@"Could not execute the query.");
	}
	[self loadData];
	[self.tagView reloadData];
	self.keyboardManager = [[KeyboardManager alloc] initWithView:self.view];
	self.keyboardManager.toolbar.editor = self.editorView;
	[self.keyboardManager beginMonitoring];
	tvd = [[tableViewDelegate alloc] initWithArticleId:self.recordIDToEdit mainView:self.view];
	svd = [[searchBarDelegate alloc] initWithArticleId:self.recordIDToEdit mainView:self.view refTable:self.searchDisplay tagView:self.tagView];
	tsbd = [[themSearchBarDelegate alloc] initWithArticleId:self.recordIDToEdit mainView:self.view refTable:self.themSearchDisplay tagView:self.themTagView];
	self.themSearch.delegate = tsbd;
	self.tagView.delegate = self;
	self.tagView.dataSource = self;
	self.tableImage.delegate = tvd;
	self.tableImage.dataSource = tvd;
	self.searchBar.delegate = svd;
	//init de la variable
	fileMustBeInsertedIntoLibrary = false;
	soundBeingTreated = false;
	CGRect screen = [[UIScreen mainScreen] bounds];
	self.view.frame = screen;
	
	articleIsEmergency = false;
	
	[self setAuthorizedPhotoTypesArray];
	[self setFinalFileMaxUploadSize];
}

- (void)orientationChanged:(NSNotification *)notification {
	CGRect screen = [[UIScreen mainScreen] bounds];
	self.view.frame = screen;
}

- (void)handleAddSoundToArticleNotification:(NSNotification*)notification {
	NSDictionary* userInfo = notification.userInfo;
	NSData* soundData = (NSData*)userInfo[@"soundData"];
	[self addSoundToArticle:soundData];
}

- (void)handleSetEmergencyEvent:(NSNotification*)notification {
	NSDictionary* userInfo = notification.userInfo;
	NSString* isEmergency = (NSString*)userInfo[@"isEmergency"];
	if ([isEmergency  isEqual: @"true"]) {
		articleIsEmergency = true;
	} else if ([isEmergency  isEqual: @"false"]) {
		articleIsEmergency = false;
	}
}

-(void) setAuthorizedPhotoTypesArray {
	NSString *xPathQuery = [NSString stringWithFormat:@"//authorizedUploadPhotosExtensions"];
	NSError *myError;
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"sessionInfos.xml"]];
	NSData *data = [NSData dataWithContentsOfFile:fullPath options:NSDataReadingMappedIfSafe error:&myError];
	NSArray* tmp = PerformXMLXPathQuery(data, xPathQuery);
	NSArray *matches = [tmp valueForKey:@"nodeContent"];
	//NSLog(@"content list = %@", matches3);
	NSString* authorizedPhotoTypesJSONStr = matches[0];
	authorizedPhotoTypes = [[NSMutableArray alloc] init];
	authorizedPhotoTypes = [NSJSONSerialization JSONObjectWithData: [authorizedPhotoTypesJSONStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
}

-(void) setFinalFileMaxUploadSize {
	NSString *xPathQuery = [NSString stringWithFormat:@"//maxUploadSize"];
	NSError *myError;
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"sessionInfos.xml"]];
	NSData *data = [NSData dataWithContentsOfFile:fullPath options:NSDataReadingMappedIfSafe error:&myError];
	NSArray* tmp = PerformXMLXPathQuery(data, xPathQuery);
	NSArray *matches = [tmp valueForKey:@"nodeContent"];
	//NSLog(@"content list = %@", matches3);
	if ([matches count] > 0) {
		finalFileMaxUploadSize = [matches[0] intValue];
	}
}

-(void) releaseSound:(NSNotification*)note  {
	soundBeingTreated = false;
}
- (void)viewWillLayoutSubviews {
	[super viewWillLayoutSubviews];
}
-(void)viewDidAppear:(BOOL)animated{
	self.scrollView.contentSize = CGSizeMake(375, 1000);
	
	[self resizeCatList:self.tagView rowsNumber:[self.tagView numberOfItemsInSection:0]];
	[self resizeCatList:self.themTagView rowsNumber:[self.themTagView numberOfItemsInSection:0]];
}

-(void)dismissKeyboard {
	[self.titleZone resignFirstResponder];
	[self.editorView resignFirstResponder];
	[self.chapoZone	resignFirstResponder];
}

-(void)loadData {
	// Form the query.
	NSString *query = [NSString stringWithFormat:@"select * from catGeo where fileInfoID = %d", self.recordIDToEdit];
	self.arrTagInfo = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
	//NSLog(@"tagInfos = %@", self.arrTagInfo);
	// Reload the table view.
	[self.tagView reloadData];
	
	NSString *query2 = [NSString stringWithFormat:@"select * from catThem where fileInfoID = %d", self.recordIDToEdit];
	self.arrThemTagInfo = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query2]];
	//NSLog(@"tagInfos = %@", self.arrThemTagInfo);
	// Reload the table view.
	[self.themTagView reloadData];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch * touch = [touches anyObject];
	if(touch.phase == UITouchPhaseBegan) {
		[self.editorView endEditing:YES];
		[self.titleZone endEditing:YES];
		[self.editorView resignFirstResponder];
	}
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField resignFirstResponder];
	if (textField ==  self.titleZone) {
		if ([self.titleZone.text isEqual: @""]) {
			return YES;
		}
	}
	return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
	return YES;
}

- (void)keyboardDidShow: (NSNotification *) notif{
	// Do something here
	//NSLog(@"show");

}

- (void)keyboardDidHide: (NSNotification *) notif{
	// Do something here
	//NSLog(@"hide");
	[self resignFirstResponder];
}

//*****************************************//
//*** numberOfSectionsInCollectionView ****//
//*****************************************//

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
	return 1;
}

//*****************************************//
//******** numberOfItemsInSection *********//
//*****************************************//

- (void)notify {
	[[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self];
}

- (void)moveDown:(NSNotification*)note {
	CGPoint point = self.themSearch.frame.origin ;
	self.scrollView.contentOffset = point;
}

- (void)handleNotification:(NSNotification*)note {
	self.collecView.hidden = NO;
	contents = [self getArticleContent];
	//NSLog(@"\n\n%@\n\n",contents);
	[self.collecView reloadData];
	[self.tableImage reloadData];
}

- (void)handleTagNotif:(NSNotification*)note {
	[self loadData];
	[self resizeCatList:self.tagView rowsNumber:[self.tagView numberOfItemsInSection:0]];
	[self resizeCatList:self.themTagView rowsNumber:[self.themTagView numberOfItemsInSection:0]];
}

- (void)enteringTagSearchBar:(NSNotification*)note {
	NSLog(@"them enter");
	originalDisplaySearchSize = self.searchDisplay.frame.size.height;
	NSInteger currentDelta = self.themSearch.frame.origin.y - (self.searchBar.frame.origin.y + self.searchBar.frame.size.height);
	NSInteger decalage = 0;
	if (currentDelta < self.searchDisplay.frame.size.height) {
		NSLog(@"them enter if");
		decalage = self.searchDisplay.frame.size.height - currentDelta;
		[self moveObjectsToAdjustView:self.tagView sizeToAdjust:decalage];
	}
	lastDecalage = decalage;
}

- (void)exitingTagSearchBar:(NSNotification*)note {
	[self moveObjectsToAdjustView:self.tagView sizeToAdjust:(0 - lastDecalage)];
	self.searchDisplay.frame = CGRectMake (self.searchDisplay.frame.origin.x, self.searchDisplay.frame.origin.y, self.searchDisplay.frame.size.width, originalDisplaySearchSize);
	lastDecalage = 0;
	[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTags" object:self];
}

- (void)enteringThemTagSearchBar:(NSNotification*)note {
	NSLog(@"them enter");
	originalThemDisplaySearchSize = self.themSearchDisplay.frame.size.height;
	NSInteger currentDelta = self.tableImage.frame.origin.y - (self.themSearch.frame.origin.y + self.themSearch.frame.size.height);
	NSInteger decalage = 0;
	if (currentDelta < self.themSearchDisplay.frame.size.height) {
		NSLog(@"enter if");
		decalage = self.themSearchDisplay.frame.size.height - currentDelta;
		[self moveObjectsToAdjustView:self.themTagView sizeToAdjust:decalage];
	}
	themLastDecalage = decalage;
}

- (void)exitingThemTagSearchBar:(NSNotification*)note {
	[self moveObjectsToAdjustView:self.themTagView sizeToAdjust:(0 - themLastDecalage)];
	self.themSearchDisplay.frame = CGRectMake (self.themSearchDisplay.frame.origin.x, self.themSearchDisplay.frame.origin.y, self.themSearchDisplay.frame.size.width, originalThemDisplaySearchSize);
	themLastDecalage = 0;
	[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTags" object:self];
}

- (void)resetMyView {
	[self.collecView setHidden:NO];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
	if (collectionView == self.tagView)
	{
		//NSLog(@"%@", self.arrTagInfo);
		return self.arrTagInfo.count;
	}
	if (collectionView == self.themTagView)
	{
		//NSLog(@"%@", self.arrThemTagInfo);
		return self.arrThemTagInfo.count;
	}
	return contents.count;
}

//*****************************************//
//*************** text return *************//
//*****************************************//

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
	if (collectionView == self.tagView)
	{
		catValue = [NSString stringWithFormat:@"%@", self.arrTagInfo[indexPath.row][1]];
		UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:@"supprimer cette catégorie ?" delegate:self cancelButtonTitle:@"annuler" destructiveButtonTitle:nil otherButtonTitles:
								@"supprimer la catégorie",
								nil];
		popup.tag = 1;
  [popup showInView:self.view];
	}
	
	if (collectionView == self.themTagView)
	{
		catValue = [NSString stringWithFormat:@"%@", self.arrThemTagInfo[indexPath.row][1]];
		UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:@"supprimer cette catégorie ?" delegate:self cancelButtonTitle:@"annuler" destructiveButtonTitle:nil otherButtonTitles:
								@"supprimer la catégorie",
								nil];
		popup.tag = 1;
  [popup showInView:self.view];
	}
}

-(void)deleteCat {
	NSString *query2 = [NSString stringWithFormat:@"delete from catGeo where geoID = %@", catValue];
	NSString *query = [NSString stringWithFormat:@"delete from catThem where themID = %@", catValue];
	// Execute the query.
	[self.dbManager executeQuery:query2];
	[self.dbManager executeQuery:query];
	[self handleTagNotif:nil];
}

- (void)actionSheet:(UIActionSheet *)popup clickedButtonAtIndex:(NSInteger)buttonIndex {
	switch (popup.tag) {
		case 1:
			switch (buttonIndex) {
				case 0:
					[self deleteCat];
					break;
			}
			break;
		case 2:
			switch (buttonIndex) {
				case 0:
					[self selectPhoto];
					break;
				case 1:
					[self addPhoto];
				default:
					break;
			}
			break;
		case 3:
			switch (buttonIndex) {
				case 0:
					[self selectVideo];
					break;
				case 1:
					[self addVideo];
				default:
					break;
			}
			break;
		case 4:
			switch (buttonIndex) {
				case 0:
					[self selectSound];
					break;
				case 1:
					[self addSound];
					break;
				default:
					break;
			}
			break;
	}
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
	if (collectionView == self.tagView)
	{
		NSInteger indexOfTitle = [self.dbManager.arrColumnNames indexOfObject:@"nomLC"];
		NSString *text = [NSString stringWithFormat:@"%@", [[self.arrTagInfo objectAtIndex:indexPath.row] objectAtIndex:2]];
		UIFont * font = [UIFont systemFontOfSize:17.0f];
		CGSize size = [text sizeWithAttributes:@{NSFontAttributeName: font}];
		size.width = self.tagView.frame.size.width;
		size.height = size.height + 2;
		return size;
	}
	if (collectionView == self.themTagView)
	{
		NSInteger indexOfTitle = [self.dbManager.arrColumnNames indexOfObject:@"nomLC"];
		NSString *text = [NSString stringWithFormat:@"%@", [[self.arrThemTagInfo objectAtIndex:indexPath.row] objectAtIndex:2]];
		UIFont * font = [UIFont systemFontOfSize:17.0f];
		CGSize size = [text sizeWithAttributes:@{NSFontAttributeName: font}];
		size.width = self.tagView.frame.size.width;
		size.height = size.height + 2;
		return size;
	}
	return CGSizeMake(50,50);
}

- (void) resizeCatList:(UICollectionView*)collectionView rowsNumber:(NSInteger)rowsNumber {
	NSInteger collectionViewSizeBefore = collectionView.frame.size.height;
	UICollectionViewCell* cell;
	if (rowsNumber > 0) {
		NSArray *visiblePaths = [collectionView indexPathsForVisibleItems];
		NSInteger newHeight = 0;
		NSInteger cellHeight = 0;
		if (visiblePaths.count > 0 ) {
			if (collectionView == self.tagView) {
				cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"isCell" forIndexPath:visiblePaths[0]];
			} else if (collectionView == self.themTagView) {
				cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:visiblePaths[0]];
			}
			cellHeight = cell.layoutMargins.top + cell.layoutMargins.bottom + cell.frame.size.height - 6;
		} else {
			cellHeight = 38;
		}
		newHeight = cellHeight * rowsNumber;
		collectionView.frame = CGRectMake (collectionView.frame.origin.x, collectionView.frame.origin.y, collectionView.frame.size.width, newHeight);
	} else {
		collectionView.frame = CGRectMake (collectionView.frame.origin.x, collectionView.frame.origin.y, collectionView.frame.size.width, 0);
	}
	NSInteger heightDelta = collectionView.frame.size.height - collectionViewSizeBefore;
	[self moveObjectsToAdjustView:collectionView sizeToAdjust:heightDelta];
}

- (void) moveObjectsToAdjustView:(UICollectionView*)collectionView sizeToAdjust:(NSInteger)sizeToAdjust {
	if (collectionView == self.tagView) {
		self.themSearch.frame = CGRectMake (self.themSearch.frame.origin.x, (self.themSearch.frame.origin.y + sizeToAdjust), self.themSearch.frame.size.width, self.themSearch.frame.size.height);
		
		self.themSearchDisplay.frame = CGRectMake (self.themSearchDisplay.frame.origin.x, (self.themSearchDisplay.frame.origin.y + sizeToAdjust), self.themSearchDisplay.frame.size.width, self.themSearchDisplay.frame.size.height);
		
		self.themTagView.frame = CGRectMake (self.themTagView.frame.origin.x, (self.themTagView.frame.origin.y + sizeToAdjust), self.themTagView.frame.size.width, self.themTagView.frame.size.height);
		
		self.tableImage.frame = CGRectMake (self.tableImage.frame.origin.x, (self.tableImage.frame.origin.y + sizeToAdjust), self.tableImage.frame.size.width, self.tableImage.frame.size.height);
		
	} else if (collectionView == self.themTagView) {
		self.tableImage.frame = CGRectMake (self.tableImage.frame.origin.x, (self.tableImage.frame.origin.y + sizeToAdjust), self.tableImage.frame.size.width, self.tableImage.frame.size.height);
	}
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
	UICollectionViewCell *cell;
	if (collectionView == self.tagView) {
		cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"isCell" forIndexPath:indexPath];
		UILabel *myLabel = (UILabel *)[cell viewWithTag:42];
		NSString *textName = [NSString stringWithFormat:@"%@", [[self.arrTagInfo objectAtIndex:indexPath.row] objectAtIndex:2]];
		myLabel.text = textName; // app crash here
		cell.layer.cornerRadius = 5;
		cell.layer.masksToBounds = YES;
		cell.layer.borderColor = [[UIColor grayColor] CGColor];
		cell.layer.borderWidth = 0.5f;
	}
	if (collectionView == self.themTagView) {
		cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
		UILabel *myLabel = (UILabel *)[cell viewWithTag:43];
		NSString *textName = [NSString stringWithFormat:@"%@", [[self.arrThemTagInfo objectAtIndex:indexPath.row] objectAtIndex:2]];
		myLabel.text = textName;
		cell.autoresizingMask = YES;
		cell.layer.cornerRadius = 5;
		cell.layer.masksToBounds = YES;
		cell.layer.borderColor = [[UIColor grayColor] CGColor];
		cell.layer.borderWidth = 0.5f;
	}
	return cell;
}

- (void) reloadTagView {
	[self.tagView reloadData];
}

//*****************************************//
//************** image delete *************//
//*****************************************//

- (void)removeImage:(NSString*)fullPath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath: fullPath error:NULL];
    //NSLog(@"image removed");
}

//*****************************************//
//**************** info saver *************//
//*****************************************//

- (IBAction)saveInfo:(id)sender {
	id myId = [NSNumber numberWithInteger: self.recordIDToEdit];
	
    if ([self enteredArticleIsEmpty]) {
		[self.keyboardManager stopMonitoring];
		[self.navigationController popViewControllerAnimated:YES];
		[self deleteArticle:self.recordIDToEdit];
	} else {
		// Prepare the query string.
		// If the recordIDToEdit property has value other than -1, then create an update query. Otherwise create an insert query.
		NSString *query;
		NSString *contentHtml = [self.editorView getHTML];
		NSString *contentString = [self.editorView getText];
		
		//update de l'article
		ZIMSqlUpdateStatement *myUpdatequery = [[ZIMSqlUpdateStatement alloc] init];
		[myUpdatequery table:@"article"];
		[myUpdatequery where:@"fileInfoID" operator:@"=" value:myId];
		[myUpdatequery column:@"titleZone" value:self.titleZone.text];
		[myUpdatequery column:@"chapo" value:self.chapoZone.text];
		[myUpdatequery column:@"content" value:contentHtml];
		[myUpdatequery column:@"otherInfo" value:contentString];
		query = myUpdatequery.statement;
			
		// Execute the query.
		[self.dbManager executeQuery:query];

		// If the query was successfully executed then pop the view controller.
		if (self.dbManager.affectedRows != 0) {
			//NSLog(@"Query was executed successfully. Affected rows = %d", self.dbManager.affectedRows);
			// Inform the delegate that the editing was finished.
			[self.delegate editingInfoWasFinished];
			// Pop the view controller.
			[self.keyboardManager stopMonitoring];
			[self.navigationController popViewControllerAnimated:YES];
		}
	}
	[[NSNotificationCenter defaultCenter] postNotificationName:@"returningToArticleList" object:self];
}

- (void) deleteArticle:(int)articleId {
	id myId = [NSNumber numberWithInteger: articleId];
	NSString* query;
	
	ZIMSqlDeleteStatement *articledeletequery = [[ZIMSqlDeleteStatement alloc] init];
	[articledeletequery table:@"article"];
	[articledeletequery where:@"fileInfoID" operator:@"=" value:myId];
	query = articledeletequery.statement;
	// Execute the query.
	[self.dbManager executeQuery:query];
	
	ZIMSqlDeleteStatement *catgeodeletequery = [[ZIMSqlDeleteStatement alloc] init];
	[catgeodeletequery table:@"catGeo"];
	[catgeodeletequery where:@"fileInfoID" operator:@"=" value:myId];
	query = catgeodeletequery.statement;
	// Execute the query.
	[self.dbManager executeQuery:query];
	
	ZIMSqlDeleteStatement *catthemdeletequery = [[ZIMSqlDeleteStatement alloc] init];
	[catthemdeletequery table:@"catThem"];
	[catthemdeletequery where:@"fileInfoID" operator:@"=" value:myId];
	query = catthemdeletequery.statement;
	// Execute the query.
	[self.dbManager executeQuery:query];
	
	ZIMSqlDeleteStatement *imagedeletequery = [[ZIMSqlDeleteStatement alloc] init];
	[imagedeletequery table:@"image"];
	[imagedeletequery where:@"articleId" operator:@"=" value:myId];
	query = imagedeletequery.statement;
	// Execute the query.
	[self.dbManager executeQuery:query];
	
	ZIMSqlDeleteStatement *videodeletequery = [[ZIMSqlDeleteStatement alloc] init];
	[videodeletequery table:@"video"];
	[videodeletequery where:@"articleId" operator:@"=" value:myId];
	query = videodeletequery.statement;
	// Execute the query.
	[self.dbManager executeQuery:query];
	
	ZIMSqlDeleteStatement *sounddeletequery = [[ZIMSqlDeleteStatement alloc] init];
	[sounddeletequery table:@"article_sound"];
	[sounddeletequery where:@"articleId" operator:@"=" value:myId];
	query = sounddeletequery.statement;
	// Execute the query.
	[self.dbManager executeQuery:query];
	
	NSString *path;
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", articleId]];
	BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	
}
- (BOOL) enteredArticleIsEmpty {
	
	NSString* titleTxt = self.titleZone.text;
	NSString* chapoTxt = self.chapoZone.text;
	NSString* otherInfosTmp = [self.editorView getText];
	
	
	NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
	NSString *otherInfosTxt = [[otherInfosTmp componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];
	
	
	NSString *queryCat = [NSString stringWithFormat:@"select * from catGeo where fileInfoID = '%d'", self.recordIDToEdit];
	NSArray *dataCat = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:queryCat]];
	NSInteger catGeoNumber = dataCat.count;
	
	NSString *queryThemCat = [NSString stringWithFormat:@"select * from catThem where fileInfoID = '%d'", self.recordIDToEdit];
	NSArray *dataThemCat = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:queryThemCat]];
	NSInteger themCatNumber = dataThemCat.count;
	
	NSInteger imageNumber = [self.tableImage numberOfRowsInSection:0];
	if ([titleTxt  isEqual: @""] && [chapoTxt  isEqual: @""] && [otherInfosTxt  isEqual: @""] && catGeoNumber == 0 && themCatNumber == 0 && imageNumber == 0) {
		return true;
	} else {
		return false;
	}
}
//*****************************************//
//************** take a photo *************//
//*****************************************//

- (IBAction)takePhoto:(id)sender {
	if (self.tableImage.delegate != NULL)
	{
		//NSLog(@"Mon delegate est au top");
	} else
	{
		//NSLog(@"Mon delegate est cassé");
	}
	UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:@"Ajouter une photo"
															 delegate:self
													cancelButtonTitle:@"Annuler"
										 destructiveButtonTitle:nil
													otherButtonTitles:@"Depuis la galerie", @"Depuis l'appareil", nil];
	popup.tag = 2;
	[popup showInView:self.view];
}
//*****************************************//
//************** pincking a video *************//
//*****************************************//

- (IBAction)pickVideo:(id)sender {
	UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:@"Ajouter une video"
															 delegate:self
													cancelButtonTitle:@"Annuler"
										 destructiveButtonTitle:nil
													otherButtonTitles:@"Depuis la galerie", @"Depuis l'appareil", nil];
	popup.tag = 3;
	[popup showInView:self.view];
}
//*****************************************//
//************** pincking a sound *************//
//*****************************************//

- (IBAction)pickSound:(id)sender {
	UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:@"Ajouter un son"
															 delegate:self
													cancelButtonTitle:@"Annuler"
										 destructiveButtonTitle:nil
													otherButtonTitles:@"Depuis la sonothèque", @"Enregistrer un son", nil];
	popup.tag = 4;
	[popup showInView:self.view];
}

//*****************************************//
//************* picking image *************//
//*****************************************//

- (void)addPhoto {
	fileMustBeInsertedIntoLibrary = true;
	currentMediaTypePicking = @"photo";
	[[NSOperationQueue mainQueue] addOperationWithBlock:^{
		UIImagePickerController *picker = [[UIImagePickerController alloc] init];
		picker.delegate = self;
		picker.allowsEditing = YES;
		picker.sourceType = UIImagePickerControllerSourceTypeCamera;
		[self presentViewController:picker animated:YES completion:NULL];
	}];
}

- (void)selectPhoto {
	fileMustBeInsertedIntoLibrary = false;
	currentMediaTypePicking = @"photo";
	[[NSOperationQueue mainQueue] addOperationWithBlock:^{
		UIImagePickerController *picker = [[UIImagePickerController alloc] init];
		picker.delegate = self;
		picker.allowsEditing = YES;
		picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
		[self presentViewController:picker animated:YES completion:NULL];
	}];
}

//*****************************************//
//************* picking video *************//
//*****************************************//


- (void)addVideo {
	fileMustBeInsertedIntoLibrary = true;
	currentMediaTypePicking = @"video";
	[[NSOperationQueue mainQueue] addOperationWithBlock:^{
		UIImagePickerController *picker = [[UIImagePickerController alloc] init];
		picker.sourceType = UIImagePickerControllerSourceTypeCamera;
		picker.allowsEditing = YES;
		picker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeMovie];
		picker.delegate = self;
		[self presentViewController:picker animated:YES completion:NULL];
	}];
}

- (void)selectVideo {
	fileMustBeInsertedIntoLibrary = false;
	currentMediaTypePicking = @"video";
	[[NSOperationQueue mainQueue] addOperationWithBlock:^{
		UIImagePickerController *picker = [[UIImagePickerController alloc] init];
		picker.delegate = self;
		picker.allowsEditing = YES;
		picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
		picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
		[self presentViewController:picker animated:YES completion:NULL];
	}];
}

//*****************************************//
//************* picking a sound *************//
//*****************************************//


- (void)addSound {
	[self recordSound];
}

- (void)selectSound {
	[self.activityIndicator setHidden:NO];
	popSoundManager = [soundManagerViewController alloc];
	[popSoundManager showInView:self.view	animated:YES articleId:self.recordIDToEdit];
}

- (void) mediaPickerDidCancel: (MPMediaPickerController *) mediaPicker {
	[mediaPicker dismissViewControllerAnimated:YES completion:nil];
}

- (NSString*)getErrorMsgForPush {
	NSString* errorMsg = @"";
	NSString* titleTxt = self.titleZone.text;
	
	NSString *queryCat = [NSString stringWithFormat:@"select * from catGeo where fileInfoID = '%d'", self.recordIDToEdit];
	NSArray *dataCat = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:queryCat]];
	NSInteger catGeoNumber = dataCat.count;
	
	NSString *queryThemCat = [NSString stringWithFormat:@"select * from catThem where fileInfoID = '%d'", self.recordIDToEdit];
	NSArray *dataThemCat = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:queryThemCat]];
	NSInteger themCatNumber = dataThemCat.count;
	
	if ([titleTxt  isEqual: @""] ) {
		if (errorMsg.length > 0) {
			errorMsg = [errorMsg stringByAppendingString: @"\n"];
		}
		errorMsg = [errorMsg stringByAppendingString: @"Titre manquant"];
	}
	if (catGeoNumber == 0) {
		if (errorMsg.length > 0) {
			errorMsg = [errorMsg stringByAppendingString: @"\n"];
		}
		errorMsg = [errorMsg stringByAppendingString: @"Catégorie géographique manquante"];
	}
	if (themCatNumber == 0) {
		if (errorMsg.length > 0) {
			errorMsg = [errorMsg stringByAppendingString: @"\n"];
		}
		errorMsg = [errorMsg stringByAppendingString: @"Catégorie thématique manquante"];
	}
	return errorMsg;
}

-(void) showMessage:(NSString*)title message:(NSString*)msg {

	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
													message:msg
												   delegate:self
										  cancelButtonTitle:@"OK"
										  otherButtonTitles:nil, nil];
	[alert show];
	
}

- (void)displayArticleProgress:(NSNotification*)note {
	[popArticleProgess showInView:self.view	animated:YES];
}

- (void)pushArticle:(NSNotification*)note {
	
	if (([self.titleZone.text isEqualToString:@""]) && ([self.content.text isEqualToString:@" "]) && ([self.otherInfos.text isEqualToString:@""])){
		[self.navigationController popViewControllerAnimated:YES];
		return ;
	}
	
	// Prepare the query string.
	// If the recordIDToEadit property has value other than -1, then create an update query. Otherwise create an insert query.
	NSString *query;
	NSString *contentText = [self.editorView getHTML];
	//NSLog(@"contentText %@", contentText);
	if (self.recordIDToEdit == -1) {
		query = [NSString stringWithFormat:@"insert into article values(null, \"%@\", \"%@\", \"%@\", \"%@\")", self.titleZone.text, contentText, self.otherInfos.text, self.chapoZone.text];
		
		ZIMSqlInsertStatement *myInsertQuery = [[ZIMSqlInsertStatement alloc] init];
		[myInsertQuery into:@"article"];
		[myInsertQuery column:@"titleZone" value:self.titleZone.text];
		[myInsertQuery column:@"content" value:contentText];
		[myInsertQuery column:@"otherInfo" value:self.otherInfos.text];
		[myInsertQuery column:@"chapo" value:self.chapoZone.text];
		query = myInsertQuery.statement;
	} else {
		ZIMSqlUpdateStatement *myUpdatequery = [[ZIMSqlUpdateStatement alloc] init];
		id myId = [NSNumber numberWithInteger: self.recordIDToEdit];
		[myUpdatequery table:@"article"];
		[myUpdatequery where:@"fileInfoID" operator:@"=" value:myId];
		[myUpdatequery column:@"titleZone" value:self.titleZone.text];
		[myUpdatequery column:@"content" value:contentText];
		if (self.otherInfos.text != nil) {
			[myUpdatequery column:@"otherInfo" value:self.otherInfos.text];
		} else {
			[myUpdatequery column:@"otherInfo" value:@""];
		}
		[myUpdatequery column:@"chapo" value:self.chapoZone.text];
		query = myUpdatequery.statement;
	}
	// Execute the query.
	[self.dbManager executeQuery:query];
	
	// If the query was successfully executed then pop the view controller.
	if (self.dbManager.affectedRows != 0) {
		//NSLog(@"Query was executed successfully. Affected rows = %d", self.dbManager.affectedRows);
		// Inform the delegate that the editing was finished.
		[self.delegate editingInfoWasFinished];
	}
	else{
		//NSLog(@"Could not execute the query.");
	}
 
	//*****************************************//
	//************ Xml generation *************//
	//*****************************************//
	
	if (self.recordIDToEdit == -1)
	{
		self.recordIDToEdit = self.dbManager.lastInsertedRowID;
	}
	NSString *pathForContents= [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d", self.recordIDToEdit]];
	contents = [self getArticleContent];
	NSString *exportPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/export", self.recordIDToEdit]];
	if(![[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
		[[NSFileManager defaultManager] createDirectoryAtPath:exportPath withIntermediateDirectories:FALSE attributes:nil error:nil];
	}
	
	NSUserDefaults *pref;
	pref=[NSUserDefaults standardUserDefaults];
	int userId = [pref integerForKey:@"userId"];
	NSString *userIdStr = [pref stringForKey:@"userId"];
	
	NSUserDefaults *pref2;
	pref2=[NSUserDefaults standardUserDefaults];
	NSString* canalId = [pref2 stringForKey:@"canalId"];
	
	NSString* imagesPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/images", self.recordIDToEdit]];
	NSArray* imageContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[pathForContents stringByAppendingString:@"/images"] error:NULL];
	
	NSString* videoPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/videos", self.recordIDToEdit]];
	NSArray* videoContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[pathForContents stringByAppendingString:@"/videos"] error:NULL];
	
	NSString* soundPath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/sounds"];
	NSArray* soundContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:soundPath error:NULL];
	
	///////////////////////////////////////NEW XML GENERATION////////////////////////////////////
	// start writing XML
	//************************************RECUPERATION DES DONNES************************************
	id articleID = [NSNumber numberWithInteger: self.recordIDToEdit];
	ZIMSqlSelectStatement *mySelectStatementForCatGeo = [[ZIMSqlSelectStatement alloc]init];
	[mySelectStatementForCatGeo from:@"catGeo"];
	[mySelectStatementForCatGeo where:@"fileInfoID" operator:@"=" value:articleID];
	NSArray* dataCatGeo = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:[mySelectStatementForCatGeo statement]]];
	
	ZIMSqlSelectStatement *mySelectStatementForCatThem = [[ZIMSqlSelectStatement alloc]init];
	[mySelectStatementForCatThem from:@"catThem"];
	[mySelectStatementForCatThem where:@"fileInfoID" operator:@"=" value:articleID];
	NSArray* dataCatThem = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:[mySelectStatementForCatThem statement]]];
	
	ZIMSqlSelectStatement *myImageSelectStatement = [[ZIMSqlSelectStatement alloc]init];
	[myImageSelectStatement from:@"image"];
	[myImageSelectStatement where:@"articleId" operator:@"=" value:articleID];
	NSArray* dataImage = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:[myImageSelectStatement statement]]];
	NSUInteger imageLegendIndex = [self.dbManager.arrColumnNames indexOfObject:@"legend"];
	NSUInteger imageCreditIndex = [self.dbManager.arrColumnNames indexOfObject:@"credit"];
	NSUInteger imageNameIndex = [self.dbManager.arrColumnNames indexOfObject:@"imageName"];
	
	ZIMSqlSelectStatement *myVideoSelectStatement = [[ZIMSqlSelectStatement alloc]init];
	[myVideoSelectStatement from:@"video"];
	[myVideoSelectStatement where:@"articleId" operator:@"=" value:articleID];
	NSArray* dataVideo = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:[myVideoSelectStatement statement]]];
	NSUInteger videoTitreIndex = [self.dbManager.arrColumnNames indexOfObject:@"titre"];
	NSUInteger videoNameIndex = [self.dbManager.arrColumnNames indexOfObject:@"videoName"];
	
	ZIMSqlSelectStatement *myArticleSoundsSelectStatement = [[ZIMSqlSelectStatement alloc]init];
	[myArticleSoundsSelectStatement from:@"article_sound"];
	[myArticleSoundsSelectStatement where:@"articleId" operator:@"=" value:articleID];
	NSArray* dataArticleSound = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:[myArticleSoundsSelectStatement statement]]];
	NSUInteger aSoundSoundNameIndex = [self.dbManager.arrColumnNames indexOfObject:@"soundName"];
	
	ZIMSqlSelectStatement *mySoundsSelectStatement = [[ZIMSqlSelectStatement alloc]init];
	[mySoundsSelectStatement from:@"sound"];
	NSArray* dataSound = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:[mySoundsSelectStatement statement]]];
	NSUInteger soundTitreIndex = [self.dbManager.arrColumnNames indexOfObject:@"titre"];
	NSUInteger soundNameIndex = [self.dbManager.arrColumnNames indexOfObject:@"soundName"];
	//************************************RECUPERATION DES DONNES************************************
	
	//************************************CONSTRUCTION DU XML************************************
	XMLWriter* xmlWriter = [[XMLWriter alloc]init];
	[xmlWriter writeStartDocumentWithEncodingAndVersion:@"UTF-8" version:@"1.0"];
		[xmlWriter writeStartElement:@"article"];
			[xmlWriter writeStartElement:@"userId"];
				[xmlWriter writeCharacters:userIdStr];
			[xmlWriter writeEndElement];
	
			[xmlWriter writeStartElement:@"canalId"];
				[xmlWriter writeCharacters:canalId];
			[xmlWriter writeEndElement];
			
			[xmlWriter writeStartElement:@"title"];
				[xmlWriter writeCharacters:self.titleZone.text];
			[xmlWriter writeEndElement];
			
			[xmlWriter writeStartElement:@"abstract"];
				[xmlWriter writeCharacters:self.chapoZone.text];
			[xmlWriter writeEndElement];
			
			[xmlWriter writeStartElement:@"text"];
				[xmlWriter writeCharacters:[NSString stringWithFormat:@"%@", contentText]];
			[xmlWriter writeEndElement];
	
	
			[xmlWriter writeStartElement:@"urgence"];
				[xmlWriter writeCharacters:articleIsEmergency ? @"true" : @"false"];
			[xmlWriter writeEndElement];
	
			[xmlWriter writeStartElement:@"photos"];
	
			for (int i = 0; i < [dataImage count]; i++) {
				NSString *description = [NSString stringWithFormat:@"%@", [[dataImage objectAtIndex:i] objectAtIndex:imageLegendIndex]];
				NSString *credit = [NSString stringWithFormat:@"%@", [[dataImage objectAtIndex:i] objectAtIndex:imageCreditIndex]];
				NSString *fileName = [NSString stringWithFormat:@"%@", [[dataImage objectAtIndex:i] objectAtIndex:imageNameIndex]];
			
				[xmlWriter writeStartElement:@"photo"];
			
					[xmlWriter writeStartElement:@"file"];
						[xmlWriter writeCharacters:fileName];
					[xmlWriter writeEndElement];
				
					[xmlWriter writeStartElement:@"title"];
						[xmlWriter writeCharacters:description];
					[xmlWriter writeEndElement];
					
					[xmlWriter writeStartElement:@"credit"];
						[xmlWriter writeCharacters:credit];
					[xmlWriter writeEndElement];
			
				[xmlWriter writeEndElement];
			}
	
			[xmlWriter writeEndElement];
	
	
			[xmlWriter writeStartElement:@"videos"];
			
			for (int i = 0; i < [dataVideo count]; i++) {
				NSString *titre = [NSString stringWithFormat:@"%@", [[dataVideo objectAtIndex:i] objectAtIndex:videoTitreIndex]];
				NSString *fileName = [NSString stringWithFormat:@"%@", [[dataVideo objectAtIndex:i] objectAtIndex:videoNameIndex]];
				
				[xmlWriter writeStartElement:@"video"];
				
				[xmlWriter writeStartElement:@"file"];
					[xmlWriter writeCharacters:fileName];
				[xmlWriter writeEndElement];
				
				[xmlWriter writeStartElement:@"title"];
					[xmlWriter writeCharacters:titre];
				[xmlWriter writeEndElement];
				
				[xmlWriter writeEndElement];
			}
			[xmlWriter writeEndElement];

	
			[xmlWriter writeStartElement:@"sounds"];
			
			for (int i = 0; i < [dataArticleSound count]; i++) {
				NSString *fileName = [NSString stringWithFormat:@"%@", [[dataArticleSound objectAtIndex:i] objectAtIndex:aSoundSoundNameIndex]];
				NSString *titre = @"";
				//on retrouve le titre par rapport au filename
				for (int j = 0; j < [dataSound count]; j++) {
					NSString* dsSoundName = [[dataSound objectAtIndex:j] objectAtIndex:soundNameIndex];
					if ([dsSoundName isEqualToString:fileName]) {
						titre = [NSString stringWithFormat:@"%@", [[dataSound objectAtIndex:j] objectAtIndex:soundTitreIndex]];
					}
				}
				
				[xmlWriter writeStartElement:@"sound"];
				
				[xmlWriter writeStartElement:@"file"];
					[xmlWriter writeCharacters:fileName];
				[xmlWriter writeEndElement];
				
				[xmlWriter writeStartElement:@"title"];
					[xmlWriter writeCharacters:titre];
				[xmlWriter writeEndElement];
				
				[xmlWriter writeEndElement];
			}
			[xmlWriter writeEndElement];
	
			[xmlWriter writeStartElement:@"categories"];
	
			for (int i = 0; i < [dataCatGeo count]; i++) {
				[xmlWriter writeStartElement:@"category"];
					[xmlWriter writeCharacters:dataCatGeo[i][1]];
				[xmlWriter writeEndElement];
			}
			for (int i = 0; i < [dataCatThem count]; i++) {
				[xmlWriter writeStartElement:@"category"];
					[xmlWriter writeCharacters:dataCatThem[i][1]];
				[xmlWriter writeEndElement];
			}
	
			[xmlWriter writeEndElement];
	
		[xmlWriter writeEndElement];
	[xmlWriter writeEndDocument];
	//************************************CONSTRUCTION DU XML************************************
	///////////////////////////////////////NEW XML GENERATION////////////////////////////////////
	
	NSString *XMLpath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/export/article.xml", self.recordIDToEdit]];
	NSString* xmlcontent = [xmlWriter toString];
	[xmlcontent writeToFile:XMLpath atomically:YES encoding:NSUTF8StringEncoding error:nil];
	
	//*****************************************//
	//************ Compress files *************//
	//*****************************************//
	
	contents = [self getArticleContent];
	NSString *zipFilePath= [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d", self.recordIDToEdit]];
	BOOL isDir = NO;
	NSArray *subpaths;
	NSFileManager *fileManager = [NSFileManager defaultManager];
	if ([fileManager fileExistsAtPath:exportPath isDirectory:&isDir] && isDir){
		subpaths = [fileManager subpathsAtPath:exportPath];
	}
	
	ZipArchive *archiver = [[ZipArchive alloc] init];
	BOOL ret = [archiver CreateZipFile2:[zipFilePath stringByAppendingPathComponent:@"article.zip"]];
	NSArray* exportContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:exportPath error:NULL];
	//NSLog(@"count = %lu \n zipFilePath = %@", count, zipFilePath);
	for (int i = 0; i < exportContent.count; i++) {
		//NSLog(@"contents %@", [contents objectAtIndex: i]);
		NSString *pathOfFile = [exportPath stringByAppendingString:[NSString stringWithFormat:@"/%@",[exportContent objectAtIndex: i]]];
		//NSLog(@"pathoffile = %@", pathOfFile);
		ret = [archiver addFileToZip:pathOfFile newname:[exportContent objectAtIndex: i]];
		NSLog(@"ret = %d", ret);
	}
	
	for (int i = 0; i < imageContents.count; i++) {
		if ([[imageContents objectAtIndex: i] rangeOfString:@".jpg"].location == NSNotFound)
			NSLog(@"skip this file !");
		else {
			NSString *pathOfFile = [imagesPath stringByAppendingString:[NSString stringWithFormat:@"/%@",[imageContents objectAtIndex: i]]];
			//NSLog(@"pathoffile = %@", pathOfFile);
			ret = [archiver addFileToZip:pathOfFile newname:[imageContents objectAtIndex: i]];
		}
	}
	
	for (int i = 0; i < videoContents.count; i++) {
		NSString *pathOfFile = [videoPath stringByAppendingString:[NSString stringWithFormat:@"/%@",[videoContents objectAtIndex: i]]];
		//NSLog(@"pathoffile = %@", pathOfFile);
		ret = [archiver addFileToZip:pathOfFile newname:[videoContents objectAtIndex: i]];
	}
	
	for (int j = 0; j < [dataArticleSound count]; j++) {
		NSString *fileName = [NSString stringWithFormat:@"%@", [[dataArticleSound objectAtIndex:j] objectAtIndex:aSoundSoundNameIndex]];
		for (int i = 0; i < soundContents.count; i++) {
			NSString* browsedFile = [soundContents objectAtIndex: i];
			if ([fileName isEqualToString:browsedFile]) {
				NSString *pathOfFile = [soundPath stringByAppendingString:[NSString stringWithFormat:@"/%@",[soundContents objectAtIndex: i]]];
				//NSLog(@"pathoffile = %@", pathOfFile);
				ret = [archiver addFileToZip:pathOfFile newname:[soundContents objectAtIndex: i]];
			}
		}
	}
	
	if( ![archiver CloseZipFile2] )
		NSLog(@" zip fail");
	else
		NSLog(@" zip success");
	
	unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/article.zip", zipFilePath] error:nil] fileSize];
	
	NSLog(@"fileSize : %ld", (NSUInteger)fileSize);
	
	if ((NSUInteger)fileSize > finalFileMaxUploadSize * 1000000) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"erreur"
														message:@"L'article dépasse la taille autorisée, il est impossible de l'envoyer" delegate:self cancelButtonTitle:@"OK"
											  otherButtonTitles:nil, nil];
		[alert show];
		[[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/article.zip", zipFilePath] error:nil];
		[[NSNotificationCenter defaultCenter] postNotificationName:@"articleSent" object:self];
		
	} else {
		//*****************************************//
		//********* send file to webservice *******//
		//*****************************************//
		NSString *urlString = [NSString stringWithFormat:@"%@webservice/APPLIMOBILE/newArticle", _BO_URL];
		NSURL *url = [NSURL URLWithString:urlString];
		NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
		[request setHTTPMethod:@"POST"];
		NSString *boundary = @"-----------------------------1294919323195";
		NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
		[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
		NSMutableData *body = [NSMutableData data];
		[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
		//NSLog(@"file is : %@/article.zip", zipFilePath);
		[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"zipFile\"; filename=\"Iarticle-%d-%d.zip\"\r\n",userId , self.recordIDToEdit] dataUsingEncoding:NSUTF8StringEncoding]];
		[body appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
		NSData *zipData = [NSData dataWithContentsOfFile: [NSString stringWithFormat:@"%@/article.zip", zipFilePath]];
		[body appendData:[NSData dataWithData:zipData]];
		[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
		[request setHTTPBody:body];
		
		[self sendPushRequest:request];
		[self.activityIndicator setHidden:YES];
	}
	
}

-(void)sendPushRequest:(NSMutableURLRequest*) request {
	/*double totalSize = [self getTotalSizeSent:request];
	
	NSLog(@"%f", totalSize);*/
	
	NSURLSession *session = [NSURLSession sharedSession];
	
	NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
		
		[[NSNotificationCenter defaultCenter] postNotificationName:@"articleSent" object:self];
		
		NSString* xmlResponse=[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
		//NSLog(@"\n\n\n\n\n\n response:\n: %@\n\n\n\n\n", xmlResponse);
		
		if ([xmlResponse rangeOfString:@"<error>"].location == NSNotFound) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Article : %@", self.titleZone.text]
															message:@"correctement envoyé" delegate:self cancelButtonTitle:@"OK"
												  otherButtonTitles:nil, nil];
			[alert show];
			[self.navigationController popViewControllerAnimated:YES];
			
			[self deleteArticle:self.recordIDToEdit];
			
			[self.delegate editingInfoWasFinished];
			// delete the image folder.
			NSString *path;
			NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
			path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", self.recordIDToEdit]];
			//NSLog(@"folder %@ successfuly deleted", path);
			NSString *query;
			NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
			[dateFormatter setDateFormat:@"dd/MM/yyyy "];
			NSString *date = [NSString stringWithFormat: @"%@", [dateFormatter stringFromDate:[NSDate date]]];
			query = [NSString stringWithFormat:@"insert into logs values(\"%@\", \"%@\")", self.titleZone.text, date];
			[self.dbManager executeQuery:query];
			
			// If the query was successfully executed then pop the view controller.
			if (self.dbManager.affectedRows != 0) {
				//NSLog(@"Query was executed successfully hahaha. Affected rows = %d", self.dbManager.affectedRows);
				// Inform the delegate that the editing was finished.
				[self.delegate editingInfoWasFinished];
			}
			else{
				NSLog(@"Could not execute the query.");
			}
		}
		else {  // in case of error during the article creation or in webservice reponce
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"erreur"
															message:@"echec de l'envoi de votre article" delegate:self cancelButtonTitle:@"OK"
												  otherButtonTitles:nil, nil];
			[alert show];
		}
	}];
	
	[task resume];
}

-(double)getTotalSizeSent:(NSMutableURLRequest*) request {
	
	dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
	NSURLSession *session = [NSURLSession sharedSession];
	__block double totalBytesExpectedToReceive;
	
	NSURLSessionDataTask *sizeTask =
	[session
	 dataTaskWithRequest:request
	 completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error)
	 {
		 if (error == nil)
		 {
			 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
			 
			 if ([httpResponse statusCode] == 200) {
				 
				 totalBytesExpectedToReceive += (double)[httpResponse expectedContentLength];
				 
				 NSLog(@" files found. file size: %f", totalBytesExpectedToReceive);
			 }
			 else {
				 NSLog(@"Bad status code (%ld) for size task at URL: %@", (long)[httpResponse statusCode], [[response URL] absoluteString]);
			 }
		 }
		 else
		 {
			 NSLog(@"Size task finished with error: %@", error.localizedDescription);
		 }
		 dispatch_semaphore_signal(semaphore);
	 }];
	
	[sizeTask resume];
	dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
	
	return totalBytesExpectedToReceive;
}

- (IBAction)sendArticle:(id)sender {
	NSString* errorForPush = [self getErrorMsgForPush];
	if (errorForPush.length > 0) {
		[self showMessage:@"Erreur" message:errorForPush];
		return;
	}
	[self.activityIndicator setHidden:NO];
	popCanal = [canalController	alloc];
	[popCanal showInView:self.view	animated:YES valueToEdit:[NSString stringWithFormat:@"index.png"] articleId:self.recordIDToEdit];
	
	popArticleProgess = [sendArticleProgressViewController alloc];
	
}

- (IBAction)recordSound {
	[self.activityIndicator setHidden:NO];
	popVoiceRecorder = [voiceRecorderViewController alloc];
	[popVoiceRecorder showInView:self.view	animated:YES valueToEdit:[NSString stringWithFormat:@"index.png"] articleId:self.recordIDToEdit forSoundManager:false];
}

//*****************************************//
//************* save an image *************//
//*****************************************//

- (void)saveImage:(UIImage*)UIimage imageName:(NSString*)imageName folderPath:(NSString*)folderPath {
	NSString *query;
	NSData *imageData = UIImageJPEGRepresentation(UIimage, 1.0);
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@/%@.jpg", folderPath, imageName]];
	query = [NSString stringWithFormat:@"insert into image values(\"%@.jpg\", %d, \"%@\", \"%@\")", imageName, self.recordIDToEdit, @"", @""];
	//NSLog(@"query = %@", query);
	[self.dbManager executeQuery:query];
	if (self.dbManager.affectedRows != 0) {
		//NSLog(@"Query was executed successfully. Affected rows = %d", self.dbManager.affectedRows);
		// Inform the delegate that the editing was finished.
		[self.delegate editingInfoWasFinished];
	}
	else{
		//NSLog(@"Could not execute the query.");
	}
	[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
	if (fileMustBeInsertedIntoLibrary) {
		UIImageWriteToSavedPhotosAlbum(UIimage, nil, nil, nil);
		fileMustBeInsertedIntoLibrary = false;
	}
	//NSLog(@"image saved");
	[tvd reload];
}

- (NSString *)contentTypeForImageData:(NSData *)data {
	uint8_t c;
	[data getBytes:&c length:1];
	
	switch (c) {
		case 0xFF:
			return @"image/jpeg";
		case 0x89:
			return @"image/png";
		case 0x47:
			return @"image/gif";
		case 0x49:
		case 0x4D:
			return @"image/tiff";
	}
	return nil;
}

//*****************************************//
//************* save a video *************//
//*****************************************//

- (void)saveVideo:(NSData*)videoData videoName:(NSString*)videoName videoPath:(NSString*)videoPath {
	NSString *pathDataVideos = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/videos", self.recordIDToEdit]];
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *query;
	ZIMSqlInsertStatement *myInsertQuery = [[ZIMSqlInsertStatement alloc] init];
	id myId = [NSNumber numberWithInteger: self.recordIDToEdit];
	[myInsertQuery into:@"video"];
	[myInsertQuery column:@"videoName" value:videoName];
	[myInsertQuery column:@"articleId" value:myId];
	[myInsertQuery column:@"titre" value:@""];
	query = myInsertQuery.statement;
	[self.dbManager executeQuery:query];
	
	if (self.dbManager.affectedRows != 0) {
		// Inform the delegate that the editing was finished.
		[self.delegate editingInfoWasFinished];
	}
	[fileManager createFileAtPath:videoPath contents:videoData attributes:nil];
	if ([contents count] > 0) {
		NSArray* tmp = [contents arrayByAddingObjectsFromArray:[[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathDataVideos error:NULL]];
		NSLog(@"%@", tmp);
	} else {
		NSArray* tmp = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathDataVideos error:NULL];
		NSLog(@"%@", tmp);
	}
	
	BOOL fileIsCompatible = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoPath);
	if (fileMustBeInsertedIntoLibrary == true && fileIsCompatible == true) {
		UISaveVideoAtPathToSavedPhotosAlbum(videoPath, nil, nil, nil);
		fileMustBeInsertedIntoLibrary = false;
	}
	[tvd reload];
}

//*****************************************//
//************* save a sound *************//
//*****************************************//

- (void)saveSound:(NSData*)soundData soundName:(NSString*)soundName soundPath:(NSString*)soundPath {
	NSString *pathDataSounds = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/sounds"];
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *query;
	ZIMSqlInsertStatement *mySoundInsertQuery = [[ZIMSqlInsertStatement alloc] init];
	[mySoundInsertQuery into:@"sound"];
	[mySoundInsertQuery column:@"soundName" value:soundName];
	[mySoundInsertQuery column:@"titre" value:@""];
	NSString* queryInsert = mySoundInsertQuery.statement;
	[self.dbManager executeQuery:queryInsert];

	ZIMSqlInsertStatement *myInsertQuery = [[ZIMSqlInsertStatement alloc] init];
	id myId = [NSNumber numberWithInteger: self.recordIDToEdit];
	[myInsertQuery into:@"article_sound"];
	[myInsertQuery column:@"soundName" value:soundName];
	[myInsertQuery column:@"articleId" value:myId];
	query = myInsertQuery.statement;
	[self.dbManager executeQuery:query];
	
	if (self.dbManager.affectedRows != 0) {
		// Inform the delegate that the editing was finished.
		[self.delegate editingInfoWasFinished];
	}
	[fileManager createFileAtPath:soundPath contents:soundData attributes:nil];
	
		NSArray* tmp = [contents arrayByAddingObjectsFromArray:[[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathDataSounds error:NULL]];
		NSLog(@"%@", tmp);
	
	[tvd reload];
}

//*****************************************//
//***** delegate picker image methods *****//
//*****************************************//

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSUserDefaults *pref;
    pref=[NSUserDefaults standardUserDefaults];
    int idGen = [pref integerForKey:@"imageID"];

	[self saveArticleWithCurrentContent];
	
	if ([currentMediaTypePicking  isEqual: @"photo"]) {
		NSString *pathDataImage= [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/images", self.recordIDToEdit]];
		if (![[NSFileManager defaultManager] fileExistsAtPath:pathDataImage]) {
			[[NSFileManager defaultManager] createDirectoryAtPath:pathDataImage withIntermediateDirectories:NO attributes:nil error:nil];
		}
		//NSLog(@"%d", self.recordIDToEdit);
		UIImage *chosenImage = [info objectForKey:UIImagePickerControllerOriginalImage];
		//SAVING IMAGE TO DIRECTORY
		//NSLog(@"result here i am = %d", self.recordIDToEdit);
		[self saveImage:chosenImage imageName:[NSString stringWithFormat:@"index%d", idGen] folderPath:[NSString stringWithFormat: @"%d/images", self.recordIDToEdit]];
		
		   //END OF IMAGE SAVING !
		[picker dismissViewControllerAnimated:YES completion:NULL];
		NSUserDefaults *pref2;
		pref2=[NSUserDefaults standardUserDefaults];
		[pref2 setInteger:idGen + 1 forKey:@"imageID"];
		[pref2 synchronize];
		contents = [self getArticleContent];
		//NSLog(@"\n\n%@\n\n",contents);
		[tvd reload];
		[self.tableImage reloadData];
		popImage = [showImageViewViewController alloc];
		popImage.mediaType = @"image";
		[popImage showInView:self.view	animated:YES valueToEdit:[NSString stringWithFormat:@"index%d.jpg", idGen] articleId:self.recordIDToEdit isForLibrary:false];
	} else if ([currentMediaTypePicking  isEqual: @"video"]) {
		NSString *pathDataVideos = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/videos", self.recordIDToEdit]];
		if (![[NSFileManager defaultManager] fileExistsAtPath:pathDataVideos]) {
			[[NSFileManager defaultManager] createDirectoryAtPath:pathDataVideos withIntermediateDirectories:NO attributes:nil error:nil];
		}
		
		NSURL *videoUrl = (NSURL*)[info objectForKey:UIImagePickerControllerMediaURL];
		NSData *videoData = [NSData dataWithContentsOfURL:videoUrl];
		NSString* extension = [videoUrl pathExtension];
		NSString* fileName = [[self NSDataToMD5String:videoData] stringByAppendingString:[NSString stringWithFormat:@".%@", extension]];
		NSString* filePath = [pathDataVideos stringByAppendingString: [NSString stringWithFormat:@"/%@", fileName]];
		
		if (![self videoIsAlreadyLinkedToArticle:fileName videoPath:filePath]) {
			//SAVING VIDEO TO DIRECTORY
			[self saveVideo:videoData videoName:fileName videoPath:filePath];
			//END OF IMAGE SAVING !
			[picker dismissViewControllerAnimated:YES completion:NULL];
			contents = [self getArticleContent];
			//NSLog(@"\n\n%@\n\n",contents);
			[tvd reload];
			[self.tableImage reloadData];
			popImage = [showImageViewViewController alloc];
			popImage.mediaType = @"video";
			[popImage showInView:self.view	animated:YES valueToEdit:fileName articleId:self.recordIDToEdit isForLibrary:false];
		} else {
			[self showMessage:@"Erreur" message:@"La vidéo est déjà liée à cet article"];
		}
	}
}

- (void)addSoundToArticle: (NSData*)soundData {
	[self saveArticleWithCurrentContent];
	 NSString *pathDataSounds = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/sounds"];
	 if (![[NSFileManager defaultManager] fileExistsAtPath:pathDataSounds]) {
	 [[NSFileManager defaultManager] createDirectoryAtPath:pathDataSounds withIntermediateDirectories:NO attributes:nil error:nil];
	 }
	
	 NSString* extension = @"mp4";
	 NSString* fileName = [[self NSDataToMD5String:soundData] stringByAppendingString:[NSString stringWithFormat:@".%@", extension]];
	 NSString* filePath = [pathDataSounds stringByAppendingString: [NSString stringWithFormat:@"/%@", fileName]];
	
	 //SAVING sound TO DIRECTORY
	 [self saveSound:soundData soundName:fileName soundPath:filePath];
	
	 contents = [self getArticleContent];
	 //NSLog(@"\n\n%@\n\n",contents);
	 [tvd reload];
	 [self.tableImage reloadData];
	 popImage = [showImageViewViewController alloc];
	 popImage.mediaType = @"sound";
	 [popImage showInView:self.view	animated:YES valueToEdit:fileName articleId:self.recordIDToEdit isForLibrary:false];
}

- (void) saveArticleWithCurrentContent {
	// Prepare the query string.
	NSString *query;
	
	NSString *contentHtml = [self.editorView getHTML];
	NSString *contentString = [self.editorView getText];
	ZIMSqlUpdateStatement *myUpdatequery = [[ZIMSqlUpdateStatement alloc] init];
	id myId = [NSNumber numberWithInteger: self.recordIDToEdit];
	[myUpdatequery table:@"article"];
	[myUpdatequery where:@"fileInfoID" operator:@"=" value:myId];
	[myUpdatequery column:@"titleZone" value:self.titleZone.text];
	[myUpdatequery column:@"chapo" value:self.chapoZone.text];
	[myUpdatequery column:@"content" value:contentHtml];
	[myUpdatequery column:@"otherInfo" value:contentString];
	query = myUpdatequery.statement;
	//NSLog(@"query is here :%@", myUpdatequery.statement);
	[self.dbManager executeQuery:query];
}

- (BOOL)videoIsAlreadyLinkedToArticle:(NSString*)videoName videoPath:(NSString*)videoPath{
	BOOL alreadyLinked = false;
	id articleID = [NSNumber numberWithInteger: self.recordIDToEdit];
	ZIMSqlSelectStatement *myVideoSelectStatement= [[ZIMSqlSelectStatement alloc]init];
	[myVideoSelectStatement from:@"video"];
	[myVideoSelectStatement where:@"articleId" operator:@"=" value:articleID];
	[myVideoSelectStatement where:@"videoName" operator:@"=" value:videoName];
	NSString* query = myVideoSelectStatement.statement;
	NSArray* videoSQLResult = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
	
	if ([[NSFileManager defaultManager] fileExistsAtPath:videoPath]) {
		if ([videoSQLResult count] > 0) {
			alreadyLinked = true;
		} else {
			[[NSFileManager defaultManager] removeItemAtPath:videoPath error:nil];
		}
	} else {
		if ([videoSQLResult count] > 0) {
			ZIMSqlDeleteStatement *videoDeleteQuery = [[ZIMSqlDeleteStatement alloc] init];
			[videoDeleteQuery table:@"video"];
			[videoDeleteQuery where:@"articleId" operator:@"=" value:articleID];
			[videoDeleteQuery where:@"videoName" operator:@"=" value:videoName];
			[self.dbManager executeQuery:videoDeleteQuery.statement];
		}
	}
	return alreadyLinked;
}

- (BOOL)soundIsAlreadyLinkedToArticle:(NSString*)soundName soundPath:(NSString*)soundPath{
	BOOL alreadyLinked = false;
	id articleID = [NSNumber numberWithInteger: self.recordIDToEdit];
	ZIMSqlSelectStatement *mySoundSelectStatement= [[ZIMSqlSelectStatement alloc]init];
	[mySoundSelectStatement from:@"article_sound"];
	[mySoundSelectStatement where:@"articleId" operator:@"=" value:articleID];
	[mySoundSelectStatement where:@"soundName" operator:@"=" value:soundName];
	NSString* query = mySoundSelectStatement.statement;
	NSArray* soundSQLResult = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
	
	if ([[NSFileManager defaultManager] fileExistsAtPath:soundPath]) {
		if ([soundSQLResult count] > 0) {
			alreadyLinked = true;
		} else {
			[[NSFileManager defaultManager] removeItemAtPath:soundPath error:nil];
		}
	} else {
		if ([soundSQLResult count] > 0) {
			ZIMSqlDeleteStatement *soundDeleteQuery = [[ZIMSqlDeleteStatement alloc] init];
			[soundDeleteQuery table:@"article_sound"];
			[soundDeleteQuery where:@"articleId" operator:@"=" value:articleID];
			[soundDeleteQuery where:@"soundName" operator:@"=" value:soundName];
			[self.dbManager executeQuery:soundDeleteQuery.statement];
		}
	}
	return alreadyLinked;
}

- (NSString *)NSDataToMD5String:(NSData*) data {
	unsigned char *cstr = (unsigned char *)[data bytes];
	unsigned char result[32];
	CC_MD5(cstr, strlen(cstr), result);
	
	return [NSString stringWithFormat:
			@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
			result[0], result[1], result[2], result[3],
			result[4], result[5], result[6], result[7],
			result[8], result[9], result[10], result[11],
			result[12], result[13], result[14], result[15],
			result[16], result[17], result[18], result[19],
			result[20], result[21], result[22], result[23],
			result[24], result[25], result[26], result[27],
			result[28], result[29], result[30], result[31],
			result[32]
			];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	NSString *pathData= [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/images", self.recordIDToEdit]];
	contents = [self getArticleContent];
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

- (NSArray*) getArticleContent {
	NSArray* contentArray;
	
	NSString *pathDataVideos = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/videos", self.recordIDToEdit]];
	NSString *pathDataimages = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%d/images", self.recordIDToEdit]];
	
	contentArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathDataVideos error:NULL];
	
	if ([contentArray count] > 0) {
		contentArray = [contentArray arrayByAddingObjectsFromArray:[[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathDataimages error:NULL]];
	} else {
		contentArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathDataimages error:NULL];
	}
	
	NSArray* articleSoundsArray = [self getArticleSoundNameArray];
	if ([contentArray count] > 0) {
		contentArray = [contentArray arrayByAddingObjectsFromArray:articleSoundsArray];
	} else {
		contentArray = articleSoundsArray;
	}
	
	return contentArray;
}

- (NSArray*)getArticleSoundNameArray {
	NSMutableArray* soundNameArray = [[NSMutableArray alloc] init];
	id myId = [NSNumber numberWithInteger: self.recordIDToEdit];
	ZIMSqlSelectStatement *articleSoundsSelectStatement = [[ZIMSqlSelectStatement alloc]init];
	[articleSoundsSelectStatement from:@"article_sound"];
	[articleSoundsSelectStatement where:@"articleId" operator:@"=" value:myId];
	NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:articleSoundsSelectStatement.statement]];
	NSUInteger soundNameIndex = [self.dbManager.arrColumnNames indexOfObject:@"soundName"];
	
	for (id result in results) {
		[soundNameArray addObject:[NSString stringWithFormat:@"%@", [result objectAtIndex:soundNameIndex]]];
	}
	return soundNameArray;
}
//*****************************************//
//******** load an existing article *******//
//*****************************************//

-(void)loadInfoToEdit{
    // Create the query.
    NSString *query = [NSString stringWithFormat:@"select * from article where fileInfoID=%d", self.recordIDToEdit];
    
    // Load the relevant data.
    NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
	
    // Set the loaded data to the textfields.
    self.titleZone.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"titleZone"]];
    [self.editorView setHTML:[[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"content"]]];
    self.otherInfos.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"otherInfo"]];
	self.chapoZone.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"chapo"]];
}
@end

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!//
//                                END OF FILE                                         //
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!//
