/* function to calculate days in a given month */

function daysInMonth (year, month) {
     return 32 - new Date(year, month, 32).getDate();
}

/* function to populate month select */

jQuery.populateMonths = function(targetID) {
	var monthNames = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	
	for(i=0; i<12; i++) {
		monthValue = i;
		$(targetID).append("<option value='"+monthValue+"'>"+monthNames[i]+"</option>");
	}
	
	$(targetID).children().eq(0).attr("selected", "selected");
};

/* function to populate days of month select */

jQuery.populateDays = function(month, targetID) {
	$(targetID).html("<option value=''>Day</option>");
	
	if(month) {
	
		var currentDate = new Date();
	
		for( i=1; i<= daysInMonth(currentDate.getFullYear(),month); i++) {
			$(targetID).append("<option value='"+i+"'>"+i+"</option>");
		}
	
		$(targetID).children().eq(0).attr("selected", "selected");
	}else {
	    $(targetID).append("<option value=''></option>");
	    $(targetID).find("option:last").hide();
	}
}

jQuery.checkZipCode = function() {
	$("#find_dealer").trigger('click');
}

function onDealerSessionSet(e, obj){
	if(obj.isDealerSession){ //used if cached
		$('body').css("display", "none");
		window.location = "http://"+obj.dealerDomain+"/ContactUsForm";
	}else{
		
	}
	
}

/************************* DOCUMENT ACTIONS ******************************/

$(document).ready (function() {
	$(document).bind("session:dealer", onDealerSessionSet);
	try{
		if(dealersession){ //used if not cached
			if(dealersession.isDealerSession == true){
				$('body').css("display", "none");
				window.location = "http://"+dealersession.dealerDomain+"/ContactUsForm";
			}else if(dealersession.isDealerSession == false){
				
			}
		}
	}catch(e){
	}

	$.preloadImages("/global/images/forms/loading_bg.png");
	
	$("#comments").keypress(function(e) {
  		if(e.charCode >= 48 ) 
    		if($("#comments").val().length > 500)
     			return false;
	});
	
	/* get VW model and trim info */
	$("#trim").attr("disabled","disabled");
	
	/* bind find dealer event */
	$("#find_dealer").click(function (e) {	
		e.preventDefault();
		$.findDealer($("#zipCode").val(), "#dealer_list");
		//check for find dealer spotlight action
		if(typeof spotlightFindDealer == 'function') {
			spotlightFindDealer();
		}
	});
	
	/* prevent "return" keypress in zipCode field from submitting the form */
	$("#zipCode").keypress(function(e){
    	if(e.keyCode == 13) {
			if($("#zipCode").val().length < 5){
				//quick fix for autocomplete
				setTimeout('$.checkZipCode()', 10);
				e.preventDefault();
			}else {
				$("#find_dealer").trigger('click');
			}
    		return false;
    	}
	});
	
	$.attachVWModels("#modelName", "#trim");
	initCookie();
	$.populateForm();
	
	$("#modelName").change(function () {
		$.attachVWTrims($("#modelName").val(), "#trim");
	});
	
	/* set modelCode, transmission, msrpTotal based on trim value */
	
	$("#trim").change(function () {
		$.setModelDetails("#modelName", "#trim", "#transmission", "#modelCode", "#msrpTotal");
	});
	
	/* set contact info requirements for phone and email based on response */
	
	$("[name=preferredContactMethod]").click(function () {
		$.setContactRequirements($("[name=preferredContactMethod]:checked").val(), "#phone", "#email1", "#email2");
	});
		
	/* restrict input to certain form fields */
	$("#comments").alphanumeric({allow:"?.@-_`!#$%&*+-~ "});
	$("#firstName").alpha({allow:"' -"});
	$("#lastName").alpha({allow:"' -"});
	$("#phone").numeric({allow:".()- "});
	$("#email1").alphanumeric({allow:".@-_`!#$%*+-~"});
	$("#email2").alphanumeric({allow:".@-_`!#$%*+-~"});
	$("#zipCode").numeric();
	
	/* populate month select */
	$.populateMonths("#month");
	$.populateDays('', '#day');
	/* update days in month on month change */
	$("#month").change(function () {
		$.populateDays($("#month").val(),"#day");
	});
	
	/* validate and submit data */
	$("#joyride").submit(function(e) {
		e.preventDefault();
		
		/* validate form, submit if passed */
    	if($("#joyride").validate({verify:"#email1, #email2"}, getFailureColor())) {
    		
    		/* trigger find a dealer action if no dealer selected */
    		if(!$('[name="dealerId"]:checked').val()) {
    			$("#find_dealer").trigger("click");
    			return false;
			}
			//populateCookie user info cookie
			var userDataObj = $("#firstName").val()+"~"+$("#lastName").val()+"~"+$("#preferredContactMethod").val()+"~"+$("#phone").val()+"~"+$("#email1").val()+"~"+$("#email2").val()+"~"+$("#zipCode").val()+"~"+"false";
			buildVwFormsUserInfoCookie(userDataObj);
			
      		$("#joyride").joyride_assembleXML("#form_wrapper");

			//check for submit spotlight action
			if(typeof spotlightSubmit == 'function') {
				spotlightSubmit();
			}
			
      		return true;
      	}
      	return false;
    });

});