// Create the master array to hold the trip details
var tripArray = [];
var eventArray = [];
var numberOfSteps = 3;
var selectionSet = false;
var selecteditinerary;
var totalTimeLow = 0;
var totalTimeHigh = 0;
var selectedwho = '';
var selectedwhen = '';
var eventdetails = new Array();

$(document).ready( function() {
	
	// Script to run when the steps page is loaded and ready
	if($('.stepscontainer').length) {
		
		// Clear out any old cookie data
		setCookie('itindetails', '', -1);
		setCookie('selecteditinerary', '', -1);
		
		// Hide all of the step content
		$('.stepcontent').css('display', 'none');
		
		// Disable all next buttons
		for(var i=0; i < (numberOfSteps + 1); i++) {
			$('.step' + i + '-next').css('cursor', 'not-allowed');
			$('.step' + i + '-next').unbind().bind('click', function() {
				// Do nothing
				return false;
			});
		}
		
		enableStep(1);
		
		$('.seeallattractions a').click(function() {
			setCookie("itindetails","all$|$all$|$all", 1);
			// hit the service here to retrieve results
			document.location = 'trip-planner-results.aspx';
			return false;
		});
		
		$('.selectallstep3').click(function() {
			$('.step3 li a').each(function() {
				eventArray[$(this).attr('href')] = $(this).attr('class').replace(/ moreactive/i, '');
				tripArray[2] = eventArray;
				$(this).addClass('moreactive');
			});
			$('.step3-next').css('cursor', 'pointer');
			$('.step3-next').unbind().bind('click', function() {
				// Collapse all of the steps
				collapseSteps();
				// Enable and display the requested step
				enableStep(4);
				return false;						
			});
			return false;
		});
	}
	
	// Script to run when the results page is loaded and ready
	if($('.itineraryselect').length) {
		
		// Get the details of the user submission
		var cookieval = getCookie('itindetails');
		if(cookieval) {
			var headerdetails = cookieval.split('$|$');
			var eventstring = '';
			eventdetails = headerdetails[2].split(':');

			for (var j = 0; j < eventdetails.length; j++) {
			    eventstring = eventstring + eventdetails[j];
			    if (j < eventdetails.length - 1) {
					eventstring = eventstring + ' + ';	
				}
			}
			
			selectedwho = headerdetails[0].toUpperCase();
			selectedwhen = headerdetails[1].toUpperCase();
			
			//Display the users selected parameters in the header
			if(selectedwho == "ALL") {
				$('.details').html('ALL ATTRACTIONS AND EVENTS');
			}
			else {
				$('.details').html(selectedwho + ' + ' + selectedwhen + ' + ' + eventstring.toUpperCase());	
			}
		}
		// Get the xml file
		
		$.ajax({
			type: "GET",
			url: "lib/xml/tripplanner.xml",
			dataType: "xml",
			success: displaySearchResults
		});	
		
		// This function will handle the scrolling sidebar when the user scrolls down the screen
/*		$(function() {
		
			var $sidebar   = $(".selecteditinerary"),
				$window    = $(window),
				offset     = $sidebar.offset(),
				topPadding = 15;
		
			$window.scroll(function() {
				if ($window.scrollTop() > offset.top) {
					$sidebar.stop().animate({
						marginTop: $window.scrollTop() - offset.top + topPadding
					});
				} else {
					$sidebar.stop().animate({
						marginTop: 0
					});
				}
			});
		
		});	*/	
				
	}
	
	// Script to run when the itinerary page is loaded and ready
	if($('.finalitinerary').length) {
		
		// Get the details of the user submission
		var cookieval = getCookie('selecteditinerary');
		if(cookieval) {
			selecteditinerary = cookieval.split('$|$');
		// Get the xml file
		
			$.ajax({
				type: "GET",
				url: "lib/xml/tripplanner.xml",
				dataType: "xml",
				success: displayItinerary
			});				
		}
				
	}	
	
});


function displaySearchResults(xml)
{

  $(xml).find("cwitem").each(function()
  {
	var itemname = $(this).find("cwitemname").text();
	var icon = $(this).find("cwitemicon").text();
	var itemid = $(this).find("cwitemid").text();
	var itemdetails = $(this).find("cwitemdetails").text();
	var itemadditionaldetails = $(this).find("cwitemadditionaldetails").text();
		
	var itineraryitem = '<div class="itineraryitem"><img src="lib/img/tripplanner/icons/' + icon + '" width="95" height="95" border="0" alt="' + itemname + '" class="iticon" /><div class="additem"><p>Add to Itinerary</p><div class="checkbox" id="chk' + itemid + '"></div></div><h4>' + itemname + '</h4><div class="itemdetails"><p>' + itemdetails + '</p><p class="moredetails">' + itemadditionaldetails + '</p><p><a href="" class="moreinfo"><img src="lib/img/tripplanner/moreinfobutton.gif" width="83" height="22" alt="More Info" border="0" /></a></p></div><div class="clear"></div></div>';
	// If the cookie was set to view all, display all.  Otherwise do a match below
	if(selectedwho == 'ALL') {
		$(".itinerarylist").append(itineraryitem);
	}
	else {
		var whomatch = $(this).find("cwitemwho").find("group");
		if(($(this).find("cwitemwho").text().toUpperCase().indexOf(selectedwho) != -1)) {
			if(($(this).find("cwitemwhen").text().toUpperCase().indexOf(selectedwhen) != -1)) {
				for(var i = 0; i < eventdetails.length; i++) {
					if($(this).find("cwitemwhat").text().toUpperCase().indexOf(eventdetails[i].toUpperCase()) != -1) {
						$(".itinerarylist").append(itineraryitem);
						break;
					}
				}
			}
		}
	}
  });
  $(".itinerarylist").append('<div class="viewitinerary"><a href=""><img src="lib/img/tripplanner/viewitinerarybuttonlg.gif" width="169" height="33" alt="View Itinerary" border="0" /></a></div> ');

  setupItineraryListeners();
    
	// Get the details of the user submission
	var cookieval = getCookie('selecteditinerary');
	if(cookieval != 'none') {
		selecteditinerary = cookieval.split('$|$');
		for(var i = 0; i < selecteditinerary.length; i++) {
			$('#chk' + selecteditinerary[i]).trigger('click');
		}
	}
	  
}


function displayItinerary(xml)
{
	for(var i = 0; i < selecteditinerary.length - 1; i++) {
		var tempitem = $("cwitem:eq(" + (selecteditinerary[i] - 1) + ")", xml).find("cwitemid").text();
		var itemname = $("cwitem:eq(" + (selecteditinerary[i] - 1) + ")", xml).find("cwitemname").text();
		var icon = $("cwitem:eq(" + (selecteditinerary[i] - 1) + ")", xml).find("cwitemicon").text();
		var itemid = $("cwitem:eq(" + (selecteditinerary[i] - 1) + ")", xml).find("cwitemid").text();
		var itemdetails = $("cwitem:eq(" + (selecteditinerary[i] - 1) + ")", xml).find("cwitemdetails").text();
		var itemadditionaldetails = $("cwitem:eq(" + (selecteditinerary[i] - 1) + ")", xml).find("cwitemadditionaldetails").text();		
		var itemapproxtime = $("cwitem:eq(" + (selecteditinerary[i] - 1) + ")", xml).find("cwitemapproxtime").text();
			
		var itineraryitem = '<div class="itineraryitem" rel="' + tempitem + '"><img src="lib/img/tripplanner/icons/' + icon + '" width="95" height="95" alt="' + itemname + '" class="iticon" /><div class="removeitem"><p><a href="">Remove</a></p></div><h4>' + itemname + '</h4><div class="itemdetails"><p>' + itemdetails + '</p><p class="moredetails">' + itemadditionaldetails + '</p><p><a href="" class="moreinfo"><img src="lib/img/tripplanner/moreinfobutton.gif" width="83" height="22" alt="More Info" border="0" /></a></p></div><span class="hiddentime">' + itemapproxtime + '</span><div class="clear"></div></div>';
		$(".finalitinerary").append(itineraryitem);
		if(itemapproxtime != 'null') {
			totalTimeLow = totalTimeLow + parseFloat(itemapproxtime);
			totalTimeHigh = totalTimeHigh + parseFloat(itemapproxtime);	
		}
		else {
			totalTimeLow = totalTimeLow + 2;
			totalTimeHigh = totalTimeHigh + 4;				
		}
	}
	
	setupResultListeners();
	
	var timeval = "hour";
	if(totalTimeHigh > 1) {
		timeval = "hours";
	}
	if(totalTimeLow == totalTimeHigh) {
		$('.allowtime').html('<strong>We recommend allotting <span class="red">' + totalTimeLow + '</span> ' + timeval + ' for this itinerary.</strong>');
	}
	else {
		$('.allowtime').html('<strong>We recommend allotting between <span class="red">' + totalTimeLow + ' and ' + totalTimeHigh + ' </span> ' + timeval + ' for this itinerary.</strong>');
	}
	
	$('.print').unbind().bind('click', function() {
		window.print() ;
		return false;
	});
	
	$('.removeitem').unbind().bind('click', function() {

		if($(this).parent().find('.hiddentime').html() != 'null') {
			totalTimeLow = totalTimeLow - $(this).parent().find('.hiddentime').html();			
			totalTimeHigh = totalTimeHigh - $(this).parent().find('.hiddentime').html();			
		}
		else {
			totalTimeLow = totalTimeLow - 2;			
			totalTimeHigh = totalTimeHigh - 4;
		}
		
		var timeval = "hour";
		if(totalTimeHigh > 1) {
			timeval = "hours";
		}
		if(totalTimeLow == totalTimeHigh) {
			$('.allowtime').html('<strong>We recommend allotting <span class="red">' + totalTimeLow + '</span> ' + timeval + ' for this itinerary.</strong>');
		}
		else {
			$('.allowtime').html('<strong>We recommend allotting between <span class="red">' + totalTimeLow + ' and ' + totalTimeHigh + ' </span> ' + timeval + ' for this itinerary.</strong>');
		}
				
		for(var i = 0; i < selecteditinerary.length - 1; i++) {
			if(selecteditinerary[i] == $(this).parent().attr('rel')) {
				selecteditinerary.splice(i, 1);
				break;
			}
		}
		
		var itemlist = '';
		for (var k = 0; k < selecteditinerary.length - 1; k++) {
		    itemlist = itemlist + selecteditinerary[k] + '$|$';	
		}
		if(itemlist.charAt(itemlist.length - 1) == ':') {
			itemlist = itemlist.substring(0, itemlist.length - 1);
		}
		setCookie('selecteditinerary', itemlist , 1);		
			
		$(this).parent().stop().animate({ opacity: 0, 'margin-top': -30 }, 300, function() {
			$(this).remove();
		});
		
		if( totalTimeLow == 0) {
			var emptyItinerary = '<div class="emptyItinerary">Your itinerary is empty. Please <a href="trip-planner-results.aspx">edit</a> or <a href="trip-planner.aspx">start over</a>.</div>';
			$(".finalitinerary").append(emptyItinerary);		
		}		
		return false;
	});	
}

// Enable each step here
function enableStep(pStep) {
	if(pStep > 3) {
		var events = '';
		for(var i = 0; i < eventArray.length; i++) {
			if(eventArray[i] != 'undefined' && eventArray[i] != null) {
				events = events + eventArray[i] + ':';
			}
		}
		if(events.charAt(events.length - 1) == ':') {
			events = events.substring(0, events.length - 1);
		}
		setCookie("itindetails",tripArray[0] + '$|$' + tripArray[1] + '$|$' + events, 1);
		// hit the service here to retrieve results
		document.location = 'trip-planner-results.aspx';
		//return false;
	}
	
	// Display the edit button and attach a binding click event
	$('.step' + (pStep - 1)).find('.editstep').css('display', 'block');
	$('.step' + (pStep - 1)).find('.editstep').unbind().bind('click', function() {
		collapseSteps();
		enableStep(pStep - 1);
		return false;
	});
	
	// Add classes to change the step styling
	$('.step' + pStep).addClass('enabled');
	$('.step' + pStep + ' .stepheader').addClass('stepheaderenabled');
	
	// Display the content within the step
	//$('.step' + pStep + ' .stepcontent').css('display', 'block');
	$('.step' + pStep + ' .stepcontent').slideDown(300);
	
	// Add a listener to each item in the list for each step
	// Populate the array and then enable the next button.
	$('.step' + pStep + ' li a').unbind('click').bind('click', function() {
		
		if(pStep == 3) {
			if(eventArray[$(this).attr('href')] != null) {
				eventArray[$(this).attr('href')] = null;
				$(this).removeClass('moreactive');				
			}
			else {
				eventArray[$(this).attr('href')] = $(this).attr('class').replace(/ moreactive/i, '');
				tripArray[pStep - 1] = eventArray;
				$(this).addClass('moreactive');
			}
		}
		else {
			$('.step' + pStep + ' li a').removeClass('active');
			tripArray[pStep - 1] = $(this).attr('class');
			$(this).addClass('active');			
		}
		
		if(pStep == 3) {
			var selectionSet = false;
			for(var i=0; i < eventArray.length; i++) {
				if(eventArray[i] != null) {
					selectionSet = true;
					break;
				}
			}
			if(selectionSet) {
				// Change the cursor back to a pointer now that a selection has been made.
				$('.step' + pStep  + '-next').css('cursor', 'pointer');					
			} 
			else {
				$('.step' + pStep  + '-next').css('cursor', 'not-allowed');
			}
		} 
		else {
			selectionSet = true;
			// Change the cursor back to a pointer now that a selection has been made.
			$('.step' + pStep  + '-next').css('cursor', 'pointer');
		}
		if(selectionSet) {
			// Add a listener for the next button of next step
			$('.step' + pStep + '-next').unbind().bind('click', function() {
				// Collapse all of the steps
				collapseSteps();
				// Enable and display the requested step
				enableStep(pStep + 1);
				return false;						
			});
		}
		else {
			$('.step' + pStep + '-next').unbind();
		}
		return false;
	});	
	return false;
}

function collapseSteps() {
	for(var i=1; i < (numberOfSteps + 1); i++) {
		//$('.step' + i + ' .stepcontent').css('display', 'none');	
		$('.step' + i + ' .stepcontent').slideUp(300);
	}
}

function modifyItinerary(pItem, pState) {
	if(pState) {
		var testelement = document.createElement('div');
		$(pItem).appendTo('.selecteditinerary');
		$('.removeitem').unbind().bind('click', function() {
			$('#chk' + $(this).parent().attr('id').substring(9, $(this).parent().attr('id').length)).css('backgroundImage', 'none');
			$(this).parent().stop().animate({ opacity: 0, 'margin-top': -30 }, 300, function() {
				$(this).remove();
			});
			return false;
		});
	}
	else {
		$('#' + pItem).stop().animate({ opacity: 0, 'margin-top': -30 }, 300, function() {
			$('#' + pItem).remove();
		});
	}
}

function setupItineraryListeners() {
	$('.checkbox').click(function() {
		var tempId = $(this).attr('id').substring(3, $(this).attr('id').length);
		if($(this).css('background-image') == 'none') {
			$(this).css('background-image', 'url(lib/img/tripplanner/checkmark.gif)');
			modifyItinerary('<div class="selecteditem" id="addeditem' + tempId + '"><img src="' + $(this).parent().parent().find('.iticon').attr('src') + '" width="32" height="32" border="0" /><span>' + $(this).parent().parent().find('h4').html() + '</span><div class="removeitem"><a href="">X</a></div><div class="clear"></div></div>', true);
		} else {
			$(this).css('background-image', 'none');
			modifyItinerary('addeditem' + tempId, false)
		}
	});


	// Select all of the itinerary items		
	$('.selectall').click(function() {
		$('.checkbox').each(function() {
			if($(this).css('background-image') == 'none') {
				$(this).css('background-image', 'url(lib/img/tripplanner/checkmark.gif)');
				var tempId = $(this).attr('id').substring(3, $(this).attr('id').length);
				modifyItinerary('<div class="selecteditem" id="addeditem' + tempId + '"><img src="' + $(this).parent().parent().find('.iticon').attr('src') + '" width="32" height="32" border="0" /><span>' + $(this).parent().parent().find('h4').html() + '</span><div class="removeitem"><a href="">X</a></div><div class="clear"></div></div>', true);
			}
		});
		/*for( var i=1; i <= $('.checkbox').size(); i++) {
			if($('#chk' + i).css('background-image') == 'none') {
				$('#chk' + i).css('background-image', 'url(lib/img/tripplanner/checkmark.gif)');
				modifyItinerary('<div class="selecteditem" id="addeditem' + i + '"><img src="' + $('#chk' + i).parent().parent().find('.iticon').attr('src') + '" width="32" height="32" /><span>' + $('#chk' + i).parent().parent().find('h4').html() + '</span><div class="removeitem"><a href="">X</a></div><div class="clear"></div></div>', true);
			}
		}*/
		return false;
	});
	
	// Display or hide the additional information for each item in the itinerary list
	$('.moreinfo').click(function() {
		if($(this).parent().prev().css('display') == 'none') {
			//$(this).parent().prev().css('display', 'block');
			$(this).parent().prev().slideDown(300);
			$(this).find('img').attr('src', 'lib/img/tripplanner/lessinfobutton.gif');
		}
		else {
			//$(this).parent().prev().css('display', 'none');
			$(this).parent().prev().slideUp(300);
			$(this).find('img').attr('src', 'lib/img/tripplanner/moreinfobutton.gif');
		}
		return false;
	});	
	
	$('.viewitinerary').click(function() {
		var selecteditems = new Array();
		$('.selecteditem').each(function() {
			var tempid = $(this).attr('id');
			tempid = tempid.substring(9, tempid.length);
			selecteditems.push(tempid);
			selecteditems.sort(function(a,b){return a - b});
		});
		var itemlist = '';
		for(var i = 0; i < selecteditems.length; i++) {
			itemlist = itemlist + selecteditems[i] + '$|$';	
		}
		if(itemlist.charAt(itemlist.length - 1) == ':') {
			itemlist = itemlist.substring(0, itemlist.length - 1);
		}
		if(selecteditems.length <= 0) {
			alert("You must select at least one item to add to view your itinerary.");
		}
		else {
			setCookie('selecteditinerary', itemlist , 1);
			document.location = 'trip-planner-itinerary.aspx';
		}
		return false;
	});
}

function setupResultListeners() {
	// Display or hide the additional information for each item in the itinerary list
	$('.moreinfo').click(function() {
		if($(this).parent().prev().css('display') == 'none') {
			//$(this).parent().prev().css('display', 'block');
			$(this).parent().prev().slideDown(300);
			$(this).find('img').attr('src', 'lib/img/tripplanner/lessinfobutton.gif');
		}
		else {
			//$(this).parent().prev().css('display', 'none');
			$(this).parent().prev().slideUp(300);
			$(this).find('img').attr('src', 'lib/img/tripplanner/moreinfobutton.gif');
		}
		return false;
	});		
}

// SET COOKIE
function setCookie(cookieName,value,expiredays) {
	var exdate= new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie = cookieName + " = " + escape(value) + "; path=/" + ((expiredays==null) ? "" : "; expires = " + exdate.toGMTString());
}

// GET COOKIE (returns 'none' if not found, you can change that to null, '', etc.)
function getCookie(check_name) {
	var cookies = document.cookie.split( ';' );
	var temp_cookie = "";
	var cookie_name = "";
	var cookie_value = "";
	var cookie_found = false;

	for (var i = 0; i < cookies.length; i++ ) {
					temp_cookie = cookies[i].split( '=' );
					cookie_name = temp_cookie[0].replace(" ", "");

					if (cookie_name == check_name) {
									cookie_found = true;
									if (temp_cookie.length > 1) cookie_value = unescape(temp_cookie[1].replace(" ", ""));
					}
	}
	if (!cookie_found) {
					return "none";
	} else {
					return cookie_value;
	}
}

