/* 
 * jsaction_bind function
 * by Shawn Marincas
 * 
 * Binds javascript events to elements via classname hooks
 * Expects:
 * 	f = Object containing keys paired to functions which will be bound based on the key in the class name
 * 	s = Set of elements to bind up (defaults to whole document)
 * 	b = bind key, what each element's class name will start with to bind to this set of functions (defaults to 'jsaction')
 * 	c = callback function to be run after each bound function runs (defaults to undefined)
 * 	d = class name delimiter - what separates each portion of the classname (defaults to _)
 * Classname:
 * 	Format = [bind key]_[event to bind to]_[function key to bind]
 * example:
  	<script type="text/javascript">
  		jsaction_bind({
  			"test": function() {
  				alert('test');
  			}
  		});
  	</script>
  	<button class="jsaction_click_test">Test</button>
 * 
 * 	This will bind click event of the button labeled Test to run the function found at jsaction_bind['test'] 
 * 	the purpose of this is to separate javascript from HTML while making functions easily resuable, portable and refactorable
 * 	
 * 	Another example is in the Find a Dealer side bar found on the Payment Plan, Payment Calc and Credit App pages
 * 	Here is the function which is passed in a hash to the jsaction_bind function:
  	 "find-dealers": function() {
		$.ajax({
			url: "/MMNA/findDealer.do",
			type: "post",
			data: $(this).closest('form').serialize(),
			dataType: "text",
			success: function(data) {
				eval(data);
				$('.dealer-list').empty();
				$.each(dealerList, function(key,value) {
					$('.dealer-list').append("<p><strong>"+value.name+"</strong> (<a target='_blank' href='"+value.url+"'>link</a>)<br />"+value.address+"<br />"+value.city+","+value.state+" "+value.zip+"<br />"+value.phone+"<br />("+value.miles+" mi)</p>");
				});
			},
			error: function(xhr,status,y) {
				$('.dealer-list').html("Error: "+xhr.status+" "+status);
			}
		});
		return false;
	},
	
 *	And here is the HTML:
 *
	<div class="container dealer-list bottomDotted">
	</div>
	<form class="container jsaction_submit_find-dealers jsaction_init_find-dealers">
		<fieldset>
			<legend>Find More Dealers</legend>
			<p><label for="brpZip" style="display: inline;">Zip Code:</label> <input name="bprZip" id="bprZip" type="text" maxLength="5" style="width: 5em;text-align: center;" value="<%= ownerSiteUser.getZip() %>"/></p>
			<p><button type="button" class="redBtn jsaction_click_find-dealers" id="get-dealers">Submit</button></p>
			<input type="hidden" name="dealerMax" value="3" />
			<input type="hidden" name="radius" value="500" />
			<input type="hidden" name="filterEcom" value="false" />
		</fieldset>
	</form>

 *	The find-dealers function is bound in 3 places:
 *		- the form has a class of "jsaction_submit_find-dealers"
 *		- the form also has a class of "jsaction_init_find-dealers"
 *		- the form button has a class of "jsaction_click_find-dealers"
 *	In this way the same function will run when the page initializes, if the form is submitted or when the button is clicked
 */
function jsaction_bind(f,s,b,c,d) {
	var funcHash = f || jsactions;
	var set = s || document; var $set = set.selector ? set : $(set);
	var bindKey = b || "jsaction";
	var callback = c || undefined;
	var delim = d || "_";

	$set.find("[class*='"+bindKey+"']").each(function() {
		var elmt = $(this);
		$.each(elmt.attr('class').split(' '), function() {
			if(this.match("^"+bindKey+delim)){
				var action_info = this.match(bindKey+delim+"([a-zA-Z0-9\-]+)"+delim+"([a-zA-Z0-9\-]+)");
				var bind = action_info[1];
				var action = action_info[2];
				
				if(funcHash[action]) {
					if(bind == 'init') {
						elmt.each(funcHash[action]);
					} else {
						if(callback) {
							elmt.bind(bind,funcHash[action]).bind(bind,callback);
						} else {
							elmt.bind(bind,funcHash[action]);
						}
					}
				} else {
					throw 'missing '+bindKey+' "' + action + '"';
				}
			}
		});
	});
}

// This function checks is a plain object has any properties
// It's actually taken from the utilities of the core jQuery 1.4.x code
// It should be swapped out for the jQuery call once the site is upgraded from 1.3.1 
function isEmptyObject( obj ) {
	for ( var name in obj ) {
		return false;
	}
	return true;
}

// Creates a modal pop-up, should be replaced with jQuery UI Dialog
function pop_box(pop_msg,add_class) {
	pop_msg = pop_msg.selector ? pop_msg : $(pop_msg);
	var blanket = $('<div id="blanket"></div>');
	var pop = $('<div id="popup" class="container"><div class="mod pop"><button class="jsaction_click_hide-modal bluePopX" type="button">CLOSE</button><div class="inner container"><div class="bd"></div></div></div></div>');
	var scroll_offset = document.all ? document.documentElement.scrollTop : window.pageYOffset;

	jsaction_bind(page_actions,pop);
	pop.find('.bd').append(pop_msg.children());
	if(add_class) {
		pop.find('.pop').addClass(add_class);
	}

	blanket.css({ "width":"100%", "height": $(document).height() });
	$('body').prepend(blanket).find('#blanket').fadeTo(200,.45,function() {
		$('body').prepend(pop).find('#popup').css({ 
			"margin-left": (pop.width()/2 * -1),
			"margin-top": (scroll_offset*.9)
		});
	});
}

// Swaps out modal pop-up with another pop-up, should also be replaced with jQuery UI Dialog
function replace_box(pop_msg) {
	var pop = $('#popup').clone();
	$('#popup').remove();
	
	pop.find('.bd').empty().html(pop_msg);
	jsaction_bind(page_actions,pop);
	
	$('body').prepend(pop).find('#popup').css({ 
		"margin-left": (pop.width()/2 * -1),
		"margin-top": (pop.height()/5 * -4)
	});
}

// Calculate payment estimates
// taken from the core of another payment calculator somewhere else on the site
function calculatePayments(v) {
	if (v.finance.termMonths && typeof(v.finance.apr) != "string") {
		i = (v.finance.apr / 100 / 12);
		var payment = 0;
		if (i) {
			payment = (Math.round((v.totalPrice - v.finance.tradeIn - v.finance.downPayment) / ( ( 1 / i) * ( 1 - Math.pow( 1 / (1+i), v.finance.termMonths))) * 100 ) / 100);			
		} else {
			//Prevent divide by zero for 0% APR offer
			payment = (Math.round((v.totalPrice - v.finance.tradeIn - v.finance.downPayment) / v.finance.termMonths * 100 ) / 100);
		}
		if (payment < 0) {
			return 0;
		}
		return payment;
	} else {
		return "fail";
	}
}

// Taken from somewheres (B&P?), just returns a currency formatted string
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	//return (((sign)?'':'-') + '$' + num + '.' + cents);
	return (((sign)?'':'-') + num + '.' + cents);
}

/*
 * getVehicleWarranty - Calls warranty service, passes results to callback
 * Expects:
 * 	callback - a function to handle the successful AJAX response
 *  vin - Vehicle VIN, required by warranty service
 *  mileage - Vehicle mileage, required by warranty service
 * 
 * Should optionally take an error callback function and have the default error function be better
 */
function getVehicleWarranty(callback,vin,mileage) {
	$.ajax({
		url: "/MMNA/ownerSiteAction.do",
		type: "post",
		dataType: "json",
		data: { "vin": vin, "mileage": mileage || 0, "method":"getWarranty" },
		success: callback,
		error: function(xhr,status,y) {
			alert ("Warranty service is currently having difficulty, please try again later.")
			//alert("Server response error: "+xhr.status+" "+status);
		}
	});
}

//Hash of models with trims and associated prices
//Used in Payment Calculator
//should be replaced with a JSON call or some other non-hardcoded stuff
var specialOffers = {
	"military": 500,
	"loyalty": 500,
	"factory": 2000
}

/*
 * The page_actions hash - this is the main function hash passed to jsactions_bind for the entire site
 */
var page_actions = {
	// prevents default event of element from firing 
	"stop": function() { return false; },
	// will close a modal popup of which the element is contained
	"hide-modal": function() {
		$(this).parents('#popup').remove();
		$('#blanket').fadeTo(200, .01, function() { $(this).remove(); });
		return false;
	},
	// Pops the forgot password dialog box... all the pop_box hooks should be sharing a function, just never got around to it 
	"forgot-pw": function() {
		pop_box($("#forgot-pw").clone(true));
		return false;
	},
	// Sends the Forgot Password request from the pop-up form, bundles up all the form inputs as the data post
	"get-new-pw": function() {
		$.ajax({
			url: "/MMNA/ownerSiteAction.do",
			type: "post",
			data: $(this).closest('form').serialize(),
			success: function(data) {
				if(data == "Success") {
					alert("Your password has been reset and sent to your email.  Thank you.");
					$('.jsaction_click_hide-modal').trigger('click');
				} else {
					alert(data);
				}
			},
			error: function(xhr,status,y) {
				alert(xhr.responseText);
			}
		});
	},
	// Pops the initial Account Delete dialog box... all the pop_box hook functions should be sharing a function, just never got around to it
	"start-account-delete": function() {
		pop_box($('.start-account-delete').clone(true));
		return false;
	},
	// Sends and handles the Account Delete request
	"confirm-account-delete": function() {
		$.ajax({
			url: "/MMNA/ownerSiteAction.do",
			type: "post",
			data: { "method":"deleteAccount" },
			dataType: "text",
			success: function(data) {
				if(data == "Success") {
					alert('Your account has been deleted');
					window.location.href = "/MMNA/jsp/owners-site/index.do";
					//replace_box($('.confirm-account-delete').html());
				} else {
					alert('error deleting account: '+data);
				}
			},
			error: function(xhr,status,y) {
				alert("server error: "+xhr.status+" "+status);
			}
		});
		return false;
	},
	// Redirects user to Owner Site home page after Account Delete
	"finalize-delete": function() {
		window.location.href = '/MMNA/jsp/owners-site/index.do';
	},
	// Pops the initial Vehicle Delete dialog box, will pop a Account Delete box if there is only 1 vehicle tab on the page
	"start-vehicle-delete": function() {
		if($('.tabPage').size() > 1) {
			pop_box($(this).siblings('.start-vehicle-delete').clone(true));
		} else {
			pop_box($(this).siblings('.confirm-account-delete').clone(true));
		}
		return false;
	},
	// Posts the Vehicle Delete request and handles the response, alerts and redirects as necessary
	"confirm-vehicle-delete": function() {
		$.ajax({
			url: "/MMNA/ownerSiteAction.do",
			type: "post",
			data: { "method":"deleteVehicle", "vin": this.name },
			dataType: "text",
			success: function(data) {
				if(data == "Success") {
					alert('Vehicle successfully deleted');
					window.location.href = '/MMNA/jsp/owners-site/vehicle.do';
				} else if (data == "AccountDeleted") {
					alert('Account deleted');
					window.location.href = '/MMNA/jsp/owners-site/index.do';
				} else {
					alert('An error occurred while deleting vehicle: '+data);
				}
			},
			error: function(xhr,status,y) {
				alert("server error: "+xhr.status+" "+status);
			}
		});
	},
	// Posts the Add Vehicle request and handles the response
	"confirm-add-vehicle": function() {
		// AJAX post with VIN for vehicle information
		$.ajax({
			url: "/MMNA/ownerSiteAction.do",
			type: "post",
			data: $('#add_veh_form').serialize(),
			dataType: "text",
			success: function(data) {
				if(data == "Success") {
					alert('Vehicle successfully added');
					window.location.href = '/MMNA/jsp/owners-site/vehicle.do';
				} else {
					if(data == "VINExists") {
						alert('The VIN already exists on this account');
						$('button.jsaction_click_hide-modal').trigger('click');
					}
					else {
						alert('An error occurred while adding vehicle: '+data);
					}
				}
			},
			error: function(xhr,status,y) {
				alert("server error: "+xhr.status+" "+status);
			}
		});
		return false;
	},
	// Pops the technology dialog boxes... all the pop_box hooks should be sharing a function, just never got around to it
	"pop-related": function() {
		pop_box($("#learn-"+this.rel).clone(true),"learnTech");
		return false;
	},
	// Pops the Find Your VIN dialog box... all the pop_box hooks should be sharing a function, just never got around to it
	"find-vin": function() {
		pop_box($("#find-vin").clone(true),"findVin");
		return false;
	},
	// DEPRECATED:  Validates a VIN input using the warranty service... don't think it's still be used
	"validate-vin": function() {
		var dis = this;
		var vin = dis.value;
		if(vin.length == 17) {
			$.ajax({
				url: "/MMNA/ownerSiteAction.do",
				type: "post",
				data: { "vin": vin, "mileage": "0", "method":"getWarranty" },
				dataType: "json",
				success: function(data) {
					if(data.warranty.vehicleInfo.vin == vin) {
						$('#registerModel').text(data.warranty.vehicleInfo.modelYear+" "+data.warranty.vehicleInfo.model);
						$('#registerColor').text(data.warranty.vehicleInfo.exteriorColor);
					} else {
						$(dis).parent('fieldset').triggerHandler('invalid-input',[dis]);
					}
				},
				error: function(xhr,status,y) {
					alert(status);
				}
			});
		} else {
			$(dis).parents('fieldset').triggerHandler('invalid-input',[dis]);
		}
	},
	// This is actually only used on the first Registration image to slide it in on page load
	// There were greater plans to have this function be bound to custom events in the Registration form, but never got it in place
	"reg-slide": function() {
		$('#bodyDiv').css('min-height','532px');
		$(this).parent().css({ height: $(this).height(), width: $(this).width() }).end()
		.add('.reg-slide')
		.each(function() { 
			if($(this).hasClass('vehicle')) {
				$(this).css('top',($(this).height()*-1)+'px');
			} else { 
				$(this).css('right',($(this).width()*-1)+'px');
			}
		});
		$(this).css('display','block').animate({ 'right': 0 }, 1000);
	},
	// Neat utility function which binds a click function to an anchor tag and "daisy-chains" the functionality 
	"link-btn": function() {
		var href = $(this).siblings('a.button-href').attr('href');
		if ($(this).siblings('a.button-href').attr('target') == '_blank') {
			window.open(href,'_blank','height=1000,width=1000');
		} else {
		    location.href = href;
		}
		return false;
	},
	"scroll-link-btn": function() {
		var href = $(this).siblings('a.button-href').attr('href');
		if ($(this).siblings('a.button-href').attr('target') == '_blank') {
			window.open(href,'_blank','height=1000,width=1200,scrollbars=yes,menubar=yes');
		} else {
		    location.href = href;
		}
		return false;
	},
	"hide-gracenote": function () {
		replace_box($('#learn-wireless').html());
	},
	"switch-tab": function() {
		var selected_tab = this.rel;
		$(this).parent().siblings('.tabItem').removeClass('selected').end().addClass('selected');
		
		$('#tabMenuDisplay').find('.tabPage').hide().end().find('[class*="tab-image"]').hide();
		$('[class*="'+selected_tab+'"]').show();
		$('#'+selected_tab).show();
		return false;
	},
	// Shows the Primary Driver text fields when the user selects that they are NOT the primary driver
	"show-primary-driver": function() {
		$('.primaryFirstName').parent().slideDown();
	},
	// Hides the Primary Driver text fields when the user selects that they ARE the primary driver
	"hide-primary-driver": function() {
		$('.primaryFirstName').parent().slideUp();
	},
	// Sets up and binds the Payment Calculator
	"initialize-calc": function() {
		// Hash of 
		var modelImgs = {
				"EclipseKey100046": "/MMNA/images/eclipse_allmodel.jpg",
				"EclipseSpyderKey100047": "/MMNA/images/spyder_allmodel.jpg",
			"EclipseKey100036": "/MMNA/images/eclipse_allmodel.jpg",
			"EclipseSpyderKey100037": "/MMNA/images/spyder_allmodel.jpg",
			"EndeavorKey100038": "/MMNA/images/endeavor_allmodel.jpg",
			"GalantKey100039": "/MMNA/images/galant_allmodel.jpg",
			"GalantKey100049": "/MMNA/images/galant_allmodel.jpg",
			"LancerKey100040": "/MMNA/images/lancer_allmodel.jpg",
			"LancerKey100050": "/MMNA/images/lancer_allmodel.jpg",
			"LancerSportbackKey100033": "/MMNA/images/sportback_allmodel.jpg",
			"LancerSportbackKey100041": "/MMNA/images/sportback_allmodel.jpg",
			"LancerSportbackKey100051": "/MMNA/images/sportback_allmodel.jpg",
			"LancerEvolutionKey100032": "/MMNA/images/evo_allmodel.jpg",
			"LancerEvolutionKey100052": "/MMNA/images/evo_allmodel.jpg",
			"LancerEvolutionKey100043": "/MMNA/images/evo_allmodel.jpg",
			"GalantKey100034": "/MMNA/images/galant_allmodel.jpg",
			"EclipseKey100029": "/MMNA/images/eclipse_allmodel.jpg",
			"EclipseSpyderKey100030": "/MMNA/images/spyder_allmodel.jpg",
			"OutlanderKey100035": "/MMNA/images/outlander_allmodel.jpg",
			"OutlanderKey100042": "/MMNA/images/outlander_allmodel.jpg",
			"OutlanderKey100048": "/MMNA/images/outlander_allmodel.jpg",
			"OutlanderSportKey100044": "/MMNA/images/outlandersport_allmodel.jpg",
			"OutlanderSportKey100053": "/MMNA/images/outlandersport_allmodel.jpg",
			"EndeavorKey100028": "/MMNA/images/endeavor_allmodel.jpg",
			"LancerKey100022": "/MMNA/images/lancer_allmodel.jpg",
			"OutlanderKey100026": "/MMNA/images/outlander_allmodel.jpg"
		};
		jsaction_bind({
			"get-models": function() {
				$.each(modelList, function(k,v){
					$('#model').append('<option value="'+k+'">'+v.modelName+'</option>');
				});
			},
			"get-trims": function() {
				$('.calcResults').slideUp(500);
				var model = modelList[this.value];
				model['modelImg'] = modelImgs[this.value];
				$('#trim').data('model',model).find(':not(:first)').remove();
				$.each(model.trims, function(k,v) {
					var trim = $('<option value="'+v.trimId+'">'+v.trimName+'</option>').data('trim', v);
					$('#trim').append(trim);
				});
			},
			"get-price": function() {
				var model = $(this).data('model');
				var trim = $(this).find(':selected').data('trim');
				var destPrice = model.modelDestPrice; 				
				var price = trim.trimPrice - destPrice;  // destPrice was added in tile controller java code
				$('.car-title').text(model.modelName);
				$('.car-img').attr('src',model.modelImg).show();
				$('#price').val(price);
				$('#destHand').val(destPrice);
				$('.yourPrice .value').text(formatCurrency(price));
				$('.destHand .value').text(formatCurrency(destPrice));
				$('.calcResults').slideDown(500);
			},
			"change-incentive": function() {
				var incentive = 0;
				$('.incentive:checked').each(function() {
					incentive = incentive + parseFloat(this.value);
				});
				$('.ownIncentive .value').text(formatCurrency(incentive));
			},
			"calculate-payment": function() {
				var incentive = 0;
				var payment = 0;
				
				$('.incentive:checked').each(function() {
					incentive = incentive + parseFloat(this.value);
				});

				if(parseInt($("#downpayment").val())) {
					incentive = incentive + parseInt($("#downpayment").val());
				}
				payment = calculatePayments({
					finance: {
						tradeIn: $("#tradein").val() || 0,
						downPayment: incentive,
						apr: parseFloat($("#rate").val()),
						termMonths: $("#term").val()
					},
					totalPrice: Number($('#price').val()) + Number($('#destHand').val())
				});
                
				$('#estPayment').val(payment);
				$('.estPayment').slideDown(500).find('.value').text(formatCurrency(payment));
			}
		},this,"calc-bind");
	},
	"warranty-mileage-calc": function() {
		var vehTabPage = $('.tabPage:visible');
		var vin = vehTabPage.find('input[name="vehicle_vin"]').val();
		var mileage = $('#vehicle_mileage').val();
		
		getVehicleWarranty(function(data) {
			$.each(data.warranty.ownerWarrantyDetails,function(){
				var warrantyItem = this;
				var now = new Date();
				milesRemaining = warrantyItem.mileageRemaining.replace(/999999/,"Unlimited");
				timeRemaining = new Date(warrantyItem.timeRemaining);
							
				if ((now > timeRemaining)) {
					timeRemaining = "Expired";
					milesRemaining = "-";
				} else {
					timeRemaining = warrantyItem.timeRemaining;
				}
				
				vehTabPage.find('.orig-warranty td:contains("'+warrantyItem.warrantyDescription+'")')
					.siblings('.remainingMileage').text(milesRemaining)
					.siblings('.remainingTime').text(timeRemaining);
			});
			$.each(data.warranty.subsequentOwnerWarrantyDetails,function(){
				var warrantyItem = this;
				var now = new Date();
				milesRemaining = warrantyItem.mileageRemaining.replace(/999999/,"Unlimited");
				timeRemaining = new Date(warrantyItem.timeRemaining);
				
				if ((now > timeRemaining)) {
					timeRemaining = "Expired";
					milesRemaining = "-";
				} else {
					timeRemaining = warrantyItem.timeRemaining;
				}
				
				/*
				if (warrantyItem.timeRemaining == "01/01/0001") {
					var timeOutput = "Expired"; 
				} else {
					var timeOutput = warrantyItem.timeRemaining;
				}
				*/
				
				vehTabPage.find('.sub-warranty td:contains("'+warrantyItem.warrantyDescription+'")')
					.siblings('.remainingMileage').text(milesRemaining)
					.siblings('.remainingTime').text(timeRemaining);
			});
		}, vin, mileage);
	},
	"warranty-switch-coverage": function() {
		$(this).addClass('selected');
		if(this.rel == 'original') {
			$('a[rel="subsequent"]').removeClass('selected');
			$('.sub-warranty').hide();
			$('.orig-warranty').show();
		} else {
			$('a[rel="original"]').removeClass('selected');
			$('.orig-warranty').hide();
			$('.sub-warranty').show();
		}
	},
	"find-dealers": function() {
		$.ajax({
			url: "/MMNA/findDealer.do",
			type: "post",
			data: $(this).closest('form').serialize(),
			dataType: "text",
			success: function(data) {
				eval(data);
				$('.dealer-list').empty();
				$.each(dealerList, function(key,value) {
					$('.dealer-list').append("<p><strong>"+value.name+"</strong> (<a target='_blank' href='http://"+value.url+"'>link</a>)<br />"+value.address+"<br />"+value.city+","+value.state+" "+value.zip+"<br />"+value.phone+"<br />("+value.miles+" mi)</p>");
				});
			},
			error: function(xhr,status,y) {
				$('.dealer-list').html("Error: "+xhr.status+" "+status);
			}
		});
		return false;
	},
	"faq": function() {
		$.ajax({
			url: "/MMNA/javascript/json/faq.json",
			type: "get",
			dataType: "json",
			success: function(data) {
				$.each(data, function(k,v) {
					$('a[rel="'+k+'"]').data('faq',v).click(function() {
						var q = $(this).data('faq').q;
						var a = $(this).data('faq').a;
						var faq = $("#pop-faq").clone(true);
						
						faq.find('.faq').text(q).end().find('.ans').html(a);
						
						pop_box(faq);
						return false;
					});
				});
			},
			error: function(xhr,status,y) {
				alert("Error: "+xhr.status+" "+status);
			}
		});
	},
	"next-faq": function() {
		alert('test');
	},
	"sms-opt-in": function() {
		if ($(this).is(':checked')) {
			$('#phoneForm').show();
		} else {
			$('#phoneForm').hide();
		}
	}
}

$(function() {
	jsaction_bind(page_actions);
	/*
	 * This is the registration form engine, it binds up all the actions
	 * required to validate the form at each, animate the form and submit
	 * 
	 * It utilizes custom events and it's own action bindings to accomplish
	 * this in a somewhat convoluted way... but it works sweet and is on the
	 * right track to how we should be doing things - Event-Driven Web Applications FTW!
	 */
	$('#owner_reg_form').each(function() {
		
		$(this).find('.form-step:first button').removeAttr('disabled').end().bind('move-next',function() {
			var cur_step = $('#formSteps .selected').removeClass('selected');
			var next_step = cur_step.next().addClass('selected');
			
			var cur_tab = cur_step.attr('rel');
			var next_tab = next_step.attr('rel');
			
			var step_offset = {
					"account": 0,
					"profile": -540,
					"vehicle": -1080,
					"communication": -1620
				};
			
			$('.fieldset_holder').animate({ marginLeft: step_offset[next_tab]+"px"}, 1000, function() {
				if($('input[name="isPrimary"]:checked').val() == 0) {
					$('.primaryFirstName').parent().slideDown();
				}
				$('#'+cur_tab).find('button').attr('disabled','disabled');
				$('#'+next_tab).find('button').removeAttr('disabled');
			});
			$('#carImgHolder img:visible').each(function() { 
				if($(this).hasClass('vehicle')) {
					$(this).animate({ 'top': ($(this).height()*1)+'px' }, 500, function() { 
						var next = $(this).hide().css('top',($(this).height()*-1)+'px').next('img').each(function() { 
							$(this).parent().css({ height: $(this).height(), width: $(this).width() });
						}).css({ 'display': 'block' });
						
						if(next.hasClass('vehicle')) {
							next.animate({ 'top': 80 }, 1000);
						} else {
							next.animate({ 'right': 0 }, 1000);
						}
					});
				} else {
					$(this).animate({ 'right': ($(this).width()*-1)+'px' }, 500, function() { 
						var next = $(this).hide().next('img').each(function() { 
							$(this).parent().css({ height: $(this).height(), width: $(this).width() });
						}).css({ 'display': 'block' });
						
						if(next.hasClass('vehicle')) {
							next.animate({ 'top': 80 }, 1000);
						} else {
							next.animate({ 'right': 0 }, 1000); 
						}
					});
				}
			});
			
			
			
			// stop spinner
			var spinner = $(this).data("spinner");
			if (spinner != undefined) {
				spinner.stop();
			}
			
						

			return false;
		}).bind('move-prev', function() {
			var cur_step = $('#formSteps .selected').removeClass('selected');
			var prev_step = cur_step.prev().addClass('selected');
			
			var cur_tab = cur_step.attr('rel');
			var prev_tab = prev_step.attr('rel');
			
			var step_offset = {
				"account": 0,
				"profile": -540,
				"vehicle": -1080,
				"communication": -1620
			};
						
			$('.fieldset_holder').animate({ marginLeft: step_offset[prev_tab]+"px"}, 1000, function(){
				$('#'+cur_tab).find('button').attr('disabled','disabled');
				$('#'+prev_tab).find('button').removeAttr('disabled');
			});

			$('#carImgHolder img:visible').each(function() { 
				if($(this).hasClass('vehicle')) {
					$(this).animate({ 'top': ($(this).height())+'px' }, 500, function() { 
						var next = $(this).hide().css('top',($(this).height()*-1)+'px').parent().find('.'+prev_tab).each(function() { 
							$(this).parent().css({ height: $(this).height(), width: $(this).width() });
						}).css({ 'display': 'block' });
						
						if(next.hasClass('vehicle')) {
							next.animate({ 'top': 80 }, 1000);
						} else {
							next.animate({ 'right': 0 }, 1000);
						}
					});
				} else {
					$(this).animate({ 'right': ($(this).width()*-1)+'px' }, 500, function() { 
						var next = $(this).hide().parent().find('.'+prev_tab).each(function() { 
							$(this).parent().css({ height: $(this).height(), width: $(this).width() }); 
						}).css({ 'display': 'block' });
						
						if(next.hasClass('vehicle')) {
							next.animate({ 'top': 80 }, 1000);
						} else {
							next.animate({ 'right': 0 }, 1000);
						}
					});	 
				}
			});
		});
		
		jsaction_bind({
			"stepFwd": function() {
				// start spinner and store it on the parent fieldset object
				//console.log ("creating new spinner on " + $(this).attr("id") + "_spinner");
				var spinner = new Spinner(opts).spin ($("#" + $(this).attr("id") + "_spinner")[0]);
				$(this.form).data("spinner", spinner);
				
				var this_step = $(this).parents('.form-step');
				var valid_list = this_step.find(':input[class*="input_validate"]');
				this_step.data("valid-list",valid_list);
				genericClear({source:this});
				valid_list.trigger('validate');
			},
			"stepBack": function() {
				$(this.form).trigger('move-prev');
				genericClear({source:this});
			},
			"check-step": function(e,obj) {
				validate_me = e.obj || obj;
				var inputs = $(this).data('valid-list');
				genericValidate(validate_me);
				
				
				
				if(inputs.not('.valid').size() == 0) {
					//final step
					if(this.id != 'communication') {						
						$(this.form).trigger('move-next');
					} else {
						$(this.form).submit();
						tagOmnitureSumit();
					}

				}
				
				
			}
		},this,"multistep");
		
		jsaction_bind({
			"group-phone": function(e) {
				var grpFlag = true;
				//if ($(this).is(':visible')) {  <-- only supported correctly in jQuery 1.3.2+.  1.3.1 doesn't consider ancestor's visibility
				if (this.offsetWidth > 0 && this.offsetHeight > 0) { //<-- the jQuery 1.3.2+ way of testing for visibility
					$(this).closest('.form-step').find('input[class*="phone_"]').each(function(){
						grpFlag = grpFlag && this.value.length == this.maxLength && validateRegEx({ source: this, expression: /^\d+$/ });
						if(!grpFlag) { 
							$(this).removeClass('valid').addClass('error');
						} else { 
							$(this).removeClass('error').addClass('valid');
						}
					});
				}
				
				if(grpFlag) {
					e['obj'] = { source: this, status: "pass" }
				} else {
					e['obj'] = { source: this, status: "fail", message: "Phone number not in correct format." };
					if ($(this).parents("form").data("spinner") != undefined) {
					    $(this).parents("form").data("spinner").stop();
					}
				}
			},
			"group-radio-select": function(e) {
				if($(':radio[name="'+this.id+'"]:checked').size() == 0) {
					$(this).removeClass('valid').addClass('error');
					e['obj'] = { source: this, status: "fail", message: "Must Select an Option." };
					if ($(this).parents("form").data("spinner") != undefined) {
					    $(this).parents("form").data("spinner").stop();
					}
				} else {
					$(this).removeClass('error').addClass('valid');
					e['obj'] = { source: this, status: "pass" }
				}
			},
			"prime-driver": function(e) {
				var validatedObj = {
					source: this,
					expression: /^[a-zA-Z'-]+$/
				};
				
				if($('input[name="isPrimary"]:checked').val() == 0) {
					if(validateRegEx(validatedObj)) {
						validatedObj['status'] = "pass";
					} else {
						validatedObj['status'] = "fail";
						validatedObj['message'] = "Field must be text.";
						if ($(this).parents("form").data("spinner") != undefined) {
						    $(this).parents("form").data("spinner").stop();
						}
					}
				} else {
					validatedObj['status'] = "pass";
				}
				
				e['obj'] = validatedObj;
			},
			"email": function(e) {
				var validatedObj = {
					source: this,
					expression: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z]{2,4})+$/
				};
				
				if(validateRegEx(validatedObj)) {
					e.stopPropagation();
					$.ajax({
						url: "/MMNA/ownerSiteAction.do",
						type: "post",
						data: { "email": this.value, "method": "checkUserExists" },
						success: function(data) {
							if(data == "Success") {
								validatedObj['status'] = "pass";
							} else {
								validatedObj['status'] = "fail";
								validatedObj['message'] = "Email address is already in use.  Please check the email address provided or <a href='/MMNA/jsp/owners-site/index.do'>Click here</a> to go back and log in.";
							}
							if(!(validatedObj.status == "pass" && $(validatedObj.source).hasClass('valid'))) {
								$(validatedObj.source).parents('.form-step').trigger('validate',[validatedObj]);
							}
						},
						error: function(xhr,status,y) {
							alert(xhr.responseText);
							validatedObj['status'] = "fail";
							validatedObj['message'] = "Server Error: "+xhr.status+" "+status;
							if ($(this).parents("form").data("spinner") != undefined) {
							    $(this).parents("form").data("spinner").stop();
							}
						}
					});
				} else {
					validatedObj['status'] = "fail";
					validatedObj['message'] = "Not a valid email address.";
					if ($(this).parents("form").data("spinner") != undefined) {
					    $(this).parents("form").data("spinner").stop();
					}
				}
				e['obj'] = validatedObj;
			},
			"text": function(e) {
				var validatedObj = {
					source: this,
					expression: /^[a-zA-Z'\- ]+$/
				};
									
				if(validateRegEx(validatedObj)) {
					validatedObj['status'] = "pass";
				} else {
					validatedObj['status'] = "fail";
					validatedObj['message'] = "Field must be text.";
					if ($(this).parents("form").data("spinner") != undefined) {
					    $(this).parents("form").data("spinner").stop();
					}
				}
				
				e['obj'] = validatedObj;
			},
			"numeric": function(e) {
				var validatedObj = {
					source: this,
					expression: /^\d+$/
				};
				
				if(validateRegEx(validatedObj)) {
					validatedObj['status'] = "pass";
				} else {
					validatedObj['status'] = "fail";
					validatedObj['message'] = "Field must be a number.";
					if ($(this).parents("form").data("spinner") != undefined) {
					    $(this).parents("form").data("spinner").stop();
					}
				}
				e['obj'] = validatedObj;
			},
			"blank": function(e) {
				var validatedObj = {
					source: this,
					minLength: 1
				};
				
				//var isVisible = $(this).is(':visible');	// <-- only supported correctly in jQuery 1.3.2+.  1.3.1 doesn't consider ancestor's visibility
				var isVisible = (this.offsetWidth > 0 && this.offsetHeight > 0); //<-- the jQuery 1.3.2+ way of testing for visibility
				if(validateMinLength(validatedObj) || !isVisible) {
					validatedObj['status'] = "pass";
				} else {
					validatedObj['status'] = "fail";
					validatedObj['message'] = "Field cannot be blank.";
					if ($(this).parents("form").data("spinner") != undefined) {
					    $(this).parents("form").data("spinner").stop();
					}
				}
				e['obj'] = validatedObj;
			},
			"password": function(e) {
				var validatedObj = {
					source: this,
					minLength: 6
				};
	
				if(validateMinLength(validatedObj)) {
					validatedObj['status'] = "pass";
				} else {
					validatedObj['status'] = "fail";
					validatedObj['message'] = "Not a valid password.";
					if ($(this).parents("form").data("spinner") != undefined) {
					    $(this).parents("form").data("spinner").stop();
					} else {
						//console.log ("yeah that didn't work: " + $(this).parents("form").attr("id"));
					}
				}
	
				e['obj'] = validatedObj;
			},
			"length": function(e) {
				var validatedObj = {
					source: this,
					minLength: this.maxLength
				};
	
				if(validateMinLength(validatedObj)) {
					validatedObj['status'] = "pass";
				} else {
					validatedObj['status'] = "fail";
					validatedObj['message'] = "Field must be exactly "+this.maxLength+" characters";
					if ($(this).parents("form").data("spinner") != undefined) {
					    $(this).parents("form").data("spinner").stop();
					}
				}
	
				e['obj'] = validatedObj;
			},
			"confirm": function(e) {
				var validatedObj = {
					source: this
				};
				var related = $('[name="'+this.name.split(/_/)[1]+'"]');
				
				if((this.value == related.val())) {
					validatedObj['status'] = "pass";
				} else {
					validatedObj['status'] = "fail";
					validatedObj['message'] = "Field was not a valid match.";
					if ($(this).parents("form").data("spinner") != undefined) {
					    $(this).parents("form").data("spinner").stop();
					}
				}
				e['obj'] = validatedObj;
			},
			"vin": function(e) {
				var validatedObj = {
					source: this
				};
				validatedObj['status'] = "pass";
				var vin = this.value;
				if(vin.length == 17) {
					e.stopPropagation();
					$.ajax({
						url: "/MMNA/ownerSiteAction.do",
						type: "post",
						data: { "vin": vin, "mileage": "0", "method":"getWarranty" },
						dataType: "json",
						success: function(data) {
							if(isEmptyObject(data)) {
								validatedObj['status'] = "fail";
								validatedObj['message'] = "VIN is not a valid Mitsubishi vehicle.";
							} else if(data.warranty.vehicleInfo.vin == vin) {
								$('#registerModel').text(data.warranty.vehicleInfo.modelYear+" "+data.warranty.vehicleInfo.model);
								$('#registerColor').text(data.warranty.vehicleInfo.exteriorColor);
								$.each(data.warranty.vehicleInfo, function(k,v) {
									$('input[name="'+k+'"]').val(v);
								})
								$('input[name="year"]').val(data.warranty.vehicleInfo.modelYear);
								$('input[name="trim"]').val(data.warranty.vehicleInfo.priceline);
								validatedObj['status'] = "pass";
							} else {
								validatedObj['status'] = "fail";
								validatedObj['message'] = "Server Error: VIN Validation is currently down, please come back to register in a little bit.";
							}
							if(!(validatedObj.status == "pass" && $(validatedObj.source).hasClass('valid'))) {
								$(validatedObj.source).parents('.form-step').trigger('validate',[validatedObj]);
							}
						},
						error: function(xhr,status,y) {
							validatedObj['status'] = "fail";
							validatedObj['message'] = "Server Error: VIN Validation is currently down, please come back to register in a little bit.";
							$(validatedObj.source).parents('.form-step').trigger('validate',[validatedObj]);
							if ($(validatedObj.source).parents("form").data("spinner") != undefined) {
							    $(validatedObj.source).parents("form").data("spinner").stop();
							}
						}
					});
				} else {
					validatedObj['status'] = "fail";
					validatedObj['message'] = "VIN must be 17 characters.";
					e['obj'] = validatedObj;
					if ($(this).parents("form").data("spinner") != undefined) {
					    $(this).parents("form").data("spinner").stop();
					}
				}
			}
		},this,"input");
		$('#allModels').attr('checked', false);
		var allModelsChecked;
		$('#allModels').bind('mousedown', function() {
			allModelsChecked = $(this).attr('checked');
		});
		$('#allModels').bind('click', function() {
			if (allModelsChecked) {
				$("input[class=checkallmodels]").each(function(){
					$(this).attr('checked', false);
				});
			} else {
				$("input[class=checkallmodels]").each(function(){
					$(this).attr('checked', true);
				});	
			}
		}); 
		
		$("input[class=checkallmodels]").click(function(){
			$('#allModels').attr('checked', false);
		});		
		
		/*$('#allCategories').click(function(){
			var checked_status = this.checked;
			$("input[class=checkallcategories]").each(function(){
				this.checked = checked_status;
			});
		});	*/
		
		$('#allCategories').attr('checked', false);
		var allCategoriesChecked;
		$('#allCategories').bind('mousedown', function() {
			allCategoriesChecked = $(this).attr('checked');
		});
		$('#allCategories').bind('click', function() {
			if (allCategoriesChecked) {
				$("input[class=checkallcategories]").each(function(){
					$(this).attr('checked', false);
				});
			} else {
				$("input[class=checkallcategories]").each(function(){
					$(this).attr('checked', true);
				});	
			}
		});		
		
		$("input[class=checkallcategories]").click(function(){
			$('#allCategories').attr('checked', false);
		});
		
		$('#by_mobile').attr('checked', false);
		var by_mobile;
		$('#by_mobile').bind('mousedown', function() {
			by_mobile = $(this).attr('checked');
		});		
		$('#by_mobile').bind('click', function(){
			if(by_mobile) {
				$('#phoneForm').hide();
			} else {
				$('#phoneForm').show();	
			}
			
		});
		
		/*$('#by_mobile').click(function(){
			if($('#by_mobile').attr('checked')) {
				$('#phoneForm').show();
			} else {
				$('#phoneForm').hide();				
			}			
		});*/
		
/*****/
		$(function(){
		    var allRadios = $('input[type=radio]')
		    var radioChecked;
		    
		    var setCurrent =
		                    function(e) {
		                        var obj = e.target;
		         
		                        radioChecked = $(obj).attr('checked');
		                 }
		                            
		    var setCheck =
		                function(e) {
		                    
		                    if (e.type == 'keypress' && e.charCode != 32) {
		                        return false;
		                    }
		                    
		                    var obj = e.target;
		                    
		         if (radioChecked) {
		         $(obj).attr('checked', false);
		         } else {
		         $(obj).attr('checked', true);
		         }
		             }    
		                             
		    $.each(allRadios, function(i, val){        
		         var label = $('label[for=' + $(this).attr("id") + ']');
		        
		     $(this).bind('mousedown keydown', function(e){
		            setCurrent(e);
		        });
		        
		        label.bind('mousedown keydown', function(e){
		            e.target = $('#' + $(this).attr("for"));
		            setCurrent(e);
		        });
		    
		     $(this).bind('click', function(e){
		            setCheck(e);    
		        });
		    
		    });
		});		
/*****/		
		
		$('#news_events_link').click(function(e){	
			e.preventDefault();
			$( "#news_events_dialog" ).modal({
				minHeight:650,
				minWidth: 400,
				position: ["10%", "10%"]
			});
			$('#simplemodal-container').css('height', 'auto');
		});
		
		$('#vehicle_information_link').click(function(e){	
			e.preventDefault();
			$( "#offers_promotions_dialog" ).modal({
				minHeight:650,
				minWidth: 400,
				position: ["10%", "10%"]
			});
			$('#simplemodal-container').css('height', 'auto');
		});
		
		$('#offers_promotions_link').click(function(e){	
			e.preventDefault();
			$( "#vehicle_information_dialog" ).modal({
				minHeight:650,
				minWidth: 400,
				position: ["10%", "10%"]
			});
			$('#simplemodal-container').css('height', 'auto');
		});
		
		$('#service_information_link').click(function(e){	
			e.preventDefault();
			$( "#service_information_dialog" ).modal({
				minHeight:650,
				minWidth: 450,
				position: ["10%", "10%"]
			});
			$('#simplemodal-container').css('height', 'auto');
		});		
		
		$('#sms_sample_link').click(function(e){	
			e.preventDefault();
			$( "#sms_sample_dialog" ).modal();
			$('#simplemodal-container').css('height', 'auto');
		});		
		
	});
});


