$().ready(function() {
	update_fees();
	tabbed_form();
	payment_bits();
	
	$('body').append('<div id="dialog"></div>');
	$('.location').click(function(e) {
			var url = $(this).attr('href') + '&silent=1';
			var options = { 
				modal: true,
				height: 500,
        width: 500,
        autoOpen: false,
        title: "Choose A Start Date" 
			}
			$("#dialog").load(url);
			$("#dialog").dialog(options);
			$("#dialog").dialog('open');
			
			e.preventDefault();
//			return false;
	});
	

	// Dec. 19, 2011 - Something of a hack - If the map page,
	// bail at this point. The reason for bailing is that a bunch of
	// the code below doesn't apply to the course_location.php page
	if(document.URL == 'http://www.contractorsuccess.com/course_location.php')
	{
		return;
	}
	
	// Update Payment amount
	$('input[name=book]').change(update_fees);
	$('input[name=book7]').change(update_fees);
	$('input[name=book_architectural_code]').change(update_fees);
	$('input[name=book_iecc_energy_code]').change(update_fees);
	
	$('input.payment_method').click(function() {
	$('.payment-details').hide();
	var payment_type = $(this).val();
	$('.' + payment_type).show();
	});
	
	// November 30, 2010 - No longer using the "supplement" - the books are now split out
//	$('input[name=supplement]').change(update_fees);

	// Mask input
	$("input.phone").setMask({mask:'(999) 999-9999'});
	$("input#cc_num").setMask({mask:'9999 9999 9999 9999'});
	// Not sure cc_num_print is used for anything
	$("input#cc_num_print").setMask({mask:'9999 9999 9999 9999'});
	
	// April 11, 2011 - Change credit card mask depending on Visa/MasterCard/etc.
	$("input[name=credit_type]").click(function()
	{
		
	
		// If American Express
		if($('input[name=credit_type]:checked').val() == 'American Express')
		{
			$("input#cc_num").setMask({mask:'9999 999999 99999'});
			$("input#cc_num_print").setMask({mask:'9999 999999 99999'});
		}
		else
		{
			$("input#cc_num").setMask({mask:'9999 9999 9999 9999'});
			$("input#cc_num_print").setMask({mask:'9999 9999 9999 9999'});
		}
	});
	
	// November 30, 2010 - adding clicks for back buttons
	$('#requirements_back').click(function()
	{
		$('a[href="#register"]').click();
	});
	
	$('#payment_method_back').click(function()
	{
		$('a[href="#requirements"]').click();
	});
	
	$('#student_information_back').click(function()
	{
		$('a[href="#payment-method"]').click();
	});
	
	$('#confirm_back').click(function()
	{
		$('a[href="#student-information"]').click();
	});
	
	// Hide the email confirmation messages
	$('#email_matched').hide();
	$('#email_unmatched').hide();
	
	// Put listeners on the email and email confirmation text boxes
	$('#email').keyup(update_email_message);
	$('#email_confirmation').keyup(update_email_message);
	$('#email').blur(update_email_message);
	$('#email_confirmation').blur(update_email_message);
	
	// Put a listener on the register button
	$('#register_button').click(function()
	{
//		alert('Payment type: ' + $('input[name=payment_method]:checked').val() );
	
		// If the payment plan
		if($('input[name=payment_method]:checked').val() == 'mail_partial_check')
		{		
				// Scroll to the top of the window
				$(window).scrollTop(0);
		
				// From http://www.queness.com/post/77/simple-jquery-modal-window-tutorial
				
  
   
     		
		  
        // Get the window height and width  
         var winH = $(window).height();  
         var winW = $(window).width();  
        
				        
        // Set the popup window to center
        // Moving it down a bit to accommodate the page height
//        $('#plan_dialog').css('top',  (winH/2-$('#plan_dialog').height()/2) );
//        $('#plan_dialog').css('left', winW/2-$('#plan_dialog').width()/2);
				//$('#plan_dialog').css('left', (maskWidth-$('#plan_dialog').width() ) / 2);
				$('#plan_dialog').css('left', (winW - 800) / 2);  
      
      
      	// Get the screen height and width  
        var maskHeight = $(document).height();  
        var maskWidth = $(window).width();  
      
        // Set height and width to mask to fill up the whole screen  
        $('#mask').css({'width':maskWidth,'height':maskHeight});  
          
        // Transition effect    
				$('#mask').fadeIn(500);   
//         $('#mask').fadeIn(500, function (){
//             // Scroll to the top of the mask
//      				$('#mask').scrollTop(0);
//           }
// 				);      
        $('#mask').fadeTo("fast",0.8);    
      
        // Transition effect  
        $('#plan_dialog').fadeIn(1000); 
		}
		else
		{
			// Just submit the form
			$('form#signup').submit();
		}
	});
	
	
	// For a click on the "Continue" button when viewing the payment schedule
	$('#ps_button').click(function()
	{
		// If the check box has been checked
		if($('#ps_checkbox').attr('checked') )
		{
			// Submit the form
			$('form#signup').submit();
		}
		else
		{
			// Ask the user to check the box
			alert('Please check the checkbox to confirm you have printed the payment plan.');
		}
		
	});
	
	
});


function update_email_message()
{
	$('#email_matched').hide();
	$('#email_unmatched').hide();

	
	// If the emails don't match
	if($('#email').val() != $('#email_confirmation').val() )
	{
		$('#email_unmatched').show();
	}
	// Else if they're not empty
	else if($('#email').val() != '')
	{
		$('#email_matched').show();
	}
}


function update_fees() {

	$('body').data('course-fee', $('#course-fee').text());
	
	$('#registration_fee_text').remove();
	$('#book_text').remove();
	$('#book7_text').remove();
//	$('#supplement_text').remove();
	$('#book_architectural_code_text').remove();
	$('#book_iecc_energy_code_text').remove();
	
	// November 30, 2010 - The supplement is now split out into two optional books
// 	$('body').data('supplement', '<tr id="supplement_text"><td>Supplemental Books </td><td><strong>$55.00</strong></td></tr>');
// 	$('body').data('supplement_amount', 55);
// 	$('#total_fees').before($('body').data('supplement'));

	// There's a new $25 registration fee
	$('body').data('registration_fee', '<tr id="registration_fee_text"><td>Non-refundable registration fee </td><td><strong>$25.00</strong></td></tr>');
	$('body').data('registration_fee_amount', 25);
	$('#total_fees').before($('body').data('registration_fee'));	
		
	if($('input[name=book]:checked').val() == 'yes') {
		$('body').data('book', '<tr id="book_text"><td>8th Edition Commercial Code Book </td><td><strong>$120.00</strong></td></tr>');
		$('body').data('book_amount', 120);
		$('#total_fees').before($('body').data('book'));
	} else {
		$('body').removeData('book');
		$('body').data('book_amount', 0);
		$('#book_text').remove();
	}
	if($('input[name=book7]:checked').val() == 'yes') {
		$('body').data('book7', '<tr id="book7_text"><td>8th Edition Residential Code Book </td><td><strong>$100.00</strong></td></tr>');
		$('body').data('book7_amount', 100);
		$('#total_fees').before($('body').data('book7'));
	} else {
		$('body').removeData('book7');
		$('body').data('book7_amount', 0);
		$('#book7_text').remove();
	}
	
	if($('input[name=book_architectural_code]:checked').val() == 'yes')
	{
		$('body').data('book_architectural_code', '<tr id="book_architectural_code_text"><td>Architectural Access Code Book </td><td><strong>$15.00</strong></td></tr>');
		$('body').data('book_architectural_code_amount', 15);
		$('#total_fees').before($('body').data('book_architectural_code'));
//		alert('aac was checked');
	}
	else
	{
		$('body').removeData('book_architectural_code');
		$('body').data('book_architectural_code_amount', 0);
		$('#book_architectural_code_text').remove();
//		alert('aac was NOOOOOOT checked');
	}
	
	if($('input[name=book_iecc_energy_code]:checked').val() == 'yes')
	{
		$('body').data('book_iecc_energy_code', '<tr id="book_iecc_energy_code_text"><td>2009 IECC Energy Code Book </td><td><strong>$30.00</strong></td></tr>');
		$('body').data('book_iecc_energy_code_amount', 30);
		$('#total_fees').before($('body').data('book_iecc_energy_code'));
	}
	else
	{
		$('body').removeData('book_iecc_energy_code');
		$('body').data('book_iecc_energy_code_amount', 0);
		$('#book_iecc_energy_code_text').remove();
	}
	
	
	
	/*
	// now required...
	if($('input[name=supplement]:checked').val() == 'yes') {
		$('body').data('supplement', '<tr id="supplement_text"><td>Supplemental Books </td><td><strong>$55.00</strong></td></tr>');
		$('body').data('supplement_amount', 55);
		$('#total_fees').before($('body').data('supplement'));
	} else {
		$('body').removeData('supplement');
		$('body').data('supplement_amount', 0);
		$('#supplement_text').remove();
	}
	*/	
	
	// This sets the total on the "Confirm" tab
	$('#total_fees span').text(parseInt($('body').data('course-fee')) + $('body').data('book_amount') + $('body').data('book7_amount') + $('body').data('book_architectural_code_amount') + $('body').data('book_iecc_energy_code_amount') + $('body').data('registration_fee_amount')  );
	
	$('#amount').val($('#total_fees span').text());
	
	$('.course_fees span').text($('#total_fees span').text());
	
	
	// Update the payment schedule values (even if they're not used)
	var payment_1;
	var payment_2;
	var payment_3;
	var payment_4;
	
	payment_1 = 0;
	payment_2 = 0;
	payment_3 = 0;
	payment_4 = 0;
	
	// Base costs for course
	payment_1 += 100;
	payment_2 += 100;
	payment_3 += 70;
	payment_4 += 50;
	
	// Check for each book:
	if($('input[name=book]:checked').val() == 'yes')
	{
		payment_1 += 40;
		payment_2 += 35;
		payment_3 += 25;
		payment_4 += 20;
	}
	
	if($('input[name=book7]:checked').val() == 'yes')
	{
		payment_1 += 30;
		payment_2 += 30;
		payment_3 += 25;
		payment_4 += 15;
	}
	
	if($('input[name=book_architectural_code]:checked').val() == 'yes')
	{
		payment_1 += 5;
		payment_2 += 5;
		payment_3 += 5;
		payment_4 += 0;
	}
	
	if($('input[name=book_iecc_energy_code]:checked').val() == 'yes')
	{
		payment_1 += 10;
		payment_2 += 10;
		payment_3 += 5;
		payment_4 += 5;
	}
	
	// Set the values
	$('.ps_deposit').text(payment_1);
	$('.ps_class1').text(payment_2);
	$('.ps_class2').text(payment_3);
	$('.ps_class3').text(payment_4);
}

function tabbed_form() {
	var $tabs = $("#tabs").tabs({disabled: [1,2,3,4,5,6]});
	$("#tabs legend").css('display', 'none');
	$("#tabs button").click(function() {
		// Hack to get around IE LabelText vs value bug on buttons 
		// http://msdn.microsoft.com/en-us/library/ms535211%28VS.85%29.aspx
		// http://stackoverflow.com/questions/487056/retrieve-button-value-with-jquery
		var label = $(this).text(); 
		$(this).text('');
		var buttonValue = $(this).val();
		$(this).text(label);
		$tab = parseInt(buttonValue);
		// End Hack
		if(validate($tab)) {
			$tabs.tabs('enable', $tab);
			$tabs.tabs('select', $tab);
		}
		return false;
	});
}

function validate($tab) {
	$('form#signup').validate(
	{
		errorPlacement: function(error, element) {
					// If the credit card type radio buttons
					if(element.attr("name") == 'credit_type')
					{
							error.insertBefore(element);
					}
					// Else if the debit/credit radio buttons
					else if(element.attr("name") == 'debit_or_credit')
					{
						error.insertBefore(element);
					}
					// Else if the payment method radio buttons
					else if(element.attr("name") == 'payment_method')
					{
						error.insertBefore(element);
					}
					else
					{
						error.insertAfter(element);
					}
				}
	}
	);
	switch ($tab) {
		case 1: 
			return true;
		break;
		case 2:
			var required = {
				required: true,
				messages: {
					required: 'required'
				}
			};
			$('input[name=book]').rules("add", required);
			$('input[name=book7]').rules("add", required);
//			$('input[name=supplement]').rules("add", required);
			$('input[name=book_architectural_code]').rules("add", required);
			$('input[name=book_iecc_energy_code]').rules("add", required);
			$('input[name=yrsexp]').rules("add", required);
			if(! $("form#signup").valid()) {
				return false;
			}
			return true;
		break;
		case 3:
			var required = {
				required: true,
				messages: {
					required: 'Payment method required<br />'
				}
			};
			$('input[name=payment_method]').rules("add", required);
			if(! $("form#signup").valid()) {
				return false;
			}	
			return true;
		break;
		case 4:
			var required = {
				required: true,
				messages: {
					required: ''
				}
			};
			var required_with_note = {
				required: true,
				messages: {
					required: 'required'
				}
			};
			var email_options = {
				required: function(element) {
					return isOnline();
				},
				messages: {
					required: ''
				}
			};
			var cc_options = {
				required: function(element) {
					return isCC();
				},
				messages: {
					required: ''
				}
			};
			var cc_options_with_note = {
				required: function(element) {
					return isCC();
				},
				messages: {
					required: 'required'
				}
			};
			
			var email_match = {
				equalTo: "#email",
				messages: {
					equalTo: ''
				}
			};
			
// 			var cc_required = {
// 				required: true,
// 				messages: {
// 					required: 'required'
// 				}
// 				,
// 				errorPlacement: function(error, element) {
// 							// This alert works
// 						alert('Hi!');
// 					$('#credit_type_li').append('error');
// 				}
// 			};
			
			$('input[name=last_name]').rules("add", required);
			$('input[name=first_name]').rules("add", required);
			$('input[name=home_phone]').rules("add", required);
			$('input[name=home_address]').rules("add", required);
			$('input[name=home_city]').rules("add", required);
			$('input[name=home_state]').rules("add", required);
			$('input[name=home_zip]').rules("add", required);
			$('input[name=readguarantee]').rules("add", required_with_note);
			
			$('input[name=email]').rules("add", email_options);
			$('input[name=cc_num]').rules("add", cc_options);
			$('#month').rules("add", cc_options_with_note);
			$('#year').rules("add", cc_options_with_note);
			
			// Adding check that email confirmation matches email
			$('#email_confirmation').rules("add", email_match);

			// Adding check on card type and debit or credit
			$('input[name=credit_type]').rules("add", cc_options_with_note);
			$('input[name=debit_or_credit]').rules("add", cc_options_with_note);

			if(! $("form#signup").valid()) {
				return false;
			}
			return true;
		break;
		case 5:
			return true;
		break;
		case 6:
			return true;
		break;
	}
}

function payment_bits() {
	$('.payment-details').hide();
	var payment_type = $('input[name=payment_method]:checked').val();
	$('.' + payment_type).show();
	
	// Now adding this to 'document ready'
// 	$('input.payment_method').click(function() {
// 		$('.payment-details').hide();
// 		var payment_type = $(this).val();
// 		$('.' + payment_type).show();
// 	});
}

function isCC() {
	if(($('input.payment_method:checked').val() == 'credit_card_online')
		|| ($('input.payment_method:checked').val() == 'credit_card_mail')
	) {
		return true;
	}
	return false;
}

function isOnline() {
	if($('input.payment_method:checked').val() == 'credit_card_online') {
		return true;
	}
	return false;
}

