

















/*
* Nag user panel
*
*/
(function($) {
$.ti.bag = {

	lock: false,

	unopened: true,

	tempActivityId: -1,

	// Constants that we expect from the bag are stored here for reference.
	// If for example we change the display of the bag from 4 items per view we should update here
	constants: {
		view: 4,		// How many activities can be seen in a view state of the bag.
		height: 224,	// Height in pixels of the bag clipping area
		itemHeight: 56,	// Height of item within bag (a single <li>)
		speed: 500		// Bag animation speed
	},

	properties: {
		firstItem: 0,
		lastItem: 0,
		listLength: 0
	},

    init: function() {
		this.setData();
		this.events();
	},

	// Set length of activity list
	getListLength: function() {
		this.properties.listLength = $('li', '#theBag').not('.empty').length;
       // console.log 'list length is' + this.properties.listLength;
	},

	// Set the initial bag data
	setData: function() {
		this.getListLength();
		if(this.properties.listLength > 0) {
			// If we have items then first item becomes 1 not 0
			this.properties.firstItem = 1;

			var lastItem = ((this.properties.firstItem -1) + this.properties.listLength);

			// Check that last item is within the view, if not reduce to that number
			if((lastItem - this.properties.firstItem) > (this.constants.view -1)) {
				lastItem = (this.properties.firstItem -1) + this.constants.view;
			}

			// Set last item value
			this.properties.lastItem = lastItem;
		} else {
			this.properties.firstItem = 0;
			this.properties.lastItem = 0;
		}
		// Store the data
		$('#theBag').data('properties', this.properties);
		$.ti.bag.setStatus();
	},

	// Update status when we add/remove or scroll.
	updateData: function(newitem) {
		// Scroll the bag to top if it is a newly added item
		newitem = newitem || false;

		this.getListLength();
		if(this.properties.listLength > 0) {

			if(newitem && this.properties.firstItem !== 1) {
				// Full scroll of content
				if(($.ti.bag.properties.lastItem + $.ti.bag.constants.view) < $.ti.bag.properties.listLength) {
					$.ti.bag.scroll(+1, $.ti.bag.constants.height, ($.ti.bag.properties.firstItem -1));
				} else if (this.properties.firstItem > 0) {
					// Reduced scroll for when we are near the top of the bag
					var distance = (($.ti.bag.properties.firstItem -1) * $.ti.bag.constants.itemHeight);
					$.ti.bag.scroll(+1, distance, ($.ti.bag.properties.firstItem -1));
				}

				this.properties.firstItem = 1;
			}

			var lastItem = ((this.properties.firstItem -1) + this.properties.listLength);

			// Check that last item is within the view, if not reduce to that number
			if((lastItem - this.properties.firstItem) > (this.constants.view -1)) {
				lastItem = (this.properties.firstItem -1) + this.constants.view;
			}

			// Set last item value
			this.properties.lastItem = lastItem;

		} else {
			this.properties.firstItem = 0;
			this.properties.lastItem = 0;
		}

		// Store the data
		$('#theBag').data('properties', this.properties);

		// Update the bag indicators and nav
		$.ti.bag.setStatus();
	},

	setStatus: function() {
		var status = {
			view: $('<span></span>'),
			total: $('<span></span>')
		};

		$(status.total).append(this.properties.listLength);

		// Set view count
		if(this.properties.firstItem === this.properties.lastItem) {
			$(status.view).append(this.properties.firstItem);
		} else {
			$(status.view).append(this.properties.firstItem)
				.append(' - ')
				.append(this.properties.lastItem);
		}

		$('#bagStatus').empty()
			.append(status.view)
			.append(' de ')
			.append(status.total);

		$.ti.bag.setNav();
	},

	// Enable or disable the bag navigation buttons
	setNav: function() {
		// Disable top button if first item at top
		$('#bagUp').toggleClass('disabled', (this.properties.firstItem <= 1));
		// Disable bottom button if lastItem matches list length.
		$('#bagDown').toggleClass('disabled', (this.properties.lastItem === this.properties.listLength));
	},

	events: function() {
		// Show detail event
		$('span.showDetails', '#theBag').live('click', function() {
			$.ti.bag.showDetails($(this).closest('li'));
		});

		// Close details event
		$('span.close-detail', '#activityDetail').live('click', function() {
			$('#overlay').remove();
			$('#activityDetail').remove();
		});

		// Bag up event
		// Actually moves the bag down but your view moves up.
		$('#bagUp').bind('click.moveBag', function() {
			if($.ti.bag.lock === false) {
				// Prevent double scrolls
				$.ti.bag.lock = true;
				// Full scroll of content
				if(($.ti.bag.properties.firstItem - $.ti.bag.constants.view) > 1) {
					$.ti.bag.scroll(+1, $.ti.bag.constants.height, $.ti.bag.constants.view);
				} else {
					// Reduced scroll for when we are near the top of the bag
					var distance = (($.ti.bag.properties.firstItem -1) * $.ti.bag.constants.itemHeight);
					$.ti.bag.scroll(+1, distance, ($.ti.bag.properties.firstItem -1));
				}
			}
		});

		// Bag down event
		// Actually moves the bag up - but your view moves down
		$('#bagDown').bind('click.moveBag', function() {
			var difference, distance;

			if($.ti.bag.lock === false) {
				// Prevent double scrolls
				$.ti.bag.lock = true;
				// Full scroll
				if(($.ti.bag.properties.lastItem + $.ti.bag.constants.view) < $.ti.bag.properties.listLength) {
					$.ti.bag.scroll(-1, $.ti.bag.constants.height, $.ti.bag.constants.view);
				} else {
					// Reduced scroll for when we are near the bottom of the bag
					difference = ($.ti.bag.properties.listLength - $.ti.bag.properties.lastItem);
					distance = (difference * $.ti.bag.constants.itemHeight);
					$.ti.bag.scroll(-1, distance, difference);
				}
			}
		});
	},


	// Bag scroller/carousel type behaviour
	// operator: either +1 or -1 to assign positive or negative direction i.e. if distance = 100, -1 will convert that to -100px
	// distance: scroll distance, usually the bag constant height
	// updateBy: the number of items we have scrolled, again usually the bag constant view, also modified by the operator
	scroll: function(operator, distance, updateBy) {
		// Apply the operator to distance and update by to create either positive or negative numbers.
		distance = distance*operator;
		updateBy = updateBy*operator;

		// Carry out the animation and unlock the "carousel" on completion
		$('#theBag').animate({
			'top': '+=' + distance + 'px'
		}, $.ti.bag.constants.speed, function(){
				$.ti.bag.lock = false;
			}
		);

		// Update bag data and status.
		$.ti.bag.properties.firstItem -= updateBy;
		$.ti.bag.properties.lastItem -= updateBy;
		$.ti.bag.setStatus();
	},

	// Clear out the bag and fill it with empties
	reset: function() {
        var html = $(['<li class="empty"></li>',
					  '<li class="empty"></li>',
					  '<li class="empty"></li>',
					  '<li class="empty"></li>'
					].join(''));

		// Reset properties
		$.ti.bag.properties = {
			firstItem: 0,
			lastItem: 0,
			listLength: 0
		}

        $('#theBag').empty()
                    .append(html)
					.css({'top': '0px'});
		$.ti.bag.setStatus();
    },

	// Fill bag with trip activities
    // Accepts "category" as optional value to display only matching activites
    fill: function(category) {
        $.ti.cookie.setCookie('ItineraryPlanner', $.ti.tripData.trip.id);
        if($.ti.tripData.trip.tripActivities) {
            $($.ti.tripData.trip.tripActivities.activity).each(function(){

                if(category) {
                    if(this.actCategory === category) {
                        $.ti.bag.add(this, false);
                    }
                } else {
                    $.ti.bag.add(this, false);
                }
            });
        }


        if ($.ti.tripData.trip.showOnLoad)
        {
            $('#panelToggler').click();
        }
    },

	// Handles the delte item event
	deleteControler: function(event) {
		var listItem, node;

		event.stopPropagation();

		// Get list item that we are deleting
		listItem = $(event.target).closest('li');

		if($(listItem).data('data').actRowColumnDays) {
			$.ti.messages.deleteFromCalender(listItem);
		} else {
			$.ti.bag.deleteActivity(listItem);
		}
	},

	// Delete an activity from the bag.
	deleteActivity: function(listItem) {
		// If we are deleting the last item in view scroll a step
		if($.ti.bag.properties.lastItem === $.ti.bag.properties.listLength && $.ti.bag.properties.firstItem !== 1) {
			$.ti.bag.scroll(+1, $.ti.bag.constants.itemHeight, 1);
		}

		// If we are deleting the last item and there are not enough to require a scroll add an empty
		if($.ti.bag.properties.lastItem === $.ti.bag.properties.listLength && $.ti.bag.properties.firstItem === 1) {
			$.ti.bag.addEmpties(1);
		}

		$(listItem).slideUp('500', function() {
			$(this).remove();
			$.ti.bag.updateData();
		});

		// Check for calender entries
		if($(listItem).data('data').actRowColumnDays) {
			$.ti.bag.deleteCalenderActivities($(listItem).data('data').actRowColumnDays);
		}

		$.ti.bag.deleteActivityData($(listItem).data('data').id);
		$.ti.categories.get();
	},

	// Remove activity references from calender.
	deleteCalenderActivities: function(locations) {
		var count, ids, length;

		ids = locations.split(',');
		length = ids.length;

		for(count = 0; count < length; count += 1) {
			// Trigger delete event on calender activity instance
			$('.dayGridActivityClose', '#' + ids[count].split('_')[0] + 'Activity').click();
		}
	},

	// Remove acticity data from the trip object
	deleteActivityData: function(activityId) {
		var count, total;

		total = $.ti.utils.objectLength($.ti.tripData.trip.tripActivities.activity) - 1;
		if(total === 0) {
			delete $.ti.tripData.trip.tripActivities;
			// Trigger a save as server doesn't always catch this in time on an unload event
			$.ti.ajax.postData('/es/trip/', $.ti.tripData);
		} else {
			for(count = 0; count < total; count += 1) {
				if($.ti.tripData.trip.tripActivities.activity[count].id === activityId) {
					$.ti.tripData.trip.tripActivities.activity.splice(count, 1);
				}
			}
		}
	},

	// Add a required number of empties to the bag
	addEmpties: function(total) {
		var count;
		for(count = 0; count < total; count += 1) {
			$('#theBag').append($('<li class="empty"></li>'));
		}
	},

	showDetails: function(item) {
		// Check for user generated activities
		if (item.data("data").actCategory !== 'User Generated') {

            var datesHtml = '';

            if(item.data("data").actStartDate){
         	 	var startDateArray = item.data("data").actStartDate.split('-');
                var startDateFormatted = $.datepicker.formatDate('d M yy', new Date(startDateArray[0], startDateArray[1] - 1, startDateArray[2]));
            }

            if(item.data("data").actEndDate){
            	var endDateArray = item.data("data").actEndDate.split('-');
     			var endDateFormatted = $.datepicker.formatDate('d M yy', new Date(endDateArray[0], endDateArray[1] - 1, endDateArray[2]));
        	}

            if(startDateFormatted) {
            	datesHtml = '<h4>' + startDateFormatted;
                	if(endDateFormatted){
                  	  datesHtml = datesHtml + ' - ' + endDateFormatted;
                    }
                 datesHtml = datesHtml + '</h4>';
            }

			var html = $(['<div id="activityDetail" style="left:' + Math.round(($(document).width()/2) - 210) + 'px">',
						'<span class="close-detail"></span>',
						'<div class="content ' + item[0].className + '">',
							'<dl id="activityName">',
                   			'<dt>' + item.data("data").actName + '</dt>',
								'<dd>' + item.data("data").actCategory + ', ' + item.data("data").actCity + '</dd>',
							'</dl>',
							'<div class="info">',
								'<img src="' + item.data("data").actImageUrl + '" alt="" width="100" height="100" />',
								'<div class="details">',
                                	datesHtml,
									'<p>' + item.data("data").actDescription + '<a href="' + item.data("data").actUrl + '" title="">Ver más</a></p>',
									'<dl id="contactData">',
									'</dl>',
								'</div>',
							'</div>',
						'</div>',
					'</div>'
					].join(''));

			// Add star ratings if present
			if(item.data("data").actRating) {
				$('#activityName', html).append(this.addRating(item.data("data").actRating));
			}

			// Add telephone if present
			if(item.data("data").actTelephone) {
				$('#contactData', html).append($('<dt>Teléfono:</dt><dd>' + item.data("data").actTelephone + '</dd>'));
			}

			// Add address if present
			if(item.data("data").actAddress) {
				$('#contactData', html).append($('<dt>Dirección:</dt><dd>' + item.data("data").actAddress + '</dd>'));
			}

			// Add website link if present
			if(item.data("data").actOperatorUrl) {
				$('#contactData', html).append($('<dt>Página web:</dt><dd><a href="' + item.data("data").actOperatorUrl + '" title="">' + item.data("data").actOperatorUrl +'</a>'));
			}

			// Add booking url if present
			if(item.data("data").actBookingUrl !== "actBookingUrl") {
				$('#contactData', html).append($('<dd><a href="' + item.data("data").actBookingUrl + '" title="">Reserva ahora con -' + item.data("data").actOperator + '</a></dd>'))
			}

			// Add button if it is offer
			if(item.data("data").actIsOffer && item[0].id === 'panelPromo') {
                var buttonHtml = '<input height="22" type="image" width="102" src="" id="addPanelPromoPopup" >';
				var button = $(buttonHtml);
				$('.details', html).append(button);
				button.attr('src', $('#addPanelPromo').attr('src')).click(function() {
					$('#addPanelPromo, #activityDetail span.close-detail').trigger('click');
				});
			}
		} else {
            var shtml = ['<div id="activityDetail" style="left:' + Math.round(($(document).width()/2) - 210) + 'px">',
						'<span class="close-detail"></span>',
						'<div class="content ' + item[0].className + '">',
							'<div class="info">',
								'<textarea id="addYourOwnContent">' + item.data("data").actName + '</textarea>',
                               //'<p><a href="' + item.data("data").actUrl + '" title="">Ver más</a></p>'
                         ].join('');


            var link = item.data('data').actUrl;
            if (link)
            {
               shtml += '<a href="' + link + '" target="_blank">view this page</a>';
            }

            shtml += ['</div>',
					  '</div>',
					  '</div>'
					 ].join('');

            var html = $(shtml);
		}

		// Append overlay
		$.ti.popup.overlay();

		// Append detail popup
		$(document.body).prepend(html);

		// Update user generated activity content
		if (item.data("data").actCategory === 'User Generated') {
			$('span.close-detail', '#activityDetail').click(function() {
				var addYourOwnContent = $('#addYourOwnContent').val();
				var duration = $.ti.utils.getDuration(item.data("data").actRowColumnDays);
				if (item.data("data").actName !== addYourOwnContent) {
					item.data("data").actName = addYourOwnContent;
					addYourOwnContent = $.ti.utils.mixCase(addYourOwnContent);
					addYourOwnContent = $.ti.utils.truncate(addYourOwnContent, ($.ti.createTripCalendar.dayCharacterLimit*duration));
					$('h6.activityHeading', '#'+item.data("data").id).html(addYourOwnContent);
					$('h6.activityHeading', '#'+item.data("data").actRowColumnDays.substring(0,4)).html(addYourOwnContent);
				}
			});
		}
	},

	// Add star ratings to item detail panel.
	addRating: function(rating) {
		var html = $('<dd class="star-rating"><img src="/shared/resource/images/itinerary_planner/icons/star-ratings.png" height="66" alt="' + rating + ' de 5" /></dd>');

		// position backgroun image based on rating - each row of the image is 11px
		$('img', html).css({
			top: '-' + (rating * 11) + 'px'
		});

		return html;
	},


    // This ugliness is so I don't screw up (or have to re-implement) the add method...
    myAdd: function(activityData, newItem, popupCoords)
    {
        var result = this.add(activityData, newItem);

        if (result != false && newItem == true)
            this.addFeedback(activityData.actName, popupCoords);

        // Save the addition - we can;t rely on save occuring on unload...
        //if (newItem)
		//    $.ti.ajax.postData('/es/trip/', $.ti.tripData);
    },

	add: function(activityData, newItem) {
         var activityName, activityString, liHTML, emptyItems;
         // Check that it is unique - ignore user entered activities that will have no product ID
         // Also no need to check if is first item added so check for presence of tripActivities
        if(newItem && activityData.actProductId && $.ti.tripData.trip.tripActivities) {
            if(!$.ti.utils.isUnique($.ti.tripData.trip.tripActivities.activity, activityData, "actProductId")) {
                $.ti.messages.alreadyExists();
                // Do not continue
                return false;
            }

        }


        //Check city exists - if not create empty one to keep the data object happy
        if(!activityData.actCity) {
            activityData.actCity = '';
        }

        // Create temp negative id for activities that don't already have one
        if(activityData.id === 0) {
            activityData.id = this.tempActivityId;
            this.tempActivityId -= 1;
        }

        // Tidy up activity name
        activityName = $.ti.utils.truncate(activityData.actName, 53);
		activityName = $.ti.utils.mixCase(activityName);

        // Convert string to class name suffix
        activityString = $.ti.utils.makeClassName(activityData.actCategory);

		if (newItem) {
			// Checks to see this is not the first item - otherwise we have to create the tripActivities object
			if(!$.ti.tripData.trip.tripActivities) {
				dcsMultiTrack (
					'DCS.dcsuri',					document.location.pathname + 'trip_planner/bag_started',
					'WT.ti',						'Trip Planner - Bag Started',
					'WT.cg_n',						section ,
					'WT.cg_s',						subSection ,
					'DCSext.trip_planner_action',	'bag_started'
					);
			}
			dcsMultiTrack (
				'DCS.dcsuri',					document.location.pathname + 'trip_planner/add_to_bag',
				'WT.ti',						'Trip Planner - Add to Bag - '+activityName,
				'WT.cg_n',						section ,
				'WT.cg_s',						subSection ,
				'DCSext.trip_planner_action',	'item_added_in_bag',
				'DCSext.item_name',				activityName,
				'DCSext.item_category',			activityData.actCategory
				);
		}

        // Create list item
		liHTML = $(['<li class="' + activityString + '">',
						 '<div id="' + activityData.id + '" rel="' + activityData.id + '" class="activity activity' + activityString + '">',
							 '<div class="activityWrapper clearfix">',
								 '<div class="activityContent">',
									 '<span class="category ' + activityString + '"></span>',
									 '<h6 class="activityHeading">' + activityName + '</h6>',
								 '</div>',
							 '</div>	',
						 '</div>	',
					 '</li>'
				 ].join(''));

        // If not reviewer add the delete button
        if($.ti.tripData.trip.role !== 'R') {
            $('.activityContent', liHTML).prepend($('<span class="activityClose"></span>'));
        }

		// Add User generated title if required if not user generated add show details icon
		if(activityData.actCategory === 'User Generated') {
     		$('.activityContent', liHTML).prepend($('<span class="showDetails">Tu Viaje</span>'));
			//$('.activityContent', liHTML).prepend($('<h5>Tu Viaje</h5>'));
			$('.clearfix', liHTML).removeClass('activityWrapper').addClass('activityWrapperUserGenerated');
		} else {
			$('.activityContent', liHTML).prepend($('<span class="showDetails">Información</span>'));
		}

        // Add start and end dates if present for activity
        // ToDo - do we need an id on this div?
        if(activityData.actStartDate || activityData.actEndDate) {
            $('.activityContent', liHTML).append($('<div id="' + activityData.id  + 'Date" class="dateHighlightWrapper"></div>'));
            if(activityData.actStartDate) {
                $('#' + activityData.id  + 'Date', liHTML).append($('<span class="dateHighlight">Comienzo: ' + $.ti.utils.flipDate(activityData.actStartDate) + '</span>'));
            }
            if(activityData.actEndDate) {
                $('#' + activityData.id  + 'Date', liHTML).append($('<span class="dateHighlight">Fin:' + $.ti.utils.flipDate(activityData.actEndDate) + '</span>'));
            }
        }

        // Attach data to item
        $(liHTML).data('data', activityData);

		// Check if empties exist and either replace add.
        emptyItems = $('li.empty', '#theBag');

        // Check if new item
        if(newItem) {
            // Kill nag panel
            $.ti.nag.kill();

			// Add the item
			$(liHTML).hide()
				.prependTo('#theBag')
				.slideDown('500', function() {
					if(emptyItems.length > 0) {
						$(emptyItems[0]).remove();
					}
				});
			// Update bag data
			$.ti.bag.updateData(true);

            $.ti.bag.getListLength();
            var l = $.ti.bag.properties.listLength;
            if (l === 1 && $.ti.panel.panelOpen === false)
            {
				$('#panelToggler').click();
            }

			// Only trigger the auto open for new items
/*			if(($.ti.tripData.trip.showOnAdd === true  ||
                $.ti.bag.unopened === true) && $.ti.panel.panelOpen === false) {
				$('#panelToggler').click();
			}*/

			// Checks to see this is not the first item - otherwise we have to create the tripActivities object
			if($.ti.tripData.trip.tripActivities) {
			    $.ti.tripData.trip.tripActivities.activity.push(activityData);
			} else {
			    $.ti.tripData.trip.tripActivities = {};
			    $.ti.tripData.trip.tripActivities.activity = [];
			    $.ti.tripData.trip.tripActivities.activity.push(activityData);
			}
			// Update category filter
			$.ti.categories.get();

			// feedback for adding new item
//			this.addFeedback(activityData.actName);
		} else {
			// Add items on initial load - no need for fancy slide in here.
			$('#theBag').prepend(liHTML);
			if(emptyItems.length > 0) {
				$(emptyItems[0]).remove();
			}
			$.ti.bag.setData();
		}

        // If not reviewer make draggable
        if($.ti.tripData.trip.role !== 'R') {
            $('#' + activityData.id).draggable({
                helper: 'clone',
                appendTo: '#panelContent',
                zIndex: '9000',
                cursorAt: {'top':5, 'left':5},
                start: function(event, ui) {
//                    $(ui.helper).css({'width' : $.ti.createTripCalendar.activityWidth});
                    $(ui.helper).css({'width' : 170, 'opacity': 0.7 });
                    $.ti.createCalendarActivity.toggleDateHighlight(ui.helper);
                },

                stop: function(event, ui) {
                    // save the update...
		            $.ti.ajax.postData('/es/trip/', $.ti.tripData);
                }
            });
        }

        // save the change...
        if (newItem)
            $.ti.ajax.postData('/es/trip/', $.ti.tripData);
	},

	addFeedback : function(activityName, coords) {
		var html = $('<p id="addFeedback"><span>'+activityName+'</span> se añade a la lista de tu Plan de Viaje.</p>');
		$(document.body).prepend(html);

        html.css({
            width: 200,
            top: coords.y + 'px',
            left: coords.x + 'px'
        }).fadeIn(500, function() {
            setTimeout(function() {
                html.fadeOut(1000, function() {$(this).remove(); });
            }, 500);
        });
	}
};
})(jQuery);
