/*
 * No page reloads can occur. Instead, we transition between pages seamlessly using AJAX - at least, that's the theory!
 * 
 */

(function($){ 

$.fn.transitions = function() {
	return this.each(function(){
		$('.init-transition').click(getStep);
		$('.init-transition-carousel', this).each(function() {
			$(this).click(transitionFromCarousel);
		});
	});
}

var getStep = function() {

	var step = $("input[name='UserJourney_currentStep']").val();
	var btn = $(this);
	
	if (btn.hasClass('init-transition-back')) {
		transitionFromBackBtn(step);
	}
	else if (btn.hasClass('init-transition-start')) {
		transitionToStart(step);
	}
	else {
		transition(step);
	}
	return false;
	
}

var appendSelectAll = function() {
	$('.ctr-extras').append(
		'<div>' +
			'<span id="select-all" class="type-checkbox"></span>' +
			'<label for="select-all">Select All</label>' +
		'</div>'
	);
}

var chkAllCheckboxes = function(clickedElm) {

	var spn;

	if (clickedElm.is('label')) {
		spn = clickedElm.prev('span');
	}
	else {
		spn = clickedElm;
	}
	
	if (spn.hasClass('checked')) {
		spn.removeClass('checked');
		$('.type-checkbox').removeClass('checkbox-checked');
		$('input:checkbox').attr('checked', false);
	}
	else {
		spn.addClass('checked');
		$('.type-checkbox').addClass('checkbox-checked');
		$('input:checkbox').attr('checked', true);
	}
	
}

var loadPageTest = function(post) {

	$('#wrapper').load('/ form', post, function() {
	
		$.getScript('/js/jquery.jcarousel.min.js', function() {
		
			$("#mycarousel").jcarousel({
				scroll: 1,
				wrap: 'none',
				initCallback: mycarousel_initCallback,
				// This tells jCarousel NOT to autobuild prev/next buttons
				buttonNextHTML: null,
				buttonPrevHTML: null
			});
			
		});
		
	});

}

var loadPage = function(post, step) {
		
	$(document).scrollTop(0);
	$('body').prepend('<div id="ctr-loader"><div id="loader" /></div>');
	var ctrLoader = $('#ctr-loader');
	var loader = $('#loader');
	var h = $(document).height();
	ctrLoader.height(h);
	loader.height(h);
	
	$('#wrapper').load('/ form', post, function(response, status, xhr) {
	
		if (status == 'error') {
	
			$('#bookingForm').append('<input type="hidden" name="submit_go_start" value="name" />');
			$('#bookingForm').submit();
			
		}
		else {
			$.getScript('/js/more-than-just-carousels.js', function() {
				rideTheCarousel();
				
				$('#mycarousel li').each(function() {
					$(this).removeClass('chosenVenue');
				});
				
				var currentStep = $("input[name='UserJourney_currentStep']").val();
				
				var chosenVenueItem;
				
				chosenVenueItem = $("input[name='submit_carousel_venue__" + $('#selectedVenue').val() + "']").parent('li');
				chosenVenueItem.addClass('chosenVenue');
				
				var carouselStart = $('#mycarousel li').index(chosenVenueItem);
				
				$("#mycarousel").jcarousel({
					scroll: 3,
					wrap: 'none',
					start: carouselStart,
					initCallback: mycarousel_initCallback,
					// This tells jCarousel NOT to autobuild prev/next buttons
					buttonNextHTML: null,
					buttonPrevHTML: null
				});
				
				
				if (currentStep != 'LNL_SEARCH' && currentStep != 'LNL_SEARCH_RESULTS' && currentStep != 'VENUE') {
					$('#mycarousel li').unbind('click');
					$('#mycarousel-next').unbind('click').css('cursor', 'default');
					$('#mycarousel-prev').unbind('click').css('cursor', 'default');
					$('.carousel_link').css('display', 'none');
					$("#mycarousel li").each(function() {
					
						if ($(this).hasClass('chosenVenue')) {
							$(this).find('img').addClass("carousel_active");	
							$(this).find('img.carousel_active').css("display", "block");
							$(this).find('img.carousel_inactive').css("display", "none");
						}
						else {
							$(this).find('img.carousel_active').css("display", "none");
							$(this).find('img.carousel_inactive').css("display", "block");			
							$(this).find('img').addClass("carousel_inactive");
						}
						
					});
				}
			
			});
			
			$.getScript('/js/jquery.novus-forms.js', function() {
			
				Cufon.replace('h3.menu');
				
				var currentStep = $("input[name='UserJourney_currentStep']").val();
				var event = $("input[name='event']").val();
			
				loader.fadeOut(1000, function() {
					
					ctrLoader.remove();
					loader.remove();
					
				});	
				
				if (currentStep == 'LNL_SEARCH' || currentStep == 'LNL_SEARCH_RESULTS') {
					if (event == 'worldcup') {
					
						$('#tweetsLdr').show();
					
						$.getScript('/js/jquery.juitter.js', function() {
						
							$.Juitter.start({
								searchType:"searchWord", // needed, you can use "searchWord", "fromUser", "toUser"
								searchObject:"FIFAWorldCupTM,WorldCup2010FC,WorldCupSA,KickOffMagazine,bbcfoot", // needed, you can insert a username here or a word to be searched for, if you wish multiple search, separate the words by comma.

								// The values below will overwrite the ones on the Juitter default configuration. 
								// They are optional here.
								// I'm changing here as a example only
								lang:"en", // restricts the search by the given language
								live:"live-5", // the number after "live-" indicates the time in seconds to wait before request the Twitter API for updates.
								placeHolder:"juitterContainer", // Set a place holder DIV which will receive the list of tweets example <div id="juitterContainer"></div>
								loadMSG: " ", // Loading message, if you want to show an image, fill it with "image/gif" and go to the next variable to set which image you want to use on 
								imgName: "", // Loading image, to enable it, go to the loadMSG var above and change it to "image/gif"
								total: 20, // number of tweets to be show - max 100
								readMore: " ", // read more message to be show after the tweet content
								nameUser:"text", // insert "image" to show avatar of "text" to show the name of the user that sent the tweet 
								openExternalLinks:"newWindow", // here you can choose how to open link to external websites, "newWindow" or "sameWindow"
										filter:"sex->*BAD word*,porn->*BAD word*,fuck->*BAD word*,shit->*BAD word*"  // insert the words you want to hide from the tweets followed by what you want to show instead example: "sex->censured" or "porn->BLOCKED WORD" you can define as many as you want, if you don't want to replace the word, simply remove it, just add the words you want separated like this "porn,sex,fuck"... Be aware that the tweets will still be showed, only the bad words will be removed
							});
							
						});
					}
				}
				
				timer = undefined;
				
				if (step == 'MENU') {
					var co = $('.calendar-opts').eq(0);
					
					if (!$('td').find('input').hasClass('selected')) {
						co.append('<div class="obfuscate" />')
						$('.obfuscate').width(co.width());
					}
				}
				
				if (currentStep == 'WORLDCUP_CALENDAR') {
					$.getScript('/js/worldcup-calendar.js');
					
					var co = $('.calendar-opts').eq(0);
					
					if (!$('tr').hasClass('selected')) {
						co.append('<div class="obfuscate" />')
						$('.obfuscate').width(co.width());
					}
					else {
						var tr = $('tr.selected');
						tr.find('td').addClass('selected highlight');
					}
					
				}
				
				if (currentStep == 'EXTRAS') {
					appendSelectAll();
					$('#select-all').click(function() {
						chkAllCheckboxes($(this));
					});
					$('label[for="select-all"]').click(function() {
						chkAllCheckboxes($(this));
					});
				}
				switch(currentStep) {
					case 'LNL_SEARCH':
					pageTracker._trackPageview("/funnel_G1/select-venue.html");
					break;

					case 'LNL_SEARCH_RESULTS':
					pageTracker._trackPageview("/funnel_G1/search-result.html");
					break;
					
					case 'VENUE':
					pageTracker._trackPageview("/funnel_G1/venue-details.html");
					break;

					case 'MENU':
					pageTracker._trackPageview("/funnel_G1/select-menu.html");
					break;

					case 'CALENDAR':
					pageTracker._trackPageview("/funnel_G1/party-date-time.html");
					break;

					case 'WORLDCUP_CALENDAR':
					pageTracker._trackPageview("/funnel_G1/match-date-time.html");
					break;

					case 'EXTRAS':
					pageTracker._trackPageview("/funnel_G1/extras.html");
					break;

					case 'DETAILS':
					pageTracker._trackPageview("/funnel_G1/details.html");
					break;

					case 'THANKS':
					pageTracker._trackPageview("/funnel_G1/thank-you.html.html");
					break;
					
					default:
					break;
				}
				
				
			});
			
			$('.init-transition').click(getStep);
			$('.init-transition-carousel').click(transitionFromCarousel);
			$('.init-transition-menu-tabs').click(transitionFromMenuTab);
			$('.init-transition-calendar-tabs').click(transitionFromCalendarTab);
			$('.init-transition-worldcup-calendar-tabs').click(transitionFromWorldcupCalendarTab);
			$('.init-transition-calendar').click(transitionFromCalendarCell);
			$('.init-transition-worldcup-calendar').click(transitionFromWorldcupCalendarCell);
			$('.init-transition-back').click(getStep);
			$('.init-transition-start').click(getStep);
			$('.temp').remove();
		}
		
	});
	
	return false;
				
}

var loadCalendar = function(post, elm) {
	
	var currentStep = $("input[name='UserJourney_currentStep']").val();
	var elmParent = elm.parents('td');
	
	elm.wrap('<div class="calendar-cell-wrap">');
	var calendarCellWrap = elmParent.find('.calendar-cell-wrap')
	
	if (currentStep == 'WORLDCUP_CALENDAR') {
		$('TD input').removeClass('selected');
		$('TD').removeClass('selected highlight');
		calendarCellWrap.prepend('<div class="calendar-loading" />');

		var tr = elmParent.parents('tr');
		
		tr.find('td').addClass('selected highlight');
	}
	else {
		$('TD input').css('background', '#F1E4F0').removeClass('selected');
		calendarCellWrap.prepend('<div class="calendar-loading" />');	
		elm.css('background', 'lightblue').addClass('selected');
	}
	$('TD input').attr('disabled', true); // attr added to prevent superfastfinger breaking layout
	
	var chooseTime = $('.select-type2').children('#chooseTime');
	var chooseOpt = chooseTime.find('option');
	
	chooseOpt.remove();
	
	$('.select-type2').prepend('<div class="hidden" />');
	var hidden = $('.select-type2').find('.hidden');
	
	hidden.load('/ #chooseTime ', post, function() {
	
		var currentStep = $("input[name='UserJourney_currentStep']").val();
	
		$('.calendar-loading').fadeOut(1000, function() {
			
			if (currentStep == 'WORLDCUP_CALENDAR') {
				$('.pulse').stop().delay(500).animate({color: '#000000'}, function() {
					$(this).animate({color: '#ffffff'}, {queue: false});
				});
			}
			else {
				$('.pulse').stop().delay(500).animate({color: '#be00ab'}, function() {
					$(this).animate({color: '#ffffff'}, {queue: false});
				});
			}
			elm.unwrap();
			$('.calendar-loading').remove();
			$('TD input').removeAttr('disabled'); // attr removed to enable change of fixture
		
		});
		$('.obfuscate').remove();
		
		
		chooseTime = $('.select-type2').children('#chooseTime');
		var newTimes = $('.hidden').children('#chooseTime');
		var newOpt = newTimes.find('option');
		
		newOpt.each(function() {
		
			var opt = $(this);
			chooseTime.append('<option value="' + opt.attr('value') + '">' + opt.text() + '</option>');
			
		});
		
		$('.hidden').remove();
		var listTimes = $('.dropdown').find('ul');
		chooseOpt = chooseTime.find('option');
		
		listTimes.find('li').remove();
		
		chooseOpt.each(function() {
		
			var opt = $(this);
			
			if (opt.attr('value') != "") {
				listTimes.append('<li><span id="' + opt.attr('value') + '">' + opt.text() + '</span></li>');
			}
			
		});
		
		$('.txt').text('');
		
		var pos = $('.ctr-dropdown').position().top;
		
		var spn = listTimes.find('span');
		
		spn.click(function() {
		
			var span = $(this);
								
			chooseOpt.each(function() {
							   
				var opt = $(this);
				
				if (span.attr('id') == opt.attr('value')) {
					listTimes.find('span').each(function() {
						$(this).removeClass('selected');							
					});
					
					$('.txt').text(span.text());
					span.addClass('selected');
					opt.attr('selected', 'selected');
					
					$('.ctr-dropdown').animate({
						top: pos
					}, {
						duration: 0,
						complete: function() {
							$('.viewport').css('visibility', 'hidden');		
						},
						queue: false
					});
					
				}
				
			});
			
		});
		
		spn.hover(
			function() {
				$(this).addClass('hover');
			},
			function() {
				$(this).removeClass('hover');			
			}
		);				
		
		listTimes.jScrollPane({scrollbarWidth:12, dragMinHeight:20});
		
	});
	
	return false;
				
}

var transitionFromCarousel = function() {
	
	var elm = $(this);
	var post = {};
	post[elm.attr('name')] = 'name';
	
	loadPage(post, elm.attr('name'));
	
	return false;
	
}

var transitionFromMenuTab = function() {
	
	var elm = $(this);
	var post = {UserJourney_currentStep: 'MENU'};
	post[elm.attr('name')] = elm.val();
	
	loadPage(post);
	
	return false;
	
}

var transitionFromCalendarTab = function() {
	
	var elm = $(this);
	var post = assemblePost();
	post[elm.attr('name')] = elm.val();
	
	loadPage(post);
	
	return false;
	
}

var transitionFromWorldcupCalendarTab = function() {
	
	var elm = $(this);
	
	var post = assemblePost();
	post[elm.attr('name')] = elm.val();
	
	loadPage(post);
	
	return false;
	
}

var transitionFromCalendarCell = function() {
	
	var elm = $(this);
	var post = {UserJourney_currentStep: 'CALENDAR'};
	post[elm.attr('name')] = 'name';
	
	loadCalendar(post, elm);
	
	return false;
	
}

var transitionFromWorldcupCalendarCell = function() {
	
	var elm = $(this);
	var post = {UserJourney_currentStep: 'WORLDCUP_CALENDAR'};
	post[elm.attr('name')] = 'name';
	
	loadCalendar(post, elm);
	
	return false;
	
}

var transitionToStart = function(step) {
	
	$('#bookingForm').append('<input type="hidden" name="submit_go_start" value="name" />');
	$('#bookingForm').submit();
	
}

var assemblePost = function() {
	
	var post = {};
	
	$('select option:selected').each(function() {
		post[$(this).parent().attr('name')] = $(this).attr('value');
	});
	
	$('input[type="checkbox"]:checked').each(function() {
		post[$(this).attr('name')] = $(this).val();
	});
	
	$('input[type="text"]').each(function() {
		post[$(this).attr('name')] = $(this).val();
	});
	
	$('input[type="hidden"]').each(function() {
		post[$(this).attr('name')] = $(this).val();
	});
	
	return post;
	
}

var transitionFromBackBtn = function(step) {
	
	var post = assemblePost();
	
	post['submit_go_back'] = 'name';
	
	loadPage(post, step);
	
	return false;
	
}

var transition = function(step) {
	
	// Our post data from any submitted form. It will be a JSON string.
	var post = null;

	// We're going to switch based on the user journey step, grabbed from each form's hidden field.
	switch(step) {
		case 'LNL_SEARCH':
			post = {
				UserJourney_currentStep: step,
				lnl_search_location: $('#location').val(), 
				lnl_search_specialty: $('#venueFeatures').val(),
				submit_lnl_search: 'name'
			};
			break;
		case 'VENUE':
			post = {
				UserJourney_currentStep: step,
				submit_go_next: 'name'
			};
			break;
		case 'MENU':
			post = {
				UserJourney_currentStep: step,
				submit_go_next: 'name'
			};
			break;
		case 'CALENDAR':
			post = {
				UserJourney_currentStep: step,
				calendar_time: $('#chooseTime').val(),
				calendar_guests: $('#howManyDiners').val(),
				submit_calendar_next: 'name'
			};
			if ($('#confirm18').attr('checked') == true) {
				post['calendar_confirm'] = '1';
			}
			break;
		case 'WORLDCUP_CALENDAR':
			post = {
				UserJourney_currentStep: step,
				calendar_time: $('#chooseTime').val(),
				calendar_guests: $('#howManyDiners').val(),
				submit_worldcup_calendar_next: 'name'
			};
			if ($('#confirm18').attr('checked') == true) {
				post['calendar_confirm'] = '1';
			}
			break;
		case 'EXTRAS':
			post = {
				UserJourney_currentStep: step,
				submit_extras_next: 'name'
			};
			
			var extra = $('input:checked');
			
			extra.each(function() {
			
				var checkedBox = $(this).attr('id');
			
				post[checkedBox] = $('#' + checkedBox).val();
				
			});
			break;
		case 'DETAILS':
			post = {
				UserJourney_currentStep: step,
				details_first_name: $('#userFirstName').val(),
				details_last_name: $('#userLastName').val(),
				details_email: $('#userEmail').val(),
				details_confirm_email: $('#userEmail2').val(),
				details_phone_number: $('#userNumber').val(),
				submit_details_next: 'name'
			};
			break;
		default:
			throw 'Unrecognized step';
	}
	
	loadPage(post, step);
	
}


$(function(){
	$(document).transitions();	
});

})(jQuery);
