var finishing = 0;
var vol = {};
$(function()
{
 	$('nav ul').hover(  
	   function() {  
		  $(this).addClass('hovered');     /* On hover add the class 'hovered' and apply the hovered styles */ 
	   }, function() {  
		  $(this).removeClass('hovered');  /* On mouseout remove the class 'hovered' and reset the styles   */ 
	   }  
	);  
  
	if ($('.home_runs_scroller').length)
	{
		$('.home_runs_scroller').SetScroller({	velocity: 	 90,
											direction: 	 'horizontal',
											startfrom: 	 'right',
											loop:		 'infinite',
											movetype: 	 'linear',
											onmouseover: 'pause',
											onmouseout:  'play',
											onstartup: 	 'play',
											cursor: 	 'pointer'
										});
	}
  
	$('a.external').each(function(){
		$(this).attr('target', '_blank');
	});
  
	if ($('#contact_form').length)
	{
		$("#contact_form").validationEngine()
		$('#Phone').coymask("(999)999-9999");
	}
  
	if ($('#tryout_form').length)
	{
		$("#tryout_form").validationEngine()
	}  
  
 
  
    if ($('#signin_form').length > 0)
	{
		$("#signin_form").validationEngine()
	}    
  
    if ($('#last_year_form').length > 0)
	{
		$("#last_year_form").validationEngine()
	}   
  
    if ($('#payment_form').length > 0)
	{
		$("#payment_form").validationEngine()
		//$('#address_num').coymask("9999999999");
		//$('#zip').coymask("99999-9999");  
	}    
  
    if ($('.back_button').length > 0)
	{
		$(".back_button").click(function() {
			window.location.href = $(this).attr('title');
		});
	}    
  
    if ($('.finish_reg').length > 0)
	{
		$(".finish_reg").click(function() {
			window.location.href = '/register-finish';
		});
	}    
  
    if ($('#contacts_form').length > 0)
	{
		$("#contacts_form").validationEngine();
		$("#name_last_0").focus();
		
		$('#home_phone_0').coymask("(999)999-9999");
		$('#home_phone_1').coymask("(999)999-9999");
		$('#work_phone_0').coymask("(999)999-9999");
		$('#work_phone_1').coymask("(999)999-9999");  

	}
	
    if ($('#player_form').length > 0)
	{
		$("#player_form").validationEngine({success: verifyAllergies})
		$("#name_last").focus();
		$('#home_phone').coymask("(999)999-9999");
	}	
	
    if ($('#finish_form').length > 0)
	{
		$("#finish_form").validationEngine({success: verifyVolunteerOptions});
		$(".buyout").click(function(){
			if ($(this).val() == 0)
			{
				delete(vol[$(this).attr('title')]);
				$('#right_col').load('/cart?finish='+finishing+'&buyout=0&player_id='+$(this).attr('title'));
			}
			else
				vol[$(this).attr('title')] = $(this).val();
				
			var num = 0;
			for (n in vol)
			{
				if (vol[n] == 1 || vol[n] == 2)
					num++;
			}
			if (num > 2 && $(this).val() != 0)
			{
				alert("Only two players are required for the volunteer option");
				$("input[name='"+$(this).attr('name')+"']:eq(0)").attr('checked', 'checked');
				delete(vol[$(this).attr('title')]);
				$('#right_col').load('/cart?finish='+finishing+'&buyout=0&player_id='+$(this).attr('title'));
			}
			
			if (num <= 2 && $(this).val() != 0)
			{
				$('#right_col').load('/cart?finish='+finishing+'&buyout='+$(this).val()+'&player_id='+$(this).attr('title'));
			}
		});
	}	
	
    if ($('#create_form').length > 0)
	{
		$("#create_form").validationEngine({
			unbindEngine:false,
			success: function() {
				if (verifyPassword())
				{
					$('#create_form').unbind('submit');
					$('#create_form').submit();
				}
			}
		});
	}
	
	
	$('#user_password').blur(verifyPassword);
	$('#verify_password').blur(verifyPassword);
  
	$('#right_col').load('/cart?finish='+finishing);
	
	if ($('#terms_conditions').length > 0)
	{
		$("#terms_conditions[rel]").overlay({mask: '#000'});
		$("#terms").bgiframe();
	}	
  
	if ($('.print').length > 0)
	{
		$(".print").click(function(){ window.print(); });
	}
	
	if ($('.sign_out').length > 0)
	{
		$(".sign_out").click(function(){ window.location.href = '/sign-out' });
	}	
	
	if ($('.played_last_year').length > 0)
	{
		$(".played_last_year").click(function(){
			var val = parseInt($("input[name='played_last_year']:checked").val());
			if (val > 0)
			{
				$("#allstar").attr('disabled', false);
			}
			else
			{
				$("#allstar option[value='0']").attr('selected', 'selected');
				$("#allstar").attr('disabled', true);
				
			}
			
			if  (val == 1)
			{
				$("#last_team").attr('disabled', false);
			}
			else
			{
				$("#last_team").attr('disabled', true);
			}
			
		});
	}
  
});

function checkJerseyNumbers()
{
	if (isNaN(parseInt($('#shirt_number').val())))
	{
		return true;
	}

	if (isNaN(parseInt($('#shirt_number_alt').val())))
	{
		return true;
	}
	
	if (parseInt($('#shirt_number_alt').val()) == parseInt($('#shirt_number').val()))
	{
		return true;
	}
	return false;
}

function loadGames()
{
	if ($('#division_id').val() == '')
	{
		alert("Please select a division");
		return;
	}
	
	$.post("/load-games", { "division_id": $('#division_id').val() },
		function(data){
			$('#game_id').html(data);
		});
}

function verifyAllergies()
{
	if ($("#player_form").validationEngine({returnIsValid:true}))
	{
		if ($('input:radio[name=has_limitations]:checked').val() == 1)
		{
			if ($('#limitations').val() == '')
			{
				$.validationEngine.buildPrompt("#limitations","Please tell us about the limitations","error");
				$("#player_form").validationEngine({success: verifyAllergies})
				return false;
			}
		}
		
		if ($('input:radio[name=is_allergic]:checked').val() == 1)
		{
			if ($('#allergic_to').val() == '')
			{
				$.validationEngine.buildPrompt("#allergic_to","Please tell us about the allergies","error");
				$("#player_form").validationEngine({success: verifyAllergies})
				return false;
			}
		}		
		$("#player_form").submit();
		return true;
	}
	$("#player_form").validationEngine({success: verifyAllergies})
	return false;
}

function wn_reload()
{
	
}

function verifyVolunteerOptions()
{
	/*if ($("#finish_form").validationEngine({returnIsValid:true}))
	{
		var num = 0;
		for (n in vol)
		{
			if (vol[n] == 1 || vol[n] == 2)
				num++;
		}
		
		if (num < min_fundraiser)
		{
			alert("Please select "+min_fundraiser+" volunteer or buy-out options");
			$("#finish_form").validationEngine({success: verifyVolunteerOptions})
			return false;
		}
		else
		{
			$("#finish_form").submit();
			return true;
		}
		
	}
	return false;*/
	$("#finish_form").submit();
	return true;
}

function askForSure()
{
	return confirm('Are you sure you want to add another player?');
}

function verifyPassword()
{
	var pass = $('#user_password').val();
	var verify = $('#verify_password').val();
	if (pass.length >= 6 && pass != '' && verify == '')
	{
		$('#verify_bad').show();
		$('#verify_good').hide();
		$('#password_bad').hide();
		$('#password_good').show();
		$('#password_message').html('');
		$('#verify_message').html('Please verify your password');
		return false;
	}

	if (pass.length < 6 && pass != '')
	{
		$('#password_bad').show();
		$('#password_good').hide();
		$('#password_message').html('The password must be at least 6 characters');
		$('#verify_message').html('');
		return false;
	}
	
	if (pass != '' && verify != pass)
	{
		$('#verify_bad').show();
		$('#verify_good').hide();
		$('#password_message').html('');
		$('#verify_message').html('The passwords do not match');
		return false;
	}

	if (pass != '' && verify == pass)
	{
		$('#verify_bad').hide();
		$('#password_bad').hide();
		$('#verify_good').show();
		$('#password_good').show();
		$('#password_message').html('');
		$('#verify_message').html('');
		return true;
	}
	
	return false;
}

 function doCheckCreditCard()
 {
	var card_num = $('#card_number').val();
	var card_type = $('#card_type').val();
	var val = checkCreditCard(card_num, card_type);
	return (val ? false : true);
 }
 
 
function checkCreditCard (cardnumber, cardname) {
     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "305, 36, 38, 54,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,622,64,65",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "16", 
               prefixes: "35",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334, 6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "12,13,14,15,16,18,19", 
               prefixes: "5018,5020,5038,6304,6759,6761",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913,4508,4844",
               checkdigit: true};
  cards [12] = {name: "LaserCard", 
               length: "16,17,18,19", 
               prefixes: "6304,6706,6771,6709",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
  
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}
