

















(function($) {
$.ti.share = $.prototype = {

    html:   $([
				'<div id="swapableContent">',
                    '<h2><img src="/shared/resource/images/itinerary_planner/fr/text/share-trip.png" height="28" alt="Enregistrer et partager votre Trip Planner" /></h2>',
                    '<p></p>',
                    '<div id="shareTabs">',
                        '<ul class="tabs">',
                            '<li id="manageTrigger"><a href="#manage">Gérer les accès de vos amis à votre Trip Planner (<span id="tabFriendsCount">0</span>)</a></li>',
                            '<li id="commentsTrigger"><a href="#comments">Commentaires (<span id="tabCommentsCount">0</span>)</a></li>',
                            '<li id="inspireTrigger"><a href="#inspire">Enregistrez et Inspirez d&#39;autres personnes</a></li>',
                        '</ul>',
                        '<div id="manage" class="tab">',
							'<p class="intro">Vous aimez le projet de voyage que vous avez monté sur le Trip Planner du Tourisme Irlandais? Enregistrez-le et inspirez d&#39;autres personnes en rendant votre projet accessible à tous sur Irlande-tourisme.fr</p>',
							'<p class="intro">Vous avez partagé votre projet avec ',
								'<em><span id="friendCount">0</span></em>',
								' Amis</p>',
							'<div class="wrap">',
								'<form method="" action="" id="manageFriends">',
								'</form>',
								'<form method="" action="" id="addFriends">',
									'<fieldset class="section">',
										'<label class="heading" for="friendsEmail">Enregistrez et partagez ce projet avec vos amis</label>',
										'<input class="text" type="text" id="friendsEmail" value="L&#39;adresse email de votre ami" />',
									'</fieldset>',
									'<fieldset class="section" id="friendStatus">',
										'<label class="heading" for="permssions">Qu&#39;est-ce que votre ami à le droit de faire?</label>',
										'<label for="reviewOnly">',
											'<input class="radio" type="radio" id="reviewOnly" value="R" name="permissions" />',
										'Revoir uniquement</label>',
										'<label for="reviewAndContribute">',
											'<input class="radio" type="radio" id="reviewAndContribute" value="C" name="permissions" checked="" />',
										'Revoir et contribuer</label>',
									'</fieldset>',
									'<fieldset>',
										'<label class="heading">Votre message</label>',
										'<textarea id="yourMessage" class="clearfix" rows="5">',
											'Bonjour, J&#39;ai crée ce projet de voyage sur le Trip Planner du Tourisme Irlandais (Irlande-tourisme.fr) et j&#39;aimerais savoir ce que tu en penses. Merci !',
										'</textarea>',
                                        '<label for="ccOwner">',
                                            '<input type="checkbox" id="ccOwner" />',
                                            ' Envoyer une copie à moi',
                                        '</label>',
									'</fieldset>',
									'<div class="input-wrap">',
                                       '<input type="image" class="button" id="addFriend" src="/shared/resource/images/itinerary_planner/fr/buttons/share-this-trip.png" height="22" alt="Enregistrez et partagez ce projet avec vos amis" />',
									'</div>',
								'</form>',
							'</div>',
                        '</div>',
                        '<div id="comments" class="tab">',
                            '<p class="intro">Bonjour, J&#39;ai jeté un coup d&#39;&#339;il à ton projet e voyage sur le site du Tourisme Irlandais (Irlande-tourisme.fr) and j&#39;ai fait quelques commentaires. Merci !</p>',
                            '<p class="intro">Voici tous les commentaires qui ont été ajoutés à votre projet de voyage sur Irlande-tourisme.fr<em> <span id="commentCount">0</span> </em></p>',
							'<form id="submitComment" method="" action="">',
								'<div class="wrap">',
									'<div id="commentsWrapper">',
										'<ul id="commentList">',
										'</ul>',
									'</div>',
									'<fieldset>',
										'<label for="commentText" class="heading">Merci d&#39;ajouter un commentaire.<br>(<span id="charCount">300</span> nombre de caractères restants)</span></label>',
										'<textarea id="commentText" rows="10">',
											'Merci d&#39;ajouter un commentaire à ce projet de voyage sur Irlande-tourisme.fr',
										'</textarea>',
										'<p>Maintenant que vous avez enregistré votre projet de voyage, laissez vos amis le revoir, le commenter et même y contribuer! Vous en tant qu&#39;administrateur de votre projet, pouvez gérer les droits d&#39;accès de chacun.</p>',
									'</fieldset>',
								'</div>',
								'<input type="image" class="button" id="addComment" src="/shared/resource/images/itinerary_planner/fr/buttons/add-comment.png" alt="Merci d&#39;ajouter un commentaire à ce projet de voyage sur Irlande-tourisme.fr" />',
							'</form>',
                        '</div>',
                        '<div id="inspire" class="tab">',
                            '<p class="intro">Vous aimez le projet de voyage que vous avez monté sur le Trip Planner du Tourisme Irlandais? Donnez-lui un nom, enregistrez-le et inspirez d&#39;autres personnes en rendant votre projet accessible à tous sur Irlande-tourisme.fr</p>',
							'<p class="intro" id="tripPublicStatus">Votre voyage n&#39;est pas accessible à tous sur Irlande-tourisme.fr </p>',
							'<form id="makeTripPublic" method="" action="">',
								'<div class="wrap">',
									'<fieldset class="tripDetails first">',
										'<div class="section">',
											'<label for="publicTripName" class="heading">Nom de mon projet de voyage</label>',
											'<input id="publicTripName" type="text" value="" class="text"/>',
										'</div>',
										'<div class="section">',
											'<h4 class="heading">Ou allez-vous?</h4>',
											'<ul id="tripCities">',
												'<li>Irlande</li>',
											'</ul>',
										'</div>',
										'<label for="tripSeason" class="heading">A quelle saison?</label>',
										'<div class="inputRow">',
											'<input type="radio" id="winter" name="tripSeason" value="0" checked="checked" />',
											'<label for="winter">Hiver (Décembre à Février)</label>',
										'</div>',
										'<div class="inputRow">',
											'<input type="radio" id="spring" name="tripSeason" value="1" />',
											'<label for="spring">Printemps ( Mars à Mai)</label>',
										'</div>',
										'<div class="inputRow">',
											'<input type="radio" id="summer" name="tripSeason" value="2" />',
											'<label for="summer">Eté (Juin à Août)</label>',
										'</div>',
										'<div class="inputRow">',
											'<input type="radio" id="autumn" name="tripSeason" value="3" />',
											'<label for="autumn">Automne (Septembre à Novembre)</label>',
										'</div>',
									'</fieldset>',
									'<fieldset class="tripDescription" id="tripDescription">',
										'<div class="section">',
											'<label for="tripType" class="heading">Quel genre de voyage est-ce?</label>',
											'<div class="col first">',
												'<div class="inputGroup">',
													'<input type="checkbox" id="id_couple" name="tripType" value="couple" />',
													'<label for="id_couple">Couple</label>',
												'</div>',
												'<div class="inputGroup">',
													'<input type="checkbox" id="id_family" name="tripType" value="family" />',
													'<label for="id_family">Séjour en famille</label>',
												'</div>',
												'<div class="inputGroup">',
													'<input type="checkbox" id="id_group" name="tripType" value="group" />',
													'<label for="id_group">Group</label>',
												'</div>',
												'<div class="inputGroup">',
													'<input type="checkbox" id="id_activity" name="tripType" value="activity" />',
													'<label for="id_activity">Activités et Aventure</label>',
												'</div>',
												'<div class="inputGroup">',
													'<input type="checkbox" id="id_history" name="tripType" value="history"/>',
													'<label for="id_history">Histoire et culture</label>',
												'</div>',
											'</div>',
											'<div class="col">',
												'<div class="inputGroup">',
													'<input type="checkbox" id="id_touring" name="tripType" value="touring" />',
													'<label for="id_touring">Touring - self drive or escorted</label>',
												'</div>',
												'<div class="inputGroup">',
													'<input type="checkbox" id="id_relax" name="tripType" value="relax" />',
													'<label for="id_relax">Relax & Recharge</label>',
												'</div>',
												'<div class="inputGroup">',
													'<input type="checkbox" id="id_city" name="tripType" value="city" />',
													'<label for="id_city">Court séjour en ville</label>',
												'</div>',
												'<div class="inputGroup">',
													'<input type="checkbox" id="id_stay" name="tripType" value="stay" />',
													'<label for="id_stay">Stay</label>',
												'</div>',
												'<div class="inputGroup">',
													'<input type="checkbox" id="id_other" name="tripType" value="other" />',
													'<label for="id_other">Autre</label>',
												'</div>',
											'</div>',
										'</div>',
										'<label for="description" class="heading">Description du projet de voyage (<span id="summaryCharCount">300</span> nombre de caractères restants).</span></label>',
										'<textarea id="description" value="Ecrire un bref résumé du projet de voyage">',
											'Ecrire un bref résumé du projet de voyage',
										'</textarea>',
									'</fieldset>',
								'</div>',
								'<input type="image" class="button" id="shareTrip" src="/shared/resource/images/itinerary_planner/fr/buttons/make-public.png" alt="Inspirez d&#39;autres personnes en rendez votre projet accessible à tous sur Irlande-tourisme.fr" />',
							'</form>',
                        '</div>',
                    '</div>',
                '</div>'
			].join('')),

	sharedUsers:	$([
						'<fieldset id="sharedUsers" class="first">',
							'<h3 class="heading">Ce projet de voyage est désormais sauvegardé et partagé avec</h3>',
							'<div id="sharedUsersList">',
							'</div>',
						'</fieldset>'
					].join('')),

/*    sharedConfirm: $(["<div id='swapableContent'>",
                      '<h2>Your trip has been shared</h2>',
                      '<p>Bob  will receive a message about this trip',
                      "</div>"
                     ].join('')), */

    init: function() {
        // Set pop up button event
/*		if($.ti.tripData.trip.tripUsers) {
			$('#shareTripSubmit').unbind('click.notLoggedIn').unbind('click.loggedIn')
				.bind('click.loggedIn', function(){
					$.ti.popup.init({
						content: $.ti.share.html,
						callback: $.ti.share.events,
						width: "600px"
					});
				// Create tabs
				$.ti.share.setTabs(0);
				$.ti.share.setFriendsEmail();
			});
		} else {
			$('#shareTripSubmit').unbind('click.notLoggedIn').unbind('click.loggedIn')
				.bind('click.notLoggedIn', function(){
					$.ti.login.openDialogue();
					$.ti.login.afterLogin = function() {
						$.ti.popup.swapContent($.ti.share.html, "600px", function(){
							$.ti.share.setTabs(0);
							$.ti.share.setFriendsEmail();
						});
					};
			});

		}*/

        $('#shareTripSubmit').click(function() {

            var afterSuccess = function() {
                var tabidx = 0;
                // If the user is a reviewer only the comments tabl should be visible...
                if ($.ti.tripData.trip.role === 'R')
                    tabidx = 1;


                $.ti.share.setTabs(tabidx);
                    $.ti.share.setFriendsEmail();

                $.ti.share.events();
            };

            if (!($.ti.tripData.trip.login))
            {
                $.ti.login.openDialogue();
                $.ti.login.afterLogin = function() {
                    $.ti.popup.swapContent($.ti.share.html, "600px", afterSuccess);
                }
            }
            else
            {
                $.ti.popup.init({
                    content: $.ti.share.html,
                    callback: afterSuccess,
                    width: "600px"
                });
            }

            if ($.browser.msie && $.browser.version.substr(0,1)<7) {
            	$('span#close').pngFix();
    		}

        });
    },



	setTabs: function(tab) {
		$('#shareTabs', $.ti.share.html).tabs({
			fx:{
				opacity: 'toggle',
				height: 'toggle'
			},
			selected: tab
		});
	},

	// Add email address if entered in share input
	setFriendsEmail: function() {
		var friendsAddress = $('#shareTripInput').val();
		if(friendsAddress.match(/[^\d\s]/)) {
			$('#friendsEmail').val($('#shareTripInput').val());
		}
	},

    events: function() {
        // reviewers should only see the comments tab...
        // alert('role is' + $.ti.tripData.trip.role);
        if (typeof($.ti.tripData.trip.role !== 'undefined') && $.ti.tripData.trip.role === 'R'){
            $('#shareTabs').addClass('reviewer');
        }

        if (typeof($.ti.tripData.trip.role !== 'undefined') && $.ti.tripData.trip.role !== 'R'){
        //	alert('called');
            $('#shareTripSubmit').attr('src', '/shared/resource/images/itinerary_planner/fr/buttons/share-trip.png');
        }





		// Set up Inspire tab
		$.ti.share.inspireData();

		// Set inspire cities list
		$.ti.share.setCities();

		// Set categories
		$.ti.share.setCategories();

		// Update existing trip users
		$.ti.share.updateFriends();

		// Comments tab
		$.ti.share.setCommentsCount();

		// Share tab
		$.ti.share.setFriendsCount();

		// Populate comments
		if($.ti.tripData.trip.tripComments) {
			$.ti.share.populateComments();
		}

		// Set public/private text indicator
		if($.ti.tripData.trip.tripPublic === true) {
			$('#tripPublicStatus').text('Votre projet de voyage est désormais accessible à tous sur Irlande-tourisme.fr - Merci!');
		} else {
			$('#tripPublicStatus').text('Votre voyage n&#39;est pas accessible à tous sur Irlande-tourisme.fr ');
		}

		$('#publicTripName').bind({
			blur: function(){
					$.ti.tripData.trip.tripName = $('#publicTripName').val();
					$.ti.panelContent.setTripName();
				}
		});

		if($.ti.tripData.trip.tripDescription) {
			$('#description').val($.ti.tripData.trip.tripDescription);
		}

		$('#tripDescription').bind({
			keydown: function(event){return $.ti.utils.checkLimit(event, this, 300);},
			keyup: function(){$('#summaryCharCount').text(300 - $(this).val().length);}
		});

		$('#commentText').bind({
			keydown: function(event){return $.ti.utils.checkLimit(event, this, 300);},
			keyup: function(){$('#charCount').text(300 - $(this).val().length);}
		});

		// Add comment submit events
		$('#addComment').unbind('click.submitComment');
		$('#addComment').bind('click.submitComment', function(event){
			event.preventDefault();
			$.ti.validate.check('#submitComment', {
				rules: {
					commentText: {
						"required"	: "le champs est obligatoire",
						"maxLength" : ["300", "Comment cannot be longer than 300 characters"]
					}
				},
				success: $.ti.share.submitComment,
				failure: $.ti.login.throwError
			});
		});

		// Add friend submit events
		$('#addFriend').unbind('click.addfriend');
		$('#addFriend').bind('click.addfriend', function(event){
			event.preventDefault();
			$.ti.validate.check('#addFriends', {
				rules: {
					friendsEmail: {
						required: "le champs est obligatoire",
						cannotBe: [$.ti.tripData.trip.tripUsers.user[0].email, "Désolé, vous ne pouvez pas partager votre projet avec vous-même"],
						email: "Merci de saisir une adresse email valide"
					}
				},
				success: $.ti.share.submitAddFriend
			});
		});



		// Share trip submit events
		$('#shareTrip').click(function(event) {
			event.preventDefault();
			$.ti.validate.check('#makeTripPublic', {
				rules: {
					description: {
						required: "Merci d&#39;entrer une brève description de votre projet "
					}
				},
				success: $.ti.share.submitPublic,
				failure: function(){}
			});
		});

        $('#yourMessage').unbind('focus');
        $('#yourMessage').unbind('blur');

        $('#yourMessage').bind({
            focus: function(event) { return false; },
            blur: function(event) { return false; }
        });


        $('#commentText').unbind('focus');
        $('#commentText').unbind('blur');

        $('#commentText').bind({
            focus: function(event) { return false; },
            blur: function(event) { return false; }
        });
    },

	submitPublic: function() {
		var tripCategories = {
				category: []
			};

		// Set public
		$.ti.tripData.trip.tripPublic = true;

		// Set season
		$.ti.tripData.trip.tripSeason = $('input[name=tripSeason]', '#makeTripPublic').val();

		// Set categories
		$('input[name=tripType][checked]', '#tripDescription').each(function(index){
			tripCategories.category[index] = {tripCategory: this.value};
		});
		if(tripCategories.category.length > 0) {
			$.ti.tripData.trip.tripCategories = tripCategories;
		}

		// Set description
		$.ti.tripData.trip.tripDescription = $('#description').val();

		// Set Name
		$.ti.tripData.trip.tripName = $('#publicTripName').val();

		// Send trip
		$.ti.ajax.postData('/fr/trip/?tripId=' + $.ti.tripData.trip.id, $.ti.tripData, $.ti.share.updatePublic);

	},

	updatePublic: function(response) {
		if(response !== 0) {
			$('#tripPublicStatus').html('<span class="shareUpdatedMsg">Votre projet de voyage est désormais accessible à tous sur Irlande-tourisme.fr - Merci!</span>');
		} else {
			// ToDo - need to represent this to user
			$.ti.console.log('server error');
		}
	},

	setFriendsCount: function() {
		var friendsCount = 0;
		if($.ti.tripData.trip.tripUsers) {
			if($.ti.tripData.trip.tripUsers.user.length > 1) {
				friendsCount = ($.ti.tripData.trip.tripUsers.user.length -1);
				$('#tabFriendsCount').text(friendsCount);
				$('#friendCount').text(friendsCount);
			}
		}
	},

	// Get the number of comments for the trip and update both the tab and it's content
	setCommentsCount: function() {
		var commentsCount = 0;
		if($.ti.tripData.trip.tripComments) {
			commentsCount = $.ti.tripData.trip.tripComments.comment.length;
		}
		// Set value on the tab
		$('#tabCommentsCount').text(commentsCount);
		// Set value in the intro text inside the tab
		$('#commentCount').text(commentsCount);
	},

	// ToDo - very basic implementation until cities provided is addressed.
	setCities: function() {
		var places = [];
		if($.ti.tripData.trip.tripCities) {
			var cityArray = $.ti.tripData.trip.tripCities.city;
			var tripCityList = $('#tripCities');
			tripCityList.empty();
			for (var i = 0; i < cityArray.length; i++) {
				if (i < 5) {
					tripCityList.append($('<li>' + cityArray[i].tripCity + '</li>'));
				} else {
					tripCityList.append($('<li>...</li>'));
					i = cityArray.length;
				}
			}
			//places = $.ti.tripData.trip.tripCities.split(',');
			//$('#tripCities').append($('<li>' + (index < count -1? '':' and ') + '' + places[index] + '' + (index < count -1? ' ':'.') + '</li>'));
		}
	},

	setCategories: function() {
		if($.ti.tripData.trip.tripCategories) {
			for(var category in $.ti.tripData.trip.tripCategories.category) {
				if($.ti.tripData.trip.tripCategories.category.hasOwnProperty(category)) {
					$('input[value=' + $.ti.tripData.trip.tripCategories.category[category].tripCategory + ']', '#tripDescription').attr('checked', true);
				}

			}
		}
	},

	inspireData: function() {
		// Set trip name
		document.getElementById('publicTripName').defaultValue = $.ti.tripData.trip.tripName;
		document.getElementById('publicTripName').value = $.ti.tripData.trip.tripName;
		// Set input clearing
		$('#makeTripPublic').tiClearInputs();
		if($.ti.tripData.trip.tripStartDate) {
			this.selectSeason();
		}
	},

	// Set the season radio. ToDo - may need some more love once date picker finalised.
	// 0 = winter, 1 = spring, 2 = summer, 3 = autumn, 4 = all year round
	selectSeason: function() {
		var seasons = {
			date: $.ti.tripData.trip.tripStartDate.split('-'),
			season: 0,
			radios: $('input[name=tripSeason]', '#inspire')
		};

		// If season already chosen use that
		if($.ti.tripData.trip.tripSeason) {
			seasons.season = $.ti.tripData.trip.tripSeason;
		} else {
			// Otherwise take the start date and calculate on that
			seasons.season = (Math.floor(seasons.date[1] / 3));
			if(seasons.season === 4) {
				seasons.season = 0;
			}
		}
		seasons.radios[seasons.season].click();
	},

	submitAddFriend: function() {
		var tripUsers = {
			user: {
				email: $('#friendsEmail').val(),
				role: $('input[name=permissions]:checked', '#addFriends').val(),
				emailMessage: $('#yourMessage').val()
			}
		};

		// Reset inputs
		$.ti.utils.resetFields(['#friendsEmail', '#yourMessage']);
		// Add user data to trip
		$.ti.tripData.trip.tripUsers.user.push(tripUsers.user);

        if ($('#ccOwner').is(':checked'))
            tripUsers.user.ccOwner = true;

		dcsMultiTrack (
			'DCS.dcsuri',					document.location.pathname + 'trip_planner/shared_trip',
			'WT.ti',						'Trip Planner - Shared Trip',
			'WT.cg_n',						section,
			'WT.cg_s',						subSection,
			'DCSext.trip_planner_action',	'shared_trip'
			);


		// Submit user data
		$.ti.ajax.postData('/fr/trip/', tripUsers,
                           function() {
								//$.ti.messages.tripShared(tripUsers.user.email);
							   //alert('called-submit ajax post');
                               $.ti.share.updateFriends();
                               $.ti.console.log('Email friend update posted');
                           });
        $.ti.popup.swapContent($.ti.share.generateConfirmedMessage(tripUsers.user.email), '360px', function() {});
	},



    generateConfirmedMessage: function(emailAddr) {
        return $(["<div id='swapableContent'>",
                  '<h2>Vous avez partagé votre projet avec vos amis</h2>',
                  '<p>' + emailAddr + ' recevra un message au sujet de ce voyage',
                  "</div>"
                 ].join(''));
    },

	updateFriends: function() {
		var copy, count, userHTML, userCount, updateButton;

		// Check for users (other than trip owner)
		if($.ti.tripData.trip.tripUsers && $.ti.tripData.trip.tripUsers.user.length > 0) {

			// Clear the column
			$('#manageFriends').empty();
			copy = $($.ti.share.sharedUsers).clone();
			$('#manageFriends').append(copy);

            var updateButtonDisplay = 1;
			userCount = $.ti.tripData.trip.tripUsers.user.length -1;
			for(count = userCount; count >= 0; count -= 1) {
            	//alert('count is:' + count);
                //alert('user count is:' + userCount);
				// Generate HTML for each user
				if($.ti.tripData.trip.tripUsers.user[count].role !== "O") {
					userHTML =
								$([
									'<div class="section" id="trip-user-' + count + '">',
										'<label class="friend" for="user-' + count + '">' + $.ti.tripData.trip.tripUsers.user[count].email + '</label>',
										'<label for="reviewer-' + count + '">',
											'<input class="radio" type="radio" id="reviewer-' + count + '" name="user-' + count + '" value="R" />',
										'lecture seule</label>',
										'<label for="contributer-' + count + '">',
											'<input class="radio" type="radio" id="contributer-' + count + '" name="user-' + count + '" value="C" />',
										'Lire &amp; Contribuer</label>',
										'<label for="remove-' + count + '">',
											'<input class="radio" type="radio" id="remove-' + count + '" name="user-' + count + '"  value="X" />',
										'Supprimer</label>',
									'</div>'
								].join(''));

					$('#sharedUsersList').append(userHTML);

					// Select status of user
					switch($.ti.tripData.trip.tripUsers.user[count].role) {
						case "R":	$('#reviewer-' + count).attr("checked", "checked");
									break;
						case "C":	$('#contributer-' + count, userHTML).attr("checked","checked");
									break;
					}

					// Append update button and add submit event
					//if(count === 1) {
                    if(updateButtonDisplay){
                    	updateButtonDisplay = 0;
                    	//alert('called!');
						updateButton = $('<div class="input-wrap"><input type="image" class="button" id="update" src="/shared/resource/images/itinerary_planner/fr/buttons/update.png" alt="Mettre à jour" /></div>');
						$(updateButton).click(function(event){
							event.preventDefault();
							$.ti.share.submitUpdate();
						});
                        //alert('called');
						$('#manageFriends').append(updateButton);
					}

                    //}
				}
			}
		}
	},

	submitUpdate: function() {

		var tripUsers, users, userCount, count, newRole, userNumber, hasUpdates;

		tripUsers = {
			list: {
				user: []
			}
		};

		users = $('.section', '#sharedUsersList');
		userCount = users.length;

		hasUpdates = false;
		$.ti.console.log('update called');
		for(count = 0; count < userCount; count += 1) {

			userNumber = parseInt(users[count].id.match(/\d/g), 10);
			newRole = $('input[type=radio]:checked', users[count]).val();

			if($.ti.tripData.trip.tripUsers.user[userNumber].role !== newRole) {
				tripUsers.list.user.push({
					email: $('.friend', users[count]).text(),
					role: newRole
				});
				if( newRole == 'X' ){
					$.ti.tripData.trip.tripUsers.user.splice(userNumber, 1);
					$('#trip-user-' + userNumber).remove();
				}else{
					$.ti.tripData.trip.tripUsers.user[userNumber].role = newRole;
				}
				hasUpdates = true;
			}

		}
		tripUsers = $.toJSON(tripUsers);
		tripUsers = $.evalJSON(tripUsers);
		if(hasUpdates) {
        	$.ti.console.log('ajax call started');
        	$.ti.ajax.postData('/fr/trip/', tripUsers, $.ti.share.confirmUpdates);
            $.ti.console.log('ajax call ended');
			$.ti.popup.swapContent('<h2>Mise à jour réussie</h2><p>Vous avez mis à jour les amis de ce voyage a été partagé avec</p>', '360px', function() {});

    	}
        else{
        alert('Please make some changes to the trip sharing options before pressing the update button.');
        }
	},

	confirmUpdates: function() {
		$.ti.console.log('users updated... ');

	},

	submitComment: function() {
		var tripComment = {
			comment: {
				comment: $('#commentText').val(),
				userId: $.ti.tripData.trip.login.id,
				username: $.ti.tripData.trip.login.username
			}
		};

		$.ti.ajax.postData('/fr/trip/', tripComment, $.ti.share.updateComment);
	},

	updateComment: function(response) {
		if(response !== 0) {
			$.ti.share.showComment(response.comment);

			if(!$.ti.tripData.trip.tripComments) {
				// Add TipComments node
				$.ti.tripData.trip.tripComments = {};
				// Adding the silly extra layer - one day back end might fix all these.
				$.ti.tripData.trip.tripComments.comment = [];
			}
			// Push comment into comments array
			$.ti.tripData.trip.tripComments.comment.push(response.comment);
			$.ti.share.setCommentsCount();
			$.ti.panelContent.setShareCommentsOverview();
			$.ti.utils.resetFields(['#commentText']);
			$('#charCount').text(300);
		}
	},

	populateComments: function() {
		// Clear out the panel first
		$('#commentList').empty();

		// Loop through comments and add to panel.
		for(var comment in $.ti.tripData.trip.tripComments.comment) {
			if($.ti.tripData.trip.tripComments.comment.hasOwnProperty(comment)) {
				this.showComment($.ti.tripData.trip.tripComments.comment[comment]);
			}
		}
	},

	showComment: function(comment) {

		// manipulate the date for display purposes

		var commentDate = new Date();
		var commentDateSeparation = (comment.commentDate.split(' ')[0]).split('-');
		var commentTime = comment.commentDate.split(' ')[1];
		var commentDateString = (commentDateSeparation[2] + ' ' + $.ti.pickDates.monthNames[(commentDateSeparation[1])-1] + ' ' + commentDateSeparation[0] + ', ' + commentTime);

		var commentHTML =	$([ '<li>',
									'<p class="name">' + comment.username + '</p>',
									'<p class="date">' + commentDateString  + '</p>',
									'<p class="comment">' + comment.comment + '</p>',
								'</li>'
							].join(''));
		$(commentHTML).hide();
		$('#commentList').prepend($(commentHTML));
		$(commentHTML).show(500);
	}
};
})(jQuery);
