$(document).ready(function(){
	
	//Hide Errors DIV on all FORMS
	$('#form-errors').hide();
	
	//Show Required
	$('td.require').prepend('* ');

	//Search Form
	$("input[name='keywords']").focus(function(){
		var fieldval = "Search";
		if(this.value == fieldval)
		$(this).val('');
	}).blur(function(){
		if(this.value == '')
		$(this).val("Search"); 
	});

	$('.search-submit').mouseover(function(){
		$(this).addClass("search-submit-hover");
	}).mouseout(function() {
		$(this).removeClass("search-submit-hover");
	});

	/////////////////////////////Start Referral Form
	//Show hide client ID field
	$("select[name='referrer_i_am']").change(function(){
		if ($(this).val() != "a client"){
			$('tr#my_client_id').hide();
		}else{
			$('tr#my_client_id').show();
		}
	});

	//Change company name
	$("select[name='referrer_i_am']").change(function(){
		if ($(this).val() == "an accounting partner"){
			$('td#my_company').text('Accounting Firm:');
		}else{
			$('td#my_company').text('Company Name:');
		}
	});

	//Show hide number of employees field
	$("select[name='referring_type']").change(function(){
		if ($(this).val() != "a new client"){
			$('tr#referral_number_employees').hide();
		}else{
			$('tr#referral_number_employees').show();
		}
	});

	//Change information of the company being referred
	$("select[name='referring_type']").change(function(){
		if ($(this).val() == "a new accounting partner"){
			//$('h3#referral-heading').text('3. Referred Accounting Firm\'s Information');
			$('td#referral_company').text('Accounting Firm:');
		}else if($(this).val() == "a new bank or business partner"){
			//$('h3#referral-heading').text('3. Referred Bank or Business Partner\'s Information');
			$('td#referral_company').text('Company:');
		}else{
			//$('h3#referral-heading').text('3. Referred Client\'s Information');
			$('td#referral_company').text('Company:');
		}
	});
	
	//Refferral form Validation
	$("#referral-form").RSV({
		displayType: "display-html",
		errorTextIntro: "<h3>Please fix the following errors.</h3>",
		errorFieldClass: "error",
		errorHTMLItemBullet: "&ordm; ",
		errorTargetElementId: "form-errors",
		rules: [
		"required,first_name,Please enter your first name.",
		"required,last_name,Please enter your last name.",
		"required,company,Please enter your company\'s or firm\'s name.",
		"required,phone,Please enter your phone number.",
		"required,email,Please enter your email address.",
		"valid_email,email,Please enter a valid email address.",
		"required,zip,Please enter your ZIP.",
		"if:referrer_i_am=a client,required,client_id,Please enter your client ID.",
		"required,referral_first_name,Please enter the referral\'s first name.",
		"required,referral_last_name,Please enter the referral\'s last name.",
		"required,referral_title,Please enter the referral\'s title.",
		"required,referral_phone,Please enter the referral\'s phone number.",
		"required,referral_last_name,Please enter the referral\'s last name.",
		"required,referral_email,Please enter the referral\'s email address.",
		"required,referral_company,Please enter the referral\'s company or firm name.",
		"required,referral_zip,Please enter the referral\'s ZIP code.",
		"if:referring_type=a new client,required,referral_number_of_employees,Please enter the refferal\'s number of employees(a range is fine).",
		"required,referral_approval,Please confirm that you spoken to this contact and he/she is expecting a call from a CompuPay representative."
		]
	});
	//////////////////////////////////End Referral Form

	//Training Landing Page Filtering Dropdowns
	$('#training-filter select').change(function(){
		if ($(this).val() != ""){
			window.location = ($(this).val());
		}
		return false;
	});
	
	//Training Registration Form & Validation
	$('#student-names, #training-registration-wrap').hide();
	$('#reg_btn a').click(function(){
		$('#training-registration-wrap').slideToggle();
		return false;
	});

	//Training Val
	$("#training-registration").RSV({
		displayType: "display-html",
		errorTextIntro: "<h3>Please fix the following errors.</h3>",
		errorFieldClass: "error",
		errorHTMLItemBullet: "&ordm; ",
		errorTargetElementId: "form-errors",
		rules: [
		"required,first_name,Please enter your first name.",
		"required,last_name,Please enter your last name.",
		"required,email,Please enter your email address.",
		"valid_email,email,Please enter a valid email address.",
		"required,address,Please enter your address.",
		"required,city,Please enter your city.",
		"required,state,Please enter your state.",
		"required,zip,Please enter your ZIP.",
		"required,phone,Please enter your phone.",
		"required,train_paytype,Please select a payment method."
		]
	});
	
	//Background Screening Enrollment Val
	$("#background-screening-enrollment").RSV({
		displayType: "display-html",
		errorTextIntro: "<h3>Please fix the following errors.</h3>",
		errorFieldClass: "error",
		errorHTMLItemBullet: "&ordm; ",
		errorTargetElementId: "form-errors",
		rules: [
		"required,company,Please enter your company name.",
		"required,client_id,Please enter your compuPay account number.",
		"required,address,Please enter your address.",
		"required,city,Please enter your city.",
		"required,state,Please enter your state.",
		"required,zip,Please enter your ZIP.",
		"required,first_name,Please enter your first name.",
		"required,last_name,Please enter your last name.",
		"required,title,Please enter your title.",
		"required,email,Please enter your email address.",
		"valid_email,email,Please enter a valid email address.",
		"required,phone,Please enter your phone number.",
		"required,fax,Please enter your fax.",
		"required,2nd_address,Please enter your address.",
		"required,2nd_city,Please enter your city.",
		"required,2nd_state,Please enter your state.",
		"required,2nd_zip,Please enter your ZIP."
		]
	});
	
	//Show if bringing students
	$('#bringing_students').click(function(){
		if(this.checked){
			$('#student-names').slideDown('slow');	
		}else{
			$('#student-names').slideUp('slow');	
		}
	});

	
	//Wizard Results Form Validation
	$("#wizard-results-form").RSV({
		displayType: "display-html",
		errorTextIntro: "<h3>Please fix the following errors.</h3>",
		errorFieldClass: "error",
		errorHTMLItemBullet: "&ordm; ",
		errorTargetElementId: "form-errors",
		rules: [
		"required,company,Please enter your company name.",
		"required,first_name,Please enter your first name.",
		"required,last_name,Please enter your last name.",
		"required,zip,Please enter your company\'s ZIP.",
		"required,phone,Please enter your phone number.",
		"required,email,Please enter your email address.",
		"valid_email,email,Please enter a valid email address.",
		"required,how_you_heard,Please enter your how you hear about CompuPay.",
		"if:how_you_heard=Other,required,how_you_heard_other,Please enter Other."
		
		]
	});
	
	//Generic How did you hear about us
	$('tr.how_you_heard_other').hide();
	$("select[name='how_you_heard']").change(function(){
		if ($(this).val() == "" || $(this).val() == "Search Engine" || $(this).val() == "Yellow Pages" || $(this).val() == "News Article"){
			$('tr.how_you_heard_other').hide();
		}else{
			$('tr.how_you_heard_other').show();
			$('td#other_text').text($(this).val());
		}
	});
	
	//Contact Form Validation
	$("#contact-form").RSV({
		displayType: "display-html",
		errorTextIntro: "<h3>Please fix the following errors.</h3>",
		errorFieldClass: "error",
		errorHTMLItemBullet: "&ordm; ",
		errorTargetElementId: "form-errors",
		rules: [
		"required,first_name,Please enter your first name.",
		"required,last_name,Please enter your last name.",
		"required,company,Please enter your company name.",
		"required,zip,Please enter your ZIP.",
		"required,email,Please enter your email address.",
		"valid_email,email,Please enter a valid email address.",
		"required,how_you_heard_other,Please enter how did you hear about CompuPay."
		]
	});
	
	//Change or show the other field...how they heard.
	$('tr#partnering_options').hide();
	$("select[name='partnering_options[]']").change(function(){
		if ($(this).val() == "Other"){
			$('tr#partnering_options').show();
		}else{
			$('tr#partnering_options').hide();
		}
	});
	
	//Request a Meeting Validation
	$("#meeting-request-form").RSV({
		displayType: "display-html",
		errorTextIntro: "<h3>Please fix the following errors.</h3>",
		errorFieldClass: "error",
		errorHTMLItemBullet: "&ordm; ",
		errorTargetElementId: "form-errors",
		rules: [
		"required,first_name,Please enter your first name.",
		"required,last_name,Please enter your last name.",
		"required,email,Please enter your email address.",
		"valid_email,email,Please enter a valid email address.",
		"required,zip,Please enter your ZIP.",
		"required,phone,Please enter your phone.",
		"required,company,Please enter your firm name."		
		]
	});
	
	//Request a Quote Validation
	$("#quote-request-form").RSV({
		displayType: "display-html",
		errorTextIntro: "<h3>Please fix the following errors.</h3>",
		errorFieldClass: "error",
		errorHTMLItemBullet: "&ordm; ",
		errorTargetElementId: "form-errors",
		rules: [
		"required,first_name,Please enter your first name.",
		"required,last_name,Please enter your last name.",
		"required,company,Please enter your company name.",
		"required,zip,Please enter your ZIP.",
		"required,email,Please enter your email address.",
		"required,number_of_employees,Please enter the number of employees.",
		"valid_email,email,Please enter a valid email address."
		]
	});
	
	//Insights and Innovations and eNews
	$("#insights-innovations, #enews-form").RSV({
		displayType: "display-html",
		errorTextIntro: "<h3>Please fix the following errors.</h3>",
		errorFieldClass: "error",
		errorHTMLItemBullet: "&ordm; ",
		errorTargetElementId: "form-errors",
		rules: [
		"required,first_name,Please enter your first name.",
		"required,last_name,Please enter your last name.",
		"required,email,Please enter your email address.",
		"valid_email,email,Please enter a valid email address."
		]
	});
	
	//Submit a Question and eNews
	$("#submit-question").RSV({
		displayType: "display-html",
		errorTextIntro: "<h3>Please fix the following errors.</h3>",
		errorFieldClass: "error",
		errorHTMLItemBullet: "&ordm; ",
		errorTargetElementId: "form-errors",
		rules: [
		"required,first_name,Please enter your first name.",
		"required,last_name,Please enter your last name.",
		"required,company,Please enter your company name.",
		"required,client_id,Please enter your client ID.",
		"required,zip,Please enter your ZIP.",
		"required,comment,Please enter your message."
		]
	});

	//Stripe and Hover Table
	$('.compupay_table tr:odd').addClass("alt");
	$('.compupay_table tbody tr').mouseover(function(){
		$(this).addClass("over");
	}).mouseout(function(){
		$(this).removeClass("over");
	});

	//li regisration hovers
	$('#training ul li').mouseover(function(){
		$(this).addClass("over");
	}).mouseout(function() {
		$(this).removeClass("over");
	});

	//Valid way to open links in new window
	$("a[@rel='external']").click(function(){window.open(this.href); return false;});
	
	// WIZARD START
	
	// disable the enter key
	$("#wizard").keypress(function(e) {
		if (e.which == 13)
		return false;
	});

	// hide the steps
	$("#step-2,#step-3,#step-4,#last-step").hide();
	$("#step-2 select,#step-3 select,#step-4 select").css({ visibility: "hidden" });
	
	// hide the errors
	$(".error-overlay,.warn-overlay,.success-overlay").hide();
		
	// make initial step active
	$("#step-counter li.step-1").addClass("act");
	
	// move us forward
	// step one
	$("#step-1-button").click(function(){
		// var employee
		var employee = $("#employee_quanity").val();
	

		// check employee-quanity for errors
		if(employee == "" || employee == "0"){
			$(".error-overlay").fadeIn("slow");
			setTimeout('$(".error-overlay").fadeOut("slow");', 2000);
		}
		else
		{
			// check employee count, and remove options from step two as needed 
			if(employee >= 251){
				$("#process_choice option[value='phone']").remove();
				$("#process_choice option[value='fax']").remove();
			}
			else{
				$("#process_choice option[value='phone']").remove();
				$("#process_choice option[value='fax']").remove();
				$('<option value="fax">Fax</option><option value="phone">Phone</option>').insertAfter("#process_choice option[value='']");
			}
		// hide step one
		$("#step-1").hide();
		// show step two
		$("#step-2").show();
		$(".error-overlay").css({ visibility: "hidden" });
		$("#step-2 select").css({ visibility: "visible" });
		
		// wrangle the nav highlight
		$("#step-counter li.step-1").removeClass("act");
		$("#step-counter li.step-2").addClass("act");
		$("#employee_quanity").focus();
		return false;
		}
	});
	
	// step two
	$("#step-2-button").click(function(){
		// var process
		var process = $("#process_choice").val();  
		// check value of process for errors
		if(process == ""){ 
			$("#step-2 select").css({ visibility: "hidden" });
			$(".error-overlay").css({ visibility: "visible" }).show();
			setTimeout('$(".error-overlay").fadeOut("slow"), $("#step-2 select").css({ visibility: "visible" });', 2000);
			$("#process_choice").focus();
		}
		else
		{
		// hide step two
		$("#step-2").hide();
		// show step three
		$("#step-3").show();
		// check value of process and determine the need for step 3
			if(process == "fax" || process == "phone"){
				$("#step-3 select").css({ visibility: "hidden" });
				$(".warn-overlay").css({ visibility: "visible" }).fadeIn("slow");
				setTimeout('$("#step-3").hide(), $("#step-4").show(), $("#step-4 select").css({ visibility: "visible" }), $(".error-overlay").css({ visibility: "hidden" }), $("#step-counter li.step-3").removeClass("act").removeClass("off"), $("#step-counter li.step-last").addClass("act");', 1500);
			}
			else{
				$("#step-3 select").css({ visibility: "visible" });
				$(".warn-overlay, .error-overlay").css({ visibility: "hidden" });
			}
		
		// wrangle the nav highlight
		$("#step-counter li.step-2").removeClass("act");
		// determine the need for nav highlight on step 3
			if(process == "fax" || process == "phone"){
				$("#step-counter li.step-3").addClass("off");
			}
			else{
				$("#step-counter li.step-3").addClass("act");
			}
		return false;
		}
	});
	
	$("#back-2-button").click(function(){
		// hide step one
		$("#step-2").hide();
		// show step two
		$("#step-1").show();
		
		// wrangle the nav highlight
		$("#step-counter li.step-2").removeClass("act");
		$("#step-counter li.step-1").addClass("act");
		return false; 
	});
	
	// step three
	$("#step-3-button").click(function(){
		// hide step 3
		$("#step-3").hide();
		$(".error-overlay").css({ visibility: "hidden" });
		// show step 4
		$("#step-4").show();
		$("#step-4 select").css({ visibility: "visible" });
		
		// wrangle the nav highlight
		$("#step-counter li.step-3").removeClass("act").removeClass("off");
		$("#step-counter li.step-last").addClass("act");
		return false; 
	});
	
	$("#back-3-button").click(function(){
		// hide step one
		$("#step-3").hide();
		// show step two
		$("#step-2").show();
		
		// wrangle the nav highlight
		$("#step-counter li.step-3").removeClass("act").removeClass("off");
		$("#step-counter li.step-2").addClass("act");
		return false; 
	});
	
	// step four
	$("#last-step-button").click(function(){
		//var after
		var after = $("#after_payroll_choice").val();  
		// check value of after for errors
		if(after == ""){  
			$(".error-overlay").css({ visibility: "visible" }).show();
			$("#step-4 select").css({ visibility: "hidden" });
			setTimeout('$(".error-overlay").fadeOut("slow"), $("#step-4 select").css({ visibility: "visible" });', 2000); 
			$("#after_payroll_choice").focus(); 
		}
		else
		{
		// hide step 4
		$("#step-4").hide();
		// show last step
		$("#last-step").show();
		$(".success-overlay").fadeIn("slow");
		// submit form
		setTimeout("$('#wizard').submit();", 2000);
			
		// wrangle the nav highlight
		$("#step-counter li.step-last").removeClass("act");
		return false; 
		}
	});
	
	$("#back-last-button").click(function(){
		var process = $("#process_choice").val();  
		// hide step one
		$("#step-4").hide();
		// show step two
		$("#step-3").show();
		
		// wrangle the nav highlight
		$("#step-counter li.step-last").removeClass("act");
		if(process == "fax" || process == "phone"){
			$("#step-counter li.step-3").addClass("off");
		}
		else{
			$("#step-counter li.step-3").addClass("act");
		}
		return false; 
	});
	
	// close error
	$(".close-error").click(function(){
		$(".error-overlay").fadeOut("slow").css({ visibility: "hidden" });
	});
	
	
	$("#solution-finder a#step-1-button").attr({ onClick: "javascript:pageTracker._trackPageview('/wizard/step-one'); return false;" });
	$("#solution-finder a#step-2-button").attr({ onClick: "javascript:pageTracker._trackPageview('/wizard/step-two'); return false;" });
	$("#solution-finder a#step-3-button").attr({ onClick: "javascript:pageTracker._trackPageview('/wizard/step-three'); return false;" });
	$("#solution-finder a#last-step-button").attr({ onClick: "javascript:pageTracker._trackPageview('/wizard/step-four'); return false;" });
	
	// WIZARD END
	
	
	// =========================================================================
	// = HIRE ACT CALCULATOR FUNCTIONS                                         =
	// =========================================================================
	
	// Make form controls pretty if not IE
	if (!$.browser.msie) {
		$("table.transform").jqTransform();
	}
	
	
	// Bindings
	$('table.transform input').keyup(calculateHIREAct);
	$("select[name='emp_hire_month']").change(calculateHIREAct);
	$("select[name='type_of_pay']").change(function() {		
		
		// Hide some form controls that aren't needed based on the selection
		//alert($("input[name='hours_week']").parent().parent().parent().);
		switch($(this).val()) {
			
			case 'hourly':
				$("label[for='hourly_rate']").html('Hourly Rate:');
				$("input[name='hours_week']").val('0');
				$("input[name='hourly_rate']").val('0');
				
				$("label[for='hours_week']").show();
				$("input[name='hours_week']").show();
				$("input[name='hours_week']").parent().parent().parent('div').show();
				
				$("input[name='hourly_rate']").focus();
				$("input[name='hourly_rate']").select();
			break;
			
			case 'salary':
				$("input[name='hours_week']").val('0');
				$("input[name='hourly_rate']").val('0');
				$("label[for='hourly_rate']").html('Salary:');
				
				$("label[for='hours_week']").hide();
				$("input[name='hours_week']").hide();
				$("input[name='hours_week']").parent().parent().parent('div').hide();
				
				$("input[name='hourly_rate']").focus();
				$("input[name='hourly_rate']").select();
			break;
		}
		
		// Set values if needed
		if ($("input[name='hourly_rate']").val() == "") { $("input[name='hourly_rate']").val('$0.00'); }
		if ($("input[name='hours_week']").val() == "") {  $("input[name='hours_week']").val('0'); }
		
		// Recalculate
		calculateHIREAct();
		
	}).change();
 

});


/**
 * HIRE Act Calculator Calculation Function
 * Validates and Calculates the values in the HIRE Act Calculator form.
 *
 * @return void
 * @author Jesse Bunch
 **/
function calculateHIREAct() {
	
	// Get our data
	var intHourlyRate = $("input[name='hourly_rate']").val();
	var intHoursPerWeek = $("input[name='hours_week']").val();
	var intMonthValue = $("select[name='emp_hire_month']").val();
	var objTotal = $("div#calc-bottom-right");
	
	// Remove dollar sign
	intHourlyRate = intHourlyRate.toString().replace(/\$|\,/g,'');
	
	// Validation
	$("input").css('color', '#808080');
	var isError = false;
	if (isNaN(intHourlyRate)) { $("input[name='hourly_rate']").css('color', 'red'); isError = true; }
	if (isNaN(intHoursPerWeek)) { $("input[name='hours_week']").css('color', 'red'); isError = true; }
	if (countDecimals(intHourlyRate, '.') > 4) { $("input[name='hourly_rate']").css('color', 'red'); isError = true; }
	if (countDecimals(intHoursPerWeek, '.') > 0) { $("input[name='hours_week']").css('color', 'red'); isError = true; }
	

	// See which calculation to perform
	switch ($("select[name='type_of_pay']").val()) {
		
		case 'hourly':
		
			// Calculate SS Tax Credit
			var intSSCredit = ((intHourlyRate*intHoursPerWeek*52) / 12)*(intMonthValue)*(.062);
			if (intSSCredit > 6621.60) { intSSCredit = 6621.60; }
			$("#ssTaxCredit").html(formatCurrency(intSSCredit));
			
			// Calculate Bus Tax Credit
			var intBusCalc = (intHourlyRate * intHoursPerWeek * 52);
			if (intBusCalc > 16139.00) {
				var intBusCredit = 1000;
			} else {
				var intBusCredit = ((intHourlyRate * intHoursPerWeek * 52) * 0.062);
			}
			$("#busTaxCredit").html(formatCurrency(intBusCredit));
			
		
		break;
		
		case 'salary':
		
			// Calculate SS Tax Credit
			var intSSCredit = ((intHourlyRate / 12) * (intMonthValue) * (.062));
			if (intSSCredit > 6621.60) { intSSCredit = 6621.60; }
			$("#ssTaxCredit").html(formatCurrency(intSSCredit));
			
			
			// Calculate Bus Tax Credit			
			if (intHourlyRate > 16139.00) {
				var intBusCredit = 1000;
			} else {
				var intBusCredit = (intHourlyRate * 0.062);
			}
			$("#busTaxCredit").html(formatCurrency(intBusCredit));
		
		break;
		
	}
	
	// Total everything up
	var intTotal = (intBusCredit + intSSCredit);
	objTotal.html(formatCurrency(intTotal, true));
	
}


/**
 * Formats decimals as currency
 *
 * @return void
 * @author Jesse Bunch
 **/
function formatCurrency(strValue, boolRound) {
	if (boolRound === undefined) {
		boolRound = false;
	}
	if (isNaN(strValue)) { return '$0.00'; }
	strValue = strValue.toString().replace(/\$|\,/g,'');
	var dblValue = parseFloat(strValue);

	var blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	var intCents = dblValue%100;
	var strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
		if (boolRound) {
			return (((blnSign)?'':'-') + '$' + dblValue);
		} else {
			return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
		}
	
}


/**
 * Returns the number of decimal places in a float
 *
 * @param x The float to count
 * @param dec_sep The decimal separator (usually a .)
 * @return integer The number of decimal places
 * @author Jesse Bunch
 **/
function countDecimals(x, dec_sep)
{
	var tmp=new String();
	tmp=x;
	if (tmp.indexOf(dec_sep)>-1)
		return tmp.length-tmp.indexOf(dec_sep)-1;
	else
		return 0;
}


// add any other non-jquery js here, including swf object