$(function () {
  
  var locations = [];
  
  var selectClassFieldContainer = $('#selectClassField span');
  var selectClassField = selectClassFieldContainer.find('select');
  var selectClubFieldContainer = $('#selectClubField span');
  var selectClubField = selectClubFieldContainer.find('select');
  
  function displayLocation (locationID) {
		
    var location = getLocation(locationID);
		
    $('#nearestLocation').html(location.title);
    $('#nearestLocation').fadeIn('fast');
    
    $('#nearestLocationAddress').html(location.address + '<br />' + location.city + ', ' + location.state + ' ' + location.zip + '<br />' + location.phone);
    $('#nearestLocationAddress').fadeIn('fast');
    
    $('#className').html(selectClassField[0].options[selectClassField[0].selectedIndex].text);
    $('#className').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');
    
  }
  
  function getLocation (locationID) {
    for (var i = 0; i < locations.length; i++) {
      if (locations[i].location_id == locationID) {
        return locations[i];
      }
    }
    return null;
  }
  
  function onSelectFieldClubChange () {
    displayLocation($(this).val());
  };
  
  selectClassField.bind('change', function () {
    
    $.post("/locations_programs/programs", {id:selectClassField.val(), authenticity_token:$('#classPassForm input[name=authenticity_token]').val()}, function (responseString) {
      
      selectClubFieldContainer.html('');
      
      try {
        var result = eval('(' + responseString + ')');
        
        locations = [];
        var clubSelectString = '<select name="pass_receipt[location_id]">';
        
        // Build Select Field
        for (var i in result.locations) {
          locations.push(result.locations[i].location);
          clubSelectString += '<option value="' + result.locations[i].location.location_id + '">' + result.locations[i].location.title + '</option>';
        }
        
        selectClubFieldContainer.html(clubSelectString + '</select>');
        
        selectClubFieldContainer.find('select').bind('change', onSelectFieldClubChange);
        
        $('#selectClubField').show();
        displayLocation(locations[0].location_id);
        
      } catch (error) {
        //failed
      }
      
    });
    
  });
  
  $('#subnavigation').animate({top:0}, 300);
  
	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);

  $('#classPassForm').ajaxForm({
		success:function(responseString) {
      
      try {
        
        var result = eval('(' + responseString + ')');
        
        if (!result.hasOwnProperty('success') || result.success === false) {
          fadeOutAllFields();
          return;
        }
        
        var location = result.locations[0].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');
        
        $('#className').html(selectClassField.val());
        $('#className').fadeIn('fast');
        
        $('#description').html(location.guest_pass_description);
        $('#description').fadeIn('fast');
        
        $('#barcode').fadeIn('fast');
        $('#printDate').fadeIn('fast');
        $('#printButton').fadeIn('fast');
        
      } catch (error) {
        //console.log('failed!');
        fadeOutAllFields();
      }

		}
	});
	
	$('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 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');
	  
	}
	
	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 span select').val(),
			program:selectClassField.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:'class_pass',
			authenticity_token:$('#classPassForm input[name=authenticity_token]').val()
		}, function (responseString) {
      // ignore response
    });
		
	}
	
	$('#printButton').click(function () {
	  
	
		if ($('#infoForm').valid()) {
			saveReceipt();
		  $.jPrintArea($('#right'));
			$('body').append('<iframe src="/class_passes/complete" width="1" height="1"></iframe>');
		}
	  
	  this.blur();
	  return false;
	});
  
});
