

















(function($) {
$.ti.share = $.prototype = {

    html:   $([
				'<div id="swapableContent">',
                    '<h2><img src="/shared/resource/images/itinerary_planner/au/text/share-trip.png" height="28" alt="Save and share your Trip Planner" /></h2>',
                    '<p></p>',
                    '<div id="shareTabs">',
                        '<ul class="tabs">',
                            '<li id="manageTrigger"><a href="#manage">Manage your friends&#039; access to your Trip (<span id="tabFriendsCount">0</span>)</a></li>',
                            '<li id="commentsTrigger"><a href="#comments">Comments (<span id="tabCommentsCount">0</span>)</a></li>',
                            '<li id="inspireTrigger"><a href="#inspire">Save and Inspire others</a></li>',
                        '</ul>',
                        '<div id="manage" class="tab">',
							'<p class="intro">Like how your trip to the island of Ireland came together on your Trip Planner? Just save and inspire others by letting us post your Trip on Discover Ireland.</p>',
							'<p class="intro">You have shared your Trip with ',
								'<em><span id="friendCount">0</span></em>',
								' Friends </p>',
							'<div class="wrap">',
								'<form method="" action="" id="manageFriends">',
								'</form>',
								'<form method="" action="" id="addFriends">',
									'<fieldset class="section">',
										'<label class="heading" for="friendsEmail">Save and share this trip with your friends </label>',
										'<input class="text" type="text" id="friendsEmail" value="Your friend&#039;s email address" />',
									'</fieldset>',
									'<fieldset class="section" id="friendStatus">',
										'<label class="heading" for="permssions">What is your friend allowed to do?</label>',
										'<label for="reviewOnly">',
											'<input class="radio" type="radio" id="reviewOnly" value="R" name="permissions" />',
										'Review only</label>',
										'<label for="reviewAndContribute">',
											'<input class="radio" type="radio" id="reviewAndContribute" value="C" name="permissions" checked="" />',
										'Review and contribute</label>',
									'</fieldset>',
									'<fieldset>',
										'<label class="heading">Your message</label>',
										'<textarea id="yourMessage" class="clearfix" rows="5">',
											'Hi there, I&#039;ve created this Trip on Discover Ireland (www.discoverireland.com) and I&#039;d like to see what you think. Thanks!',
										'</textarea>',
                                        '<label for="ccOwner">',
                                            '<input type="checkbox" id="ccOwner" />',
                                            ' send a copy to me',
                                        '</label>',
									'</fieldset>',
									'<div class="input-wrap">',
                                       '<input type="image" class="button" id="addFriend" src="/shared/resource/images/itinerary_planner/au/buttons/share-this-trip.png" height="22" alt="Save and share this trip with your friends " />',
									'</div>',
								'</form>',
							'</div>',
                        '</div>',
                        '<div id="comments" class="tab">',
                            '<p class="intro">Hi there, I&#039;ve taken a look at your Trip on Discover Ireland (www.discoverireland.com) and have made the following comments. Thanks!</p>',
                            '<p class="intro">Here are all the comments that have been added to your Trip on Discover Ireland<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">Please add a comment.<br>(<span id="charCount">300</span> characters remaining)</span></label>',
										'<textarea id="commentText" rows="10">',
											'Please add a comment to this Trip on Discover Ireland',
										'</textarea>',
										'<p>Now you&#039;ve saved your trip, allow friends to review, comment and even contribute! You, as Trip Owner, can managed your friends access types here</p>',
									'</fieldset>',
								'</div>',
								'<input type="image" class="button" id="addComment" src="/shared/resource/images/itinerary_planner/au/buttons/add-comment.png" alt="Please add a comment to this Trip on Discover Ireland" />',
							'</form>',
                        '</div>',
                        '<div id="inspire" class="tab">',
                            '<p class="intro">Like how your Trip to the island of Ireland came together on your Trip Planner? Just name it, save it and then inspire others by letting us post your Trip on Discover Ireland.</p>',
							'<p class="intro" id="tripPublicStatus">Your Trip is not accessible to others on Discover Ireland</p>',
							'<form id="makeTripPublic" method="" action="">',
								'<div class="wrap">',
									'<fieldset class="tripDetails first">',
										'<div class="section">',
											'<label for="publicTripName" class="heading">My Trip name</label>',
											'<input id="publicTripName" type="text" value="" class="text"/>',
										'</div>',
										'<div class="section">',
											'<h4 class="heading">Where are you going?</h4>',
											'<ul id="tripCities">',
												'<li>Ireland</li>',
											'</ul>',
										'</div>',
										'<label for="tripSeason" class="heading">During which season?</label>',
										'<div class="inputRow">',
											'<input type="radio" id="winter" name="tripSeason" value="0" checked="checked" />',
											'<label for="winter">Winter (December to February)</label>',
										'</div>',
										'<div class="inputRow">',
											'<input type="radio" id="spring" name="tripSeason" value="1" />',
											'<label for="spring">Spring (March to May)</label>',
										'</div>',
										'<div class="inputRow">',
											'<input type="radio" id="summer" name="tripSeason" value="2" />',
											'<label for="summer">Summer (June to August)</label>',
										'</div>',
										'<div class="inputRow">',
											'<input type="radio" id="autumn" name="tripSeason" value="3" />',
											'<label for="autumn">Autumn (September to November)</label>',
										'</div>',
									'</fieldset>',
									'<fieldset class="tripDescription" id="tripDescription">',
										'<div class="section">',
											'<label for="tripType" class="heading">What kind of trip is it?</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">Family</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">Activity & Adventure</label>',
												'</div>',
												'<div class="inputGroup">',
													'<input type="checkbox" id="id_history" name="tripType" value="history"/>',
													'<label for="id_history">History, Culture & Gardens</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">City</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">Let my Trip do the talking</label>',
												'</div>',
											'</div>',
										'</div>',
										'<label for="description" class="heading">Trip description (<span id="summaryCharCount">300</span> characters remaining).</span></label>',
										'<textarea id="description" value="Write a short summary of your Trip">',
											'Write a short summary of your Trip',
										'</textarea>',
									'</fieldset>',
								'</div>',
								'<input type="image" class="button" id="shareTrip" src="/shared/resource/images/itinerary_planner/au/buttons/make-public.png" alt="Inspire others and make your Trip accessible to others on Discover Ireland" />',
							'</form>',
                        '</div>',
                    '</div>',
                '</div>'
			].join('')),

	sharedUsers:	$([
						'<fieldset id="sharedUsers" class="first">',
							'<h3 class="heading">This trip has been saved and shared with</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/au/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('Your Trip is now accessible to others on Discover Ireland - thank you! ');
		} else {
			$('#tripPublicStatus').text('Your Trip is not accessible to others on Discover Ireland');
		}

		$('#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"	: "This field is required",
						"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: "This field is required",
						cannotBe: [$.ti.tripData.trip.tripUsers.user[0].email, "Sorry, you cannot Share your Trip with yourself"],
						email: "Please enter a valid email address"
					}
				},
				success: $.ti.share.submitAddFriend
			});
		});



		// Share trip submit events
		$('#shareTrip').click(function(event) {
			event.preventDefault();
			$.ti.validate.check('#makeTripPublic', {
				rules: {
					description: {
						required: "Please enter a short Trip description"
					}
				},
				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('/au/trip/?tripId=' + $.ti.tripData.trip.id, $.ti.tripData, $.ti.share.updatePublic);

	},

	updatePublic: function(response) {
		if(response !== 0) {
			$('#tripPublicStatus').html('<span class="shareUpdatedMsg">Your Trip is now accessible to others on Discover Ireland - thank you! </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('/au/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>Your trip has been shared with friends</h2>',
                  '<p>' + emailAddr + ' will receive a message about this trip',
                  "</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" />',
										'Read only</label>',
										'<label for="contributer-' + count + '">',
											'<input class="radio" type="radio" id="contributer-' + count + '" name="user-' + count + '" value="C" />',
										'Read &amp; Contribute</label>',
										'<label for="remove-' + count + '">',
											'<input class="radio" type="radio" id="remove-' + count + '" name="user-' + count + '"  value="X" />',
										'Remove</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/au/buttons/update.png" alt="Update" /></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('/au/trip/', tripUsers, $.ti.share.confirmUpdates);
            $.ti.console.log('ajax call ended');
			$.ti.popup.swapContent('<h2>Update successful</h2><p>You have successfully updated the friends this trip has been shared with</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('/au/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);
