var Tickets = {

	timeout:120000,
	reservation:null,
	form:null,

	initSearch:function() {

		// Append the seat prompt dialog
		$('body').append('<div id="seatPrompt" title="These are the best available seat(s) that could be found." />');
		$("#seatPrompt").dialog({
			closeOnEscape: false,
			autoOpen: false,
			modal: true,
			resizable: false,
			draggable: false,
			width:600,
			buttons: {
				"I want these seats" : function() {
					// Disable the search for seats button (in case there is some serious traffic on the server,
					// we don't want people to click "Search for seats" again, which would delete their reservation. 
					Tickets.form.find('button').attr('disabled', true).addClass('disabled');
					window.onbeforeunload = null;
					// Proceed to add to cart
					Tickets.form.append('<input type="hidden" name="seat_reservations" value="1" />');
					Tickets.form.submit();
					$(this).dialog('close');
				},

				'No thanks' : function() {
					// Stop reservation timer
					clearTimeout(Tickets.reservation);
					
					// Release seats back to general public
					Tickets.release(Tickets.seats);
					$(this).dialog('close');
				}
			}
		});
		
		$('body').append('<div id="seatMessage" title="" />');
		$("#seatMessage").dialog({
			closeOnEscape: false,
			autoOpen: false,
			modal: true,
			resizable: false,
			draggable: false,
			width:600,
			buttons: {
				"Ok" : function() {
					// Renabled the search button
					$('button.seat_search').removeAttr('disabled').removeClass('disabled').html('<span>Search For Seats</span>');
					$(this).dialog('close');
				}
			}
		});		
		

		// Append the seat search dialog
		$('body').append('<div id="seatProgress" title=""/>');
		$("#seatProgress").dialog({
			closeOnEscape: false,
			autoOpen: false,
			modal: true,
			resizable: false,
			draggable: false,
			width:600,
			buttons: {}});		


		//watch for search seats button clicks
		$('button.seat_search').click(function(e) {
			// Grab which form the button was clicked in. This is needed for pages that have multiple seated ticket options
			Tickets.form = $(e.target).closest('form');
			
			// Disable the search button
			//var thisButton = $(this);
			$('button.seat_search').attr('disabled', true).addClass('disabled');

			// Now find the seats
			Tickets.search(Tickets.form.find('#sku').val(), Tickets.form.find('#quantity').val(), Tickets.form.find('input:radio[name=method]:checked').val());
			
			// Do not trigger default form submission
			return false;
		});
	},
	
	
	// Init the ticket reservation counter system
	initCounter:function() {

		Tickets.get();
	},
	
	counter:function() {
			
		var timeDom = $('div.GC_remaining');
		
		// Start the time interval to update the counter
		Tickets.reservation = setInterval(function() {

			// Decrement the timeout
			Tickets.timeout = Tickets.timeout - 500;
				
			// Out of time. Release tickets back to inventory and redirect back to cart with a message. Sorry bout it.
			if(Tickets.timeout < 1) {
				// Destroy the interval
				clearInterval(Tickets.reservation);
						
				// Open the seat message
				$('#seatMessage').dialog('open');				
						
				// Release tickets back to pool
				$.ajax({
					type: 'POST',
					url: '/ajax/tickets/release',
					data: {'timeout':1},
					dataType: 'json',
					success : function(data) {
						// Redirect						
						if(data.status) location.href = '/store/cart';
						else location.href = '/';
					}});
			}
		
			// Update the front end with the new time
			var minutes = Math.floor(Tickets.timeout/1000/60);
			var seconds = Math.floor((Tickets.timeout/1000) % 60);
			if(seconds<10) seconds = "0"+seconds;
					
			// Just in case
			if(minutes<0) minutes = "0";
			if(seconds<0) seconds = "00";
				
			timeDom.html(minutes+":"+seconds);
		}, 500);
		
	},
	
	
		

	// find some seats
	search:function(ticket, quantity, method) {

		// Binding page unload to observe
		function unloadPage(){
			return "Do not refresh this page or hit the back button in your browser. You will lose your place in line and may not be able to access tickets.";
		}

		window.onbeforeunload = unloadPage;

		// Destroy the previous timer and seats (if any)
		if(Tickets.reservation != null) clearTimeout(Tickets.reservation);
		Tickets.seats = null;

		// Show "Finding your seats..." dialog
		Tickets.progress();
		
		// Set a default method
		if(!method) method = 'mixed';
		
		//run search for best seats and return result
		$.ajax({
			type: 'GET',
			url: '/ajax/tickets/'+method,
			data: {'sku':ticket, 'quantity':quantity},
			dataType: 'json',
			success: function(data) {
				
				// Bad data passed
				if(data.status == 'error') {

					// Remove the "Finding your seats..." dialog
					Tickets.progress(false);
					
					// Report the error
					$('#seatMessage').dialog('option', 'title', "We&rsquo;re sorry&hellip;").html('<p>There was a problem with your request. Please refresh the page and try again.</p>');

					// Show seat search result dialog
					$("#seatMessage").dialog('open');
					window.onbeforeunload = null;
					return false;
				}
				
				if(data.status == 'timeout') {
					// Remove the "Finding your seats..." dialog
					Tickets.progress(false);
					
					// Report the error
					$('#seatMessage').dialog('option', 'title', "We&rsquo;re sorry&hellip;").html('<p>There was a problem reserving your seats. Please try searching again.</p>');

					// Show seat search result dialog
					$("#seatMessage").dialog('open');
					window.onbeforeunload = undefined;
					return false;					
				}
				
				if(data.status == 'disabled') {
					// Remove the "Finding your seats..." dialog
					Tickets.progress(false);
					
					// Report the error
					$('#seatMessage').dialog('option', 'title', "We&rsquo;re sorry&hellip;").html('<p>There was a problem reserving your seats. This account is under review. Ticket purchasing is not available at this time.</p>');

					// Show seat search result dialog
					$("#seatMessage").dialog('open');
					window.onbeforeunload = undefined;
					return false;					
				}				
				
				// Remove the "Finding your seats..." dialog
				Tickets.progress(false);
				
				// No seats found?
				if(data.status == 'soldout') {
					// Update the title and body of the seat prompt
					$('#seatMessage').dialog('option', 'title', "We&rsquo;re sorry&hellip;").html('<p>There are no available seats matching your request at this time, but other tickets may become available. Please try one or more of the following:</p><ul><li>Lower the quantity of requested tickets</li><li>Change your seating preference</li><li>Start your search again</li></ul>');

					// Show seat search result dialog
					$("#seatMessage").dialog('open');
					window.onbeforeunload = null;

				} else if(method == 'consecutive' && data.status == 'notfound') {

					$('#seatMessage').dialog('option', 'title', "We&rsquo;re sorry&hellip;").html('<p>There are no available seats together matching your request at this time, but other tickets may become available. Please try the following:</p><ul><li>Lower the quantity of requested tickets</li><li>Change your seating preference</li><li>Start your search again</li></ul>');

					// Show seat search result dialog
					$("#seatMessage").dialog('open');
					window.onbeforeunload = null;
				} else if(data.status == 'notfound') {

					$('#seatMessage').dialog('option', 'title', "We&rsquo;re sorry&hellip;").html('<p>There are no available seats matching your request at this time, but other tickets may become available. Please try the following:</p><ul><li>Lower the quantity of requested tickets</li><li>Change your seating preference</li><li>Start your search again</li></ul>');

					// Show seat search result dialog
					$("#seatMessage").dialog('open');
					window.onbeforeunload = null;
				// Show the seats found
				} else {
					// Split seats on a mix method, let's give the user a heads up!
					if(method == 'mixed' && data.status == 'split') $('#seatPrompt').dialog('option', 'title', 'These are the best available seat(s) that could be found.').html('<p>There are no available seats together matching your request at this time. The following seats are the best available for the quantity you have requested:</p><ul>');
					else $('#seatPrompt').attr('title', "These are the best available seat(s) that could be found.").html("<ul>");
					
					// Build the list of available seats
					for(var i = 0; i < data.seats.length; i++) { 
						$('#seatPrompt ul').append('<li>Section <strong>' + data.seats[i].section + '</strong> Row <strong>' + data.seats[i].row + '</strong> Seat <strong>' + data.seats[i].seat + '</strong></li>');  
					}
				
					$('#seatPrompt').append('<p>These seats are reserved for you for the next 2 minutes.</p><p><strong>Do not refresh this page or hit the back button in your browser. You will lose your place in line and may not be able to access tickets.</strong></p><p>Do you want these seats?</p>');
					
					// Begin countdown timer for seat reservation (two minutes)
					Tickets.reservation = setTimeout(function() {
						// Get rid of the prompt
						$("#seatPrompt").dialog('close');
						
						// Release the seats
						Tickets.release();
						
					}, Tickets.timeout);
					
					// Show seat search result dialog
					$("#seatPrompt").dialog('open');
				}
			}
		});
	},


	// release seats
	release:function() {

		// Let the user know NOT to refresh their page
		$('#seatProgress').dialog('option', 'title', "Please wait...").html('<p>We are preparing the system for you to search again. Do not refresh this page or hit the back button in your browser. You will lose your place in line and may not be able to access tickets.</p>').dialog('open');
			
		// Update the search button
		$('button.seat_search').html('<span>Please Wait...</span>').attr('disabled','disable').addClass('disabled');

		// Fire off request to release the seats
		$.ajax({
			type: 'POST',
			url: '/ajax/tickets/release',
			data: {},
			dataType: 'json',
			success : function(data) {
				// Re-enable the search button ONLY when the seats have been released
				if(data.status)	{
					window.onbeforeunload = undefined;
					$('button.seat_search').removeAttr('disabled').removeClass('disabled').html('<span>Search For Seats</span>');
					$('#seatProgress').dialog('close');
				}
			}
		});
	},


	progress:function(show) {
		// Remove the progress dialog
		if(show === false) $("#seatProgress").dialog('close');
		// Show the dialog
		else $("#seatProgress").dialog('option', 'title', 'Finding your seats').html('<p>Please wait while we find the seats that you have requested. Depending on demand and traffic, this process could take a while, so please be patient. Do not refresh this page or hit the back button in your browser. You will lose your place in line and may not be able to access tickets.</p>').dialog('open');
	},
	
	
	// Grab the seat reservations (if any)
	get:function() {
		$.ajax({
			type: 'POST',
			url: '/ajax/tickets/get',
			dataType: 'json',
			success : function(data) {
				if(data.status) {
					
					// Inject counter markup in body
					$('#page #GC .actions').before('<div class="GC_ticket GC_countdown"><h2>Seat Reservation</h2><ul></ul><div class="GC_ticker"><p>Your tickets are reserved for:</p><div class="GC_remaining"/></div></div>');

					// Inject message dialog
					$('body').append('<div id="seatMessage" title="You\'ve lost your seat reservations">We\'re sorry, but you\'ve lost your seat reservations. You will be redirected back to your cart.');
					$("#seatMessage").dialog({
						closeOnEscape: false,
						autoOpen: false,
						modal: true,
						resizable: false,
						draggable: false,
						width:600});
					
					// Set the timeout (in milliseconds)
					Tickets.timeout = (data.seats[0].dreserved - Math.round(new Date().getTime()/1000)) * 1000;
					
					// Print out the reserved seats
					for(var i = 0; i < data.seats.length; i++) 
						$('div.GC_countdown ul').append('<li>Section ' + data.seats[i].section + ' Row ' + data.seats[i].row + ' Seat ' + data.seats[i].seat + '</li>');
					
					Tickets.counter();
				}
		}});
	}

}
