

$(function () {
  
  $('#subnavigation').animate({top:0}, 300);
  
  var selectClubField = $('#selectClubField select');
	var printedPass = false;
  var hijackHREF = "";

  var setLocation = function (location) {
	  
	  $('#nearestLocation').html(location.title);
    $('#nearestLocation').fadeIn('fast');
    
    $('#nearestLocationAddress').html(location.address + '<br />' + location.city + ', ' + location.state + ' ' + location.zip + '<br />' + location.phone);
    $('#nearestLocationAddress').fadeIn('fast');
    
    $('#description').html(location.guest_pass_description);
    $('#description').fadeIn('fast');
    
		$('#mapIt').attr('href', location.map_url);

		$('#mapIt').fadeIn('fast');
    $('#barcode').fadeIn('fast');
    $('#printDate').fadeIn('fast');
    $('#printButton').fadeIn('fast');
	  
	  selectClubField.val(location.id);
	  
	};
	
  selectClubField.bind('change', function () {
    $.post("/locations_programs/show", {id:selectClubField.val(), authenticity_token:$('#guestPassForm input[name=authenticity_token]').val()}, function (responseString) {
      try {
        var result = eval('(' + responseString + ')');
        setLocation(result.location.location);
      } catch (error) {
        // failed
      }
    });
  });
	
	var validationOptions = {
		errorElement:"div",
		errorPlacement: function(error, element) {
	     element.before(error);
	   },
		messages: {
			first_name:'Required',
			last_name:'Required',
			email:'Required',
			phone:'Required',
			friend_first_name:'Required',
			friend_last_name:'Required',
			friend_email:'Required'
		}
	};
  
	$('#infoForm').validate(validationOptions);
	$('#shareWithFriend').validate(validationOptions);
	
	
  $('#guestPassForm').ajaxForm({
		success:function(responseString) {
      
      try {
				// yes, eval is evil
        var result = eval('(' + responseString + ')');
        
        if (!result.hasOwnProperty('success') || result.success === false) {
          fadeOutAllFields();
          return;
        }
        
        setLocation(result.locations[0].location);
        
      } catch (error) {
        fadeOutAllFields();
      }

		}
	});
	
	$('#shareWithFriend').submit(function () {
		
		if ($(this).valid()) {
			$(this).ajaxSubmit({
				success:function(responseString) {
			
					try {
        
						$('#shareWithFriendContainer').slideUp();
						$('#shareWithFriendConfirm').slideDown();

		      } catch (error) {
		        fadeOutAllFields();
		      }
			
				}
			});
		}
		
		return false;
	});
	
	function updateGuestName () {
	  
	  $('#guestName').html($('input[name=first_name]').val() + ' ' + $('input[name=last_name]').val() + '<br />' + $('input[name=email]').val() + '<br />' + $('input[name=phone]').val());
    $('#guestName').fadeIn('fast');
	  
		// Update Share Form
		$('input[name=from_first_name]').val($('input[name=first_name]').val());
		$('input[name=from_last_name]').val($('input[name=last_name]').val());
		$('input[name=from_email]').val($('input[name=email]').val());
	
	}
	
	$('input[name=first_name]').bind('change', updateGuestName);
	$('input[name=last_name]').bind('change', updateGuestName);
	$('input[name=email]').bind('change', updateGuestName);
	$('input[name=phone]').bind('change', updateGuestName);
	
	function fadeOutAllFields () {
		$('#mapIt').fadeOut('fast');
	  $('#nearestLocation').fadeOut('fast');
    $('#nearestLocationAddress').fadeOut('fast');
    $('#description').fadeOut('fast');
    $('#guestName').fadeOut('fast');
    $('#barcode').fadeOut('fast');
    $('#printDate').fadeOut();
	}
	
	function saveReceipt () {
		
		$.post("/guest_passes/save_receipt", {
			location:selectClubField.val(),
			first_name:$('input[name=first_name]').val(),
			last_name:$('input[name=last_name]').val(),
			email:$('input[name=email]').val(),
			phone:$('input[name=phone]').val(),
			source:'guest_pass',
			authenticity_token:$('#guestPassForm input[name=authenticity_token]').val()
		}, function (responseString) {
			// ignore response
    });
		
	}
	
	$('#printButton').click(function () {
		if ($('#infoForm').valid()) {
			// Save it to the backend
			printedPass = true;
		  saveReceipt();
		  $('body').append('<iframe src="/guest_passes/complete" width="1" height="1"></iframe>');
			$.jPrintArea($('#right'));
		}
	  
	  this.blur();
	  return false;
	});
  

	// Link Hijacking
	$('#header a, #navigation *, #subnavigation a, #footer a.footerlinks').click(function () {
		if (printedPass == false) {
			openPrintGuestPassLightbox();
			hijackHREF = $(this).attr('href');
			this.blur();
			return false;
		} else {
			return true;
		}
	});
	
	
	$('#printGuestPassLightboxNoThanksButton').click(function () {
		if (hijackHREF.length > 0) {
			window.location = hijackHREF;
		} else {
			closePrintGuestPassLightbox();
			this.blur();
			return false;
		}
	});

	

});