// Globals
var intervalID;


function gatherVehiclePost(form_name) {

	// purpose: generate section of post string to use in ajax forms for current vehicle info
	
	var newused = document.getElementById('vType').innerHTML;
	var year = document.getElementById('vYear').innerHTML;
	var make = document.getElementById('vMake').innerHTML;
	var model = document.getElementById('vModel').innerHTML;
	var stock = document.getElementById('vStock').innerHTML;
	var vin = document.getElementById('vVin').innerHTML;
	var leadRoutingData = document.getElementById('leadRouting').innerHTML;
	var leadRoutingParsed = leadRoutingData.split("|");
	
	//check to see if there is an email to override the lead address
	if( $j('#form-lead-override-'+form_name).length == 1 ){
		leadRoutingParsed[1] = $j('#form-lead-override-'+form_name).html();
	}

	var postStr = "&newused=" + encodeURIComponent(newused) + "&year=" + encodeURIComponent(year) + "&make=" + encodeURIComponent(make) + 
				  "&model=" + encodeURIComponent(model) + "&stock=" + encodeURIComponent(stock) + "&vin=" + encodeURIComponent(vin) + 
				  "&leadtype=" + encodeURIComponent(leadRoutingParsed[0]) + "&sendto=" + encodeURIComponent(leadRoutingParsed[1]) +
				  "&sendfrom=" + encodeURIComponent(leadRoutingParsed[2]);
	
	if( $j('#leadRoutingCC').length ){
		postStr = postStr.concat( '&ccto=' + encodeURIComponent($j('#leadRoutingCC').html()) );
	}
	
	return postStr;
	
}

function findFormUrl(form_name) {

	// purpose: based on the hardcoded form id return the correct url ***
	
	var thisForm = {};
	thisForm.name = form_name;
	
	if (form_name == "moreInformation") {
		thisForm.id = "1";
		thisForm.url = "/InventoryHosting2/Details/includes/forms/moreInformation.asp";
	}
	else if (form_name == "sendToFriend") {
		thisForm.id = "4";
		thisForm.url = "/InventoryHosting2/Details/includes/forms/sendToFriend.asp";
	}
	else if (form_name == "makeOffer") {
		thisForm.id = "2";
		thisForm.url = "/InventoryHosting2/Details/includes/forms/makeOffer.asp";
	}
	else if (form_name == "requestQuote") {
		thisForm.id = "3";
		thisForm.url = "/InventoryHosting2/Details/includes/forms/requestQuote.asp";
	}
	else if (form_name == "scheduleTestDrive") {
		thisForm.id = "6";
		thisForm.url = "/InventoryHosting2/Details/includes/forms/scheduleTestDrive.asp";
	}
	else if (form_name == "valueMyTrade") {
		thisForm.id = "5";
		thisForm.url = "/InventoryHosting2/Details/includes/forms/valueMyTrade.asp";
	}
	else if (form_name == "getFinanced") {
		thisForm.id = "7";
		thisForm.url = "/InventoryHosting2/Details/includes/forms/getFinanced.asp";
	}
	else if (form_name == "dealerInfo" || form_name == "quickContact") {
		thisForm.id = "8";
		thisForm.url = "/InventoryHosting2/Details/includes/forms/moreInformation.asp";
	}
	else if (form_name == "showInt360") {
		thisForm.id = ""; // used for display, no form posting involved so okay to just leave this empty
		thisForm.url = "/InventoryHosting2/Details/includes/forms/showInt360.asp";
	}
	else if (form_name == "showExt360") {
		thisForm.id = ""; // used for display, no form posting involved so okay to just leave this empty
		thisForm.url = "/InventoryHosting2/Details/includes/forms/showExt360.asp";
	}
	else if (form_name == "printBrochure") {
		thisForm.id = ""; // used for display, no form posting involved so okay to just leave this empty
		thisForm.url = "/InventoryHosting2/Details/includes/forms/printBrochure.asp";
	}
	else {
		thisForm.id = "";
		thisForm.url = ""; // this shouldnt happen
	}
	
	var formSetting = $j("#formBaseUrl").attr("data-url");
	if( formSetting.length > 0 ){
		formSetting = formSetting.split('|');
		var ids = formSetting[0].split(',');
		var baseUrl = formSetting[1];
		
		if( $j.inArray( thisForm.id, ids ) >= 0 ){
			thisForm.url = thisForm.url.replace('/InventoryHosting2/Details/includes/forms/',baseUrl);
		}
		
	}
	
	return thisForm;

}

function showActionForm(form_name) {
	
	// purpose: display details page popup forms
	
	// Based on form clicked, determine the corresponding form url
	var formData = findFormUrl(form_name);
	
	// Get entire contents of unposted form page and add to the empty form container
	var formContent = new ajaxObject(formData.url);
	formContent.callback = function(responseText) {
		$j('#actionForm_content').html(responseText);
		
		//being able to override pages, need to have some sort of control over CSS and IE doesn't parse doing .innerHTML = html;
		if( responseText.indexOf('<script>') >= 0 ){
			var js = responseText.slice( responseText.indexOf('<script>')+8, responseText.indexOf('</script>') );
			eval(js);
		}
		
		// Track for GA
		if(typeof _gaq == "object") {
			_gaq.push(["_trackEvent", "Forms", "Open", $j("form", "#formContainer").attr("class")]);
		}
	};
	
	var vehicleInfo = "postback=false";
	$j('.hide').each(function() {
		vehicleInfo = vehicleInfo + "&" + $j(this).attr("id") + "=" + encodeURIComponent($j(this).text());
	});
	$j('#formContainer').css({'left':'50%','width':'453px'});
	formContent.update(vehicleInfo);
	
	// Show the background screen and form and set the interval to move them as the user scrolls
	if (String($j("#adjustLongLightboxViewport").text()).toLowerCase() != 'true')
		document.getElementById('formContainer').style.top = ((document.documentElement.scrollTop || document.body.scrollTop) + 35) + 'px';
	else
		document.getElementById('formContainer').style.top = String($j("#ActionPanel").offset().top - 20) + 'px';
	$j('#formContainer').fadeIn("slow");
	document.getElementById('screen').style.display = '';
	intervalID = setInterval(function() {
		document.getElementById('screen').style.top = (document.documentElement.scrollTop || document.body.scrollTop) + 'px';
		}, 100);
}

function sendActionForm(form_name) {
	
	//Settings
	var subject = $j("#formServicePrefix").html() + " - ";
	var includeFields = ""; // additional specifics
	document.getElementById('thankyou_message').innerHTML = "Thank you!<br /><br />We will be contacting you shortly.";
	
	var jForm = $j('form.'+form_name);
	if(jForm.length > 1) {
		usedForm = jForm.filter(function(index) {
			return $j(this).find("input").first().val().length > 0;
		});
		jForm = (usedForm.length == 1) ? usedForm : jForm.first();
	}
	
	// Validate the correct form
    switch(form_name) {
        case 'moreInformation':
			//Subject line
			subject = subject + "More Information";
			//Validation
			if (jForm.find('[name=actionFirstName]').val() == "") {
				inlineMsg(jForm.find('[name=actionFirstName]').get(0),'<strong>Error</strong><br />Please enter your first name.', 2);
				return false;
			}
			if (jForm.find('[name=actionLastName]').val() == "") {
				inlineMsg(jForm.find('[name=actionLastName]').get(0),'<strong>Error</strong><br />Please enter your last name.', 2);
				return false;
			}
			if( jForm.hasClass('email-phone-required') ) {
				// Setting to force user to enter email and phone
				if (jForm.find('[name=actionEmail]').val() == "" || jForm.find('[name=actionPhone]').val() == "") {
					inlineMsg(jForm.find('[name=actionEmail],[name=actionPhone]').filter('[value=""]').get(0),'<strong>Error</strong><br />Please enter your phone and email.', 2);
					return false;
				}
				
				if (jForm.find('[name=actionEmail]').val() != "") {
					if(!isEmailValid(jForm.find('[name=actionEmail]').val())) {
						inlineMsg(jForm.find('[name=actionEmail]').get(0),'<strong>Error</strong><br />You have entered an invalid email.', 2);
						return false;
					}
				}
				
			} else if (jForm.find('[name=actionEmail]').val() == "" && jForm.find('[name=actionPhone]').val() == "") {
				inlineMsg(jForm.find('[name=actionEmail]').get(0),'<strong>Error</strong><br />Please enter your phone or email.', 2);
				return false;
			}
			else {
				if (jForm.find('[name=actionEmail]').val() != "") {
					if(!isEmailValid(jForm.find('[name=actionEmail]').val())) {
						inlineMsg(jForm.find('[name=actionEmail]').get(0),'<strong>Error</strong><br />You have entered an invalid email.', 2);
						return false;
					}
				}
			}
			if (jForm.find('[name=actionComments]').val() == "") {
				inlineMsg(jForm.find('[name=actionComments]').get(0),'<strong>Error</strong><br />Please enter your questions or comments.', 2);
				return false;
			}
			break;
			
		case 'quickContact':
		case 'dealerInfo':
			//Subject line
			subject = subject + "Dealer Quick Contact";
			//Validation
			if (jForm.find('[name=actionFirstName]').val() == "") {
				inlineMsg(jForm.find('[name=actionFirstName]').get(0),'<strong>Error</strong><br />Please enter your first name.', 2);
				return false;
			}
			if (jForm.find('[name=actionLastName]').val() == "") {
				inlineMsg(jForm.find('[name=actionLastName]').get(0),'<strong>Error</strong><br />Please enter your last name.', 2);
				return false;
			}
			if (jForm.find('[name=actionEmail]').val() == "" && jForm.find('[name=actionPhone]').val() == "") {
				inlineMsg(jForm.find('[name=actionEmail]').get(0),'<strong>Error</strong><br />Please enter your phone or email.', 2);
				return false;
			}
			else {
				if (jForm.find('[name=actionEmail]').val() != "") {
					if(!isEmailValid(jForm.find('[name=actionEmail]').val())) {
						inlineMsg(jForm.find('[name=actionEmail]').get(0),'<strong>Error</strong><br />You have entered an invalid email.', 2);
						return false;
					}
				}
			}
			if (jForm.find('[name=actionComments]').val() == "") {
				inlineMsg(jForm.find('[name=actionComments]').get(0),'<strong>Error</strong><br />Please enter your questions or comments.', 2);
				return false;
			}
			break;
			
        case 'makeOffer':
			//Subject line
			subject = subject + "Make An Offer";
			//Validation
			if (jForm.find('[name=actionFirstName]').val() == "") {
				inlineMsg(jForm.find('[name=actionFirstName]').get(0),'<strong>Error</strong><br />Please enter your first name.', 2);
				return false;
			}
			if (jForm.find('[name=actionLastName]').val() == "") {
				inlineMsg(jForm.find('[name=actionLastName]').get(0),'<strong>Error</strong><br />Please enter your last name.', 2);
				return false;
			}
			if (jForm.find('[name=actionEmail]').val() == "" && jForm.find('[name=actionPhone]').val() == "") {
				inlineMsg(jForm.find('[name=actionEmail]').get(0),'<strong>Error</strong><br />Please enter your phone or email.', 2);
				return false;
			}
			else {
				if (jForm.find('[name=actionEmail]').val() != "") {
					if(!isEmailValid(jForm.find('[name=actionEmail]').val())) {
						inlineMsg(jForm.find('[name=actionEmail]').get(0),'<strong>Error</strong><br />You have entered an invalid email.', 2);
						return false;
					}
				}
			}
			if (jForm.find('[name=actionOffer]').val() == "") {
				inlineMsg(jForm.find('[name=actionOffer]').get(0),'<strong>Error</strong><br />Please enter your payment offer.', 2);
				return false;
			}
			break;
			
        case 'requestQuote':
			//Subject line
			subject = subject + "Request A Quote";
			//Validation
			if (jForm.find('[name=actionFirstName]').val() == "") {
				inlineMsg(jForm.find('[name=actionFirstName]').get(0),'<strong>Error</strong><br />Please enter your first name.', 2);
				return false;
			}
			if (jForm.find('[name=actionLastName]').val() == "") {
				inlineMsg(jForm.find('[name=actionLastName]').get(0),'<strong>Error</strong><br />Please enter your last name.', 2);
				return false;
			}
			if (jForm.find('[name=actionEmail]').val() == "" && jForm.find('[name=actionPhone]').val() == "") {
				inlineMsg(jForm.find('[name=actionEmail]').get(0),'<strong>Error</strong><br />Please enter your phone or email.', 2);
				return false;
			}
			else {
				if (jForm.find('[name=actionEmail]').val() != "") {
					if(!isEmailValid(jForm.find('[name=actionEmail]').val())) {
						inlineMsg(jForm.find('[name=actionEmail]').get(0),'<strong>Error</strong><br />You have entered an invalid email.', 2);
						return false;
					}
				}
			}
			break;
			
        case 'sendToFriend':
			//Subject line
			subject = "Your Friend Suggested This Vehicle";
			document.getElementById('thankyou_message').innerHTML = "This vehicle and the information you requested has been emailed to " + jForm.find('[name=actionToEmail]').val();
			//Validation
			if (jForm.find('[name=actionYourName]').val() == "") {
				inlineMsg(jForm.find('[name=actionYourName]').get(0),'<strong>Error</strong><br />Please enter your full name.', 2);
				return false;
			}else{
				subject = jForm.find('[name=actionYourName]').val() + " Has Suggested This Vehicle";
			}
			if (jForm.find('[name=actionYourEmail]').val() == "") {
				inlineMsg(jForm.find('[name=actionYourEmail]').get(0),'<strong>Error</strong><br />Please enter your email adress.', 2);
				return false;
			}
			else {
				if(!isEmailValid(jForm.find('[name=actionYourEmail]').val())) {
					inlineMsg(jForm.find('[name=actionYourEmail]').get(0),'<strong>Error</strong><br />Your email adress is entered incorrectly.', 2);
					return false;
				}
			}
			if (jForm.find('[name=actionToEmail]').val() == "") {
				inlineMsg(jForm.find('[name=actionToEmail]').get(0),'<strong>Error</strong><br />Please enter your friends email adress.', 2);
				return false;
			}
			else {
				if(!isEmailValid(jForm.find('[name=actionToEmail]').val())) {
					inlineMsg(jForm.find('[name=actionToEmail]').get(0),'<strong>Error</strong><br />Your friends email adress is entered incorrectly.', 2);
					return false;
				}
			}
			if (jForm.find('[name=actionComments]').val() == "") {
				inlineMsg(jForm.find('[name=actionComments]').get(0),'<strong>Error</strong><br />Please enter some comments for your friend about this car.', 2);
				return false;
			}
			
			includeFields = "&includeFields=";
			jForm.find('input[name=includeFields]:checked').each(function() {
				includeFields = includeFields + encodeURIComponent($j(this).val() + ",");
			});

			break;
			
        case 'valueMyTrade':
			//Subject line
			subject = subject + "Value My Trade";
			//Validation
			if (jForm.find('[name=actionYear]').val() == "none") {
				inlineMsg(jForm.find('[name=actionYear]').get(0),'<strong>Error</strong><br />Please enter your vehicle year.', 2);
				return false;
			}
			if (jForm.find('[name=actionMake]').val() == "") {
				inlineMsg(jForm.find('[name=actionMake]').get(0),'<strong>Error</strong><br />Please enter your vehicle make.', 2);
				return false;
			}
			if (jForm.find('[name=actionModel]').val() == "") {
				inlineMsg(jForm.find('[name=actionModel]').get(0),'<strong>Error</strong><br />Please enter your vehicle model.', 2);
				return false;
			}
			if (jForm.find('[name=actionMileage]').val() == "") {
				inlineMsg(jForm.find('[name=actionMileage]').get(0),'<strong>Error</strong><br />Please enter your vehicle mileage.', 2);
				return false;
			}
			if (jForm.find('[name=actionColor]').val() == "") {
				inlineMsg(jForm.find('[name=actionColor]').get(0),'<strong>Error</strong><br />Please enter your vehicle color.', 2);
				return false;
			}
			if (jForm.find('[name=actionFirstName]').val() == "") {
				inlineMsg(jForm.find('[name=actionFirstName]').get(0),'<strong>Error</strong><br />Please enter your first name.', 2);
				return false;
			}
			if (jForm.find('[name=actionLastName]').val() == "") {
				inlineMsg(jForm.find('[name=actionLastName]').get(0),'<strong>Error</strong><br />Please enter your last name.', 2);
				return false;
			}
			if (jForm.find('[name=actionZipCode]').val() == "") {
				inlineMsg(jForm.find('[name=actionZipCode]').get(0),'<strong>Error</strong><br />Please enter your zipcode.', 2);
				return false;
			}
			if (jForm.find('[name=actionEmail]').val() == "" && jForm.find('[name=actionPhone]').val() == "") {
				inlineMsg(jForm.find('[name=actionEmail]').get(0),'<strong>Error</strong><br />Please enter your phone or email.', 2);
				return false;
			}
			else {
				if (jForm.find('[name=actionEmail]').val() != "") {
					if(!isEmailValid(jForm.find('[name=actionEmail]').val())) {
						inlineMsg(jForm.find('[name=actionEmail]').get(0),'<strong>Error</strong><br />You have entered an invalid email.', 2);
						return false;
					}
				}
			}
			break;
			
    }
	
	jForm.find(".button_wrapper").after("<div>Sending...</div>").remove();
	
	// Show loading / processing screen
	document.getElementById('actionForm_error').style.display = 'none';
	document.getElementById('actionForm_thankyou').style.display = 'none';
	document.getElementById('actionForm_content').style.display = 'none';
	document.getElementById('actionForm_loading').style.display = '';
	// Build the querystring from the form fields
	var formData = findFormUrl(form_name);
	var baseUrl = formData.url;
	var postVars = "postback=true&subject=" + encodeURIComponent(subject);
	// Iterate through each form field and add to querystring
	jForm.find('.form_input').each(function() {
		if( this.type != "checkbox" ){
			postVars = postVars + "&" + $j(this).attr("id") + "=" + encodeURIComponent($j(this).val());
		} else {
			postVars = postVars + "&" + $j(this).attr("id") + "=" + encodeURIComponent($j(this).attr('checked'));
		}
	});	
	
	// Make the ajax call
	postVars = postVars + gatherVehiclePost(form_name) + includeFields;
	baseUrl = document.getElementById("baseUrl").value + baseUrl;
	//alert(baseUrl);
	postActionForm(postVars, baseUrl, formData);
	
} 
	
function postActionForm(postStr, baseUrl, formData) {

	var formPosting = new ajaxObject(baseUrl);
	formPosting.callback = function(responseText, responseStatus, responseXML) {
		if (responseStatus == 200){	
			if (responseText == "success") {
				//show thank you
				document.getElementById('actionForm_thankyou').style.display = '';	
				document.getElementById('actionForm_content').style.display = 'none';
				document.getElementById('actionForm_loading').style.display = 'none';
				document.getElementById('actionForm_error').style.display = 'none';
				//log the conversion
				var vid = document.getElementById("visId").value;
				var vin = document.getElementById("vVin").innerHTML;
				var bwurl = $j("#bwUrl").attr("data-url");
				var reseller = document.getElementById("bwResellerFolder").innerHTML;
				trackConversion(vid, formData.id, vin, bwurl, reseller);
				
				if( $j('div.inside #actionForm').length && (formData.id == "8" || formData.id == "1") ){
					$j('div.inside #actionForm').parent().css('text-align','center').html( $j('#thankyou_message').html() );
				}
				
				// Track for GA
				if(typeof _gaq == "object") {
					_gaq.push(["_trackEvent", "Forms", "Submit - Success", formData.name]);
				}
				
				// Track Google Ad Conversion
				if ($j("#googleAdConversionCode").length) {
					var conversionID = $j("#googleAdConversionCode").html(),
						conversionLabel = $j("#googleAdConversionCode").attr("data-{0}".format(formData.name));
					
					if (conversionLabel.length) {
						conversionSrc = "http://www.googleadservices.com/pagead/conversion/{0}/?label={1}&guid=ON&script=0".format(conversionID, conversionLabel);
						$j("<img />").attr("src", conversionSrc).appendTo("body");
					}
				}
				
				if ($j("#clickableConversionCode").length) {
					_cctq.push(['cct_setConversionValue', 'ppc_ads']);
					_cctq.push(['cct_log', $j("#clickableConversionCode").html()]);
					(function() {
					var cctjs = document.createElement('script'); cctjs.type = 'text/javascript'; cctjs.async = true;
					cctjs.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cn.clickable.net/js/cct.js';
					var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(cctjs, s);
					})();
				}
			}
			else {
				//alert(responseText);
				document.getElementById('actionForm_error').style.display = '';	
				document.getElementById('actionForm_thankyou').style.display = 'none';	
				document.getElementById('actionForm_content').style.display = 'none';
				document.getElementById('actionForm_loading').style.display = 'none';
				
				if( $j('div.inside #actionForm').length && (formData.id == "8" || formData.id == "1") ){
					$j('div.inside #actionForm').parent().css('text-align','center').html( $j('#actionForm_error').html() );
				}
				
				// Track for GA
				if(typeof _gaq == "object") {
					_gaq.push(["_trackEvent", "Forms", "Submit - Error", $j("form", "#formContainer").attr("class")]);
				}
			}
		}
		else {
			document.getElementById('actionForm_error').style.display = '';
			document.getElementById('actionForm_thankyou').style.display = 'none';	
			document.getElementById('actionForm_content').style.display = 'none';
			document.getElementById('actionForm_loading').style.display = 'none';
			
			if( $j('div.inside #actionForm').length && (formData.id == "8" || formData.id == "1") ){
				$j('div.inside #actionForm').parent().css('text-align','center').html( $j('#actionForm_error').html() );
			}
			
			// Track for GA
			if(typeof _gaq == "object") {
				_gaq.push(["_trackEvent", "Forms", "Submit - Error", $j("form", "#formContainer").attr("class")]);
			}
		}
	};
	//alert(postStr);
	formPosting.update(postStr, 'post');
}

// for clickable badness
var _cctq = _cctq || [];

