function flashLoader(flashMovie, flashVars, flashHeight, flashWidth, flashAlign, flashQuality, flashBGColor, flashID, flashScale) {
	var flashPluginSpace = '';
	var codebase = '';

	if (flashVars.indexOf('ssl=true') != -1 || flashMovie.indexOf('https://') != -1) {
		codebase = 'https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0';
		flashPluginSpace = 'https://www.macromedia.com/go/getflashplayer';
	} else { 
		codebase = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0';
		flashPluginSpace = 'http://www.macromedia.com/go/getflashplayer';
	}
	
	document.write('<object type="application/x-shockwave-flash" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="' + codebase + '" width="' + flashWidth + '" height="' + flashHeight + '" id="' + flashID + '" align="' + flashAlign + '">');
	document.write('<param name="flashvars" value="' + flashVars + '">');
	document.write('<param name="movie" value="' + flashMovie + '">');
	document.write('<param name="quality" value="' + flashQuality + '">');

	if (flashScale == null) {
		var flashScale = '';
		var flashScaleParam = '';
	} else {
		document.write('<param name="scale" value="' + flashScale + '">');
		var flashScaleParam = ' scale="' + flashScale + '"';
	}

	document.write('<param name="bgcolor" value="' + flashBGColor + '">');
	document.write('<param name="wmode" value="transparent">');
	document.write('<param name="allowscriptaccess" value="always">');
	document.write('<embed src="' + flashMovie + '" quality="' + flashQuality + '"' + flashScaleParam + ' bgcolor="' + flashBGColor + '"  width="' + flashWidth + '" height="' + flashHeight + '" name="' + flashID + '" align="' + flashAlign + '" TYPE="application/x-shockwave-flash" pluginspage="' + flashPluginSpace + '" flashvars="' + flashVars + '" wmode="transparent" allowscriptaccess="always"></embed>');
	document.write('</object>');
}

function OpenWindow(url,name,w,h){
	if (typeof(wl_bj_pre) != 'undefined')
		url = wl_bj_pre + url;

	window.open(url,name,'width='+w+',height='+h);
}

function OpenWindowResizable(url,name,w,h){
	if (typeof(wl_bj_pre) != 'undefined')
		url = wl_bj_pre + url;

	window.open(url,name,'width='+w+',height='+h+',resizable=1');
}

var _width, _height;
var _openedUrl;
var _popupObject;
var _documentHead;

function OpenWindowCenter(url, name, width, height, scroll, title){
	if (url.indexOf('embedded=true') == -1) {
		var params = '';

		if (scroll){
			params += 'scrollbars=yes, ';
			width = width + 16;
		} 

		var scrX = (document.all)?window.screenLeft:window.screen.left;
		var left   = scrX + (window.screen.width  - width)/2;
		var top    = (window.screen.height - height)/2;
		
		params += 'width=' + width + ', height=' + height;
		params += ', top=' + top+', left=' + left;

		if (typeof(wl_bj_pre) != 'undefined')
			url = wl_bj_pre + url;

		popupWin = window.open(url, name, params);

		if(popupWin != null)
			popupWin.focus();
	} else {
		_width = width;
		_height = height;
		_openedUrl = url;
		_popupObject = $('<div id="PopupLoaderPopupContent">'+ globalPopupHeader.replace('{PopupHeader}', title) + 
			'<iframe src="'+url+'" frameborder="0" scrolling="no" width="'+width+'" height="'+height+'"></iframe></div>').modal({
			zIndex: 20000,
			close: true,
			positionStyle: 'absolute',
			containerCss: {width: _width, height: _height},
			containerId: 'PopupLoaderContainer',
			position: [73,]
		});
		$('body').animate({scrollTop:0}, 'slow');

		$('.ClosePopup').bind('click.simplemodal', function (e) {
			e.preventDefault();
			if (document.getElementById('_extIntViewContainer')!=null) 
				document.getElementById('_extIntViewContainer').style.visibility='visible';
			_popupObject.close();
		});
	}
}

function closeSelf() {
	window.open('','_parent','');
	window.opener = top;
	window.close();
}

function checkEmail(emailCtrl) {
	var email = emailCtrl.value;
	return checkEmailStr(email);
}

function checkEmailStr(email) {
	if(!(/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/.test(trim(email))))
		return false;
	else 
		return true;
}

function checkEmpty(ctrl) {
	if (ctrl.value.length > 0)
		return true;
	else
		return false;
}

function checkAllowedChars(ctrl) {
	var regularExpression = /<|>|\\/;

	return !regularExpression.test(ctrl.value);
}

function checkDate(dateElm) {
	var date;

	if(dateElm.value != null)
		date = dateElm.value;
	else
		date = dateElm;

	if(((/^([1-9]|0[1-9]|1[012]|)[- /.]([1-9]|0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d/.test(date))))
		return true;

	return false;
}

function checkOfferPrice(offerElm) {
	var offer = offerElm.value;

	if(!(/^(\$)?([0-9]+|[0-9]{1,3}(,[0-9]{3})*)$/.test(offer)))
		return false;
	else
		return true;
}

// Standard
function trim(str) {
	var i,j;
	i = 0;
	j = str.length - 1;
	str = str.split("");

	while(i < str.length) {
		if(str[i]==" ")
			str[i] = ""
		else
			break;

		i++;
	}

	while(j > 0) {
		if(str[j]== " ")
			str[j]=""
		else
			break;

		j--;
	}

	return str.join("");
}

function remove(str) {
}

/* !!! All the Page specific functionality please put below */


/*  Site map and google should be moved to proper lib */
/* Begin code for SiteMap mouseover popup */
function googleMapSubmit() {
	s0 = document.getElementById('tmpAddr');
	s1 = document.getElementById('tmpAddr1');
	s2 = document.getElementById('tmpAddr2');
	s0.value = s1.value + ', ' + s2.value;
}

var delay=null;
var delaySecs=500;
var current=null;

function isIE6() {
	version = 0;
	if (navigator.appVersion.indexOf("MSIE") != -1) {
		tempVer = navigator.appVersion.split("MSIE");
		version = parseFloat(tempVer[1]);
	}
	return (version == 6) ? true:false
}

function mX(evt) {
	if (evt.pageX) return evt.pageX;
	else if (evt.clientX) return evt.clientX + (document.documentElement.scrollLeft ?
	   document.documentElement.scrollLeft :
	   document.body.scrollLeft);
	else return null;
}

function mY(evt) {
	if (evt.pageY) return evt.pageY;
	else if (evt.clientY) return evt.clientY + (document.documentElement.scrollTop ?
	   document.documentElement.scrollTop :
	   document.body.scrollTop);
	else return null;
}
/* End code for SiteMap mouseoverpopup */

function ExecuteCampaignConversionTrackingCode(siteDefaultUrl) {
	//we need to create hidden DIV to append object to it
	var oDiv = document.createElement('div');

	window.onload = function(){
		document.body.appendChild(oDiv);
	}

	oDiv.style.visibility = "hidden";
	var pathToFile = siteDefaultUrl + "shared/campaignconversiontrackingcode/campaignconversiontrackingcode.aspx";

	try {
		var obj = document.createElement('object');
		//this object contains data for Conversion Tracking
		obj.data = pathToFile; 

		if (!isIE6())
			obj.type = "text/html";

		oDiv.appendChild(obj);

		if (isIE6())
			obj.classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13";
	}
	catch (err){
	}
}

function ExecuteConversionTrackingCode(id, conversionTrackingCode) {
	$(id).append(conversionTrackingCode);
}

function FixPngTransparency() {
	var elements = document.getElementsByTagName('img');
	var mask=/\.png/i;
	var index=elements.length;

	while(index-- > 0) {
		var element = elements[index];
		var style=element.style;

		if (element.src && element.src.match(mask) && !style.filter)
			style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+element.src+"',sizingMethod='crop')";
	}
}

if (isIE6()) window.attachEvent('onload', FixPngTransparency);

function getSelectedText(id) {
	var el = document.getElementById(id);
	var index = el.selectedIndex;

	if (typeof(index) != 'undefined')
		return el.getElementsByTagName('option')[index].innerHTML;
	else
		return null;
}

/* ajax calls for items */
function getItemsAdvancedSearchDataMakes(hostURL, siteId, newUsedCpoCtrlId, makeCtrlId, modelCtrlId) {
	var newUsedCpo = $("#" + newUsedCpoCtrlId).val();
	if (newUsedCpo == '0') {
		$("#" + makeCtrlId).empty().append('<option value="">Select Make</option>');
		return;
	} else
		$("#" + makeCtrlId).empty().append('<option value="">Loading...</option>');

	$("#" + modelCtrlId).empty().append('<option value="">Select Model</option>');
	$.ajax({
		type: "POST",
		url: hostURL + "masterpagewebservice.asmx/GetItemsAdvancedSearchDataMakes",
		data: "{ siteId: " + siteId + ", isNew:" + (newUsedCpo == '1') + ", isCpo: " + (newUsedCpo == '3') + "}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			var makes = (typeof response) == 'string' ? eval('(' + response + ')') : response;
			var makesList = $("#" + makeCtrlId).empty().append('<option value="">Select Make</option>');
			for (var i = 0; i < makes.length; i++)
				makesList.append('<option value="' + makes[i] + '">' + makes[i] + '</option>')
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}


function getItemsAdvancedSearchDataModels(hostURL, siteId, newUsedCpoCtrlId, makeCtrlId, modelCtrlId) {
	var newUsedCpo = $("#" + newUsedCpoCtrlId).val();
	var make = $("#" + makeCtrlId).val();
	if (newUsedCpo == '0') {
		$("#" + makeCtrlId).empty().append('<option value="">Select Make</option>');
		return;
	} else if (make == '') {
		$("#" + modelCtrlId).empty().append('<option value="">Select Model</option>');
		return;
	} else
		$("#" + modelCtrlId).empty().append('<option value="">Loading...</option>');
		
	$.ajax({
		type: "POST",
		url: hostURL + "masterpagewebservice.asmx/GetItemsAdvancedSearchDataModels",
		data: "{ siteId: " + siteId + ", isNew:" + (newUsedCpo == '1') + ", isCpo: " + (newUsedCpo == '3') + ", make:'" + make + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			var models = (typeof response) == 'string' ? eval('(' + response + ')') : response;
			var modelsList = $("#" + modelCtrlId).empty().append('<option value="">Select Model</option>');
			for (var i = 0; i < models.length; i++)
				modelsList.append('<option value="' + models[i] + '">' + models[i] + '</option>')
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}


function GetModelHomePageAdvancedSearchContent(hostURL, makeControlID, modelControlID, yearFromControlID, yearToControlID, bodyStyleControlID, siteId, country) {
	var make = $("#" + makeControlID).val();
	$("#"+modelControlID).empty().append('<option value="">Loading...</option>');
	$.ajax({
		type: "POST",
		url: hostURL + "masterpagewebservice.asmx/GetModelHomePageAdvancedSearchContent",
		data: "{make: '"+make+"', siteId: "+siteId+"}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			var models = (typeof response) == 'string' ? eval('(' + response + ')') : response;
			var modelsList = $("#"+modelControlID);
			modelsList.empty().append('<option value="">Select Model</option>');
			for (var i = 0; i < models.length; i++)
				modelsList.append('<option value="' + models[i] + '">' + models[i] + '</option>')

			GetYearsHomePageAdvancedSearchContent(hostURL, makeControlID, modelControlID, yearFromControlID, yearToControlID, bodyStyleControlID, siteId, country);
			GetBodyStylesHomePageAdvancedSearchContent(hostURL, makeControlID, modelControlID, bodyStyleControlID, siteId, country);
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}

function GetYearsHomePageAdvancedSearchContent(hostURL, makeControlID, modelControlID, yearFromControlID, yearToControlID, bodyStyleControlID, siteId, country) {
	var make = $("#"+makeControlID).val();
	var model = $("#"+modelControlID).val();

	$("#" + yearFromControlID).empty().append('<option value="">Loading...</option>');
	$("#" + yearToControlID).empty().append('<option value="">Loading...</option>');

	$.ajax({
		type: "POST",
		url: hostURL + "masterpagewebservice.asmx/GetYearsHomePageAdvancedSearchContent",
		data: "{make: '"+make+"', model: '"+model+"', siteId: "+siteId+"}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			var years = (typeof response) == 'string' ? eval('(' + response + ')') : response;

			$("#"+yearFromControlID).empty().append('<option value="">Low Year</option>');
			for(var i = years.length - 1; i >= 0; i--)
				$("#"+yearFromControlID).append('<option value="' + years[i] + '">' + years[i] + '</option>')
			$("#"+yearToControlID).empty().append('<option value="">High Year</option>');
			for (var j = 0; j < years.length; j++)
				$("#"+yearToControlID).append('<option value="' + years[j] + '">' + years[j] + '</option>')

			GetBodyStylesHomePageAdvancedSearchContent(hostURL, makeControlID, modelControlID, bodyStyleControlID, siteId, country);
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}

function GetBodyStylesHomePageAdvancedSearchContent(hostURL, makeControlID, modelControlID, bodyStyleControlID, siteId, country) {
	var make = $("#"+makeControlID).val();
	var model = $("#"+modelControlID).val();

	$("#"+bodyStyleControlID).empty().append('<option value="">Loading...</option>');

	var bodyStylesTemp = [];

	$.ajax({
		type: "POST",
		url: hostURL + "masterpagewebservice.asmx/GetBodyStylesHomePageAdvancedSearchContent",
		data: "{make: '"+make+"', model: '"+model+"', siteId: "+siteId+", country: "+country+"}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			var bodyStyles = (typeof response) == 'string' ? eval('(' + response + ')') : response;
			$("#"+bodyStyleControlID).empty().append('<option value="">Select Body Style</option>');
			for (var i = 0; i < bodyStyles.length; i++) {
				bodyStylesTemp[i] = eval('(' + bodyStyles[i] + ')');
				$("#"+bodyStyleControlID).append('<option value="' + bodyStylesTemp[i].Value + '">' + bodyStylesTemp[i].Name + '</option>')
			}
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}

function homePageAdvancedSearchReset(makeControlID, modelControlID, yearFromControlID, yearToControlID, bodyStyleControlID, priceFromNameControlID,
									priceToNameControlID, milesFromNameControlID, milesToNameControlID, cpoNameControlID, cpoDealerNameControlID) {
	$("#"+makeControlID).val("");
	$("#"+modelControlID).val("");
	$("#"+yearFromControlID).val("");
	$("#"+yearToControlID).val("");
	$("#"+bodyStyleControlID).val("");
	$("#"+priceFromNameControlID).val("");
	$("#"+priceToNameControlID).val("");
	$("#"+milesFromNameControlID).val("");
	$("#"+milesToNameControlID).val("");

	if(!isNullOrEmpty($("#"+cpoNameControlID)))
		$("#"+cpoNameControlID).removeAttr('checked');

	if(!isNullOrEmpty($("#"+cpoDealerNameControlID)))
		$("#"+cpoDealerNameControlID).removeAttr('checked');
}

function homePageAdvancedSearch(formControlID, makeControlID, modelControlID, yearFromControlID, yearToControlID,
								bodyStyleControlID, makeNameHiddenControlID, modelNameHiddenControlID,
								yearFromNameHiddenControlID, yearToNameHiddenControlID,bodyStyleNameHiddenControlID) {

	$("#"+makeNameHiddenControlID).val($("#"+makeControlID).val());
	$("#"+modelNameHiddenControlID).val($("#"+modelControlID).val());
	$("#"+yearFromNameHiddenControlID).val($("#"+yearFromControlID).val());
	$("#"+yearToNameHiddenControlID).val($("#"+yearToControlID).val());
	$("#"+bodyStyleNameHiddenControlID).val($("#"+bodyStyleControlID).val());

	$("#"+formControlID).submit();
}

/* End HomePageAdvancedSearch */

/* Begin DetailPage */
var numPopups = 3; 

function processGetAQuoteOnClickEvent(firstNameRequired, lastNameRequired, phoneRequired){
	if (IsGetAQuoteFormValid(firstNameRequired, lastNameRequired, phoneRequired)) {
		var span = document.getElementById('_txtGetAQuoteClientEmail');

		if (span != null) {
			span.innerHTML = document.getElementById('_txtGetAQuoteEmail').value;
		}

		submitGetAQuote();
	}
}

function IsEmailStringValid(email) {
	if(!(/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/.test(email))) {
		return false;
	} else {
		return true;
	}	
}

function IsEmpty(ctrl) {
	if (ctrl.value.length > 0)
		return false;
	else
		return true;
}

function IsGetAQuoteFormValid(firstNameRequired, lastNameRequired, phoneRequired) {
	var inputField;
	var resultString = '';
	
	if (firstNameRequired) {
		inputField = document.getElementById('_txtGetAQuoteFirstName');
		if (IsEmpty(inputField)) 
			resultString += 'Please fill out first name.\n';
	}
	if (lastNameRequired) {
		inputField = document.getElementById('_txtGetAQuoteLastName');
		if (IsEmpty(inputField)) 
			resultString += 'Please fill out last name.\n';
	}

	if (phoneRequired) {
		inputField = document.getElementById('_txtGetAQuotePhone');
		if (IsEmpty(inputField)) 
			resultString += 'Please enter phone number.\n';
	}
	
	inputField = document.getElementById('_txtGetAQuoteEmail');
	if (!IsEmailStringValid(inputField.value))
		resultString += 'Email address has wrong format.\n';
			
	if (resultString.length > 0) {
		alert(resultString);
		return false;
	}

	return true;
}

// Media Viewer
var mediaViewerUrl = '';
function OpenMediaViewer(tab) {
	PageTracking(23, false, false, true,'',false);
	_popupObject = $('<div id="MVContainer"><div class="ClosePopupBtn" onmouseover="this.className=\'ClosePopupBtn_hover\'" onmouseout="this.className=\'ClosePopupBtn\'"><b></b></div><div class="MVContainerInner"></div></div>').modal({
		zIndex: 20000,
		close: true,
		positionStyle: 'absolute',
		containerCss: { width: 821 },
		containerId: 'PopupLoaderContainer',
		position: [40,]
	});

	$('body').animate({scrollTop:0}, 'slow');

	$('#MVContainer .ClosePopupBtn').bind('click.simplemodal', function (e) {
		e.preventDefault();
		_popupObject.close();
	});
	$.ajax({
		type: 'POST',
		url: mediaViewerUrl + '&tab=' + tab,
		success: function(response) {
			$('#MVContainer .MVContainerInner').html(response);
		},
		error: function(obj, msg) {
			$('#MVContainer .MVContainerInner').html('<div style="height:200px">Error occured while loading content.</div>');
		}
	});
}

function SwitchMediaViewerTab(n,count,id) {
	var tabSelected, divSelected;
	for (tabSelected = 1; tabSelected <= count; tabSelected++) {
		if (tabSelected != n) {
			divSelected = document.getElementById(id + tabSelected);
			if (divSelected != null && divSelected.className != 'mvtab')
				break
		}
	}
	if (divSelected && tabSelected <= count) { // to fast clicking 
		divSelected.className = 'mvtab';
		document.getElementById(id + tabSelected + 'Content').style.display = 'none';
		document.getElementById(id + n + 'Content').style.display = 'block';
		document.getElementById(id + n).className = 'mvtab_s';
	}
}

// Media Viewer end

// Share Video Form begin
function ReturnToMediaViewer() {
	var link = document.getElementById('returnToMediaViewer').value;
	location.replace(link);
}

function validateShareVideoControls() {
	var errorMessage = "";
	var firstNameCtrl = document.getElementById('txtName');
	var error = false;
	if (!checkEmpty(firstNameCtrl)) {
		errorMessage = errorMessage + "- Please provide your name. \n";
		error = true;
	} else {
		if (!checkAllowedChars(firstNameCtrl)) {
			errorMessage = errorMessage + "- Chars '<' and '>' are not allowed in Your Name \n";
			error = true;
		} 
	}
	
	if (!checkEmail(document.getElementById('txtYourEmail'))) {
		error = true;
		errorMessage =  errorMessage + "- Please provide your email address  \n";
	}
	var emails = document.getElementById('txtRecipientEmails').value.replace(/\s/gi," ").split(',');
	for(i = 0; i < emails.length; i++) {
		if (trim(emails[i]).length > 0 && !checkEmailStr(trim(emails[i]))) {
			error = true;
			errorMessage =  errorMessage + "- Please provide correct recepient email addresses (separated by commas)  \n";
			break;
		}
	}
	if (!checkAllowedChars(document.getElementById('txtMessage'))) {
		error = true;
		errorMessage =  errorMessage + "- - Chars '<' and '>' are not allowed in Personal Message text \n";
	}
	if (error)
		alert('You must enter a proper value in the following fields:\n' + errorMessage);
		
	return !error;
}

function clearShareVideoControls() {
	document.getElementById('txtName').value = "";
	document.getElementById('txtYourEmail').value = "";
	document.getElementById('txtRecipientEmails').value = "";
	document.getElementById('txtMessage').value = "";
	document.getElementById('chkSendCopy').checked = false;
}

// Share Video Form begin
function OpenPrintModal() {
	var _popupObject;
	_popupObject = $("#PrintModalContent").modal({
		zIndex: 20000,
		close: true,
		positionStyle: 'absolute',
		position: [20,]
	});

	$("body").animate({scrollTop:0}, "slow"); 

	$('.ClosePopup').bind('click.simplemodal', function (e) {
		e.preventDefault();
		_popupObject.close();
	});
}

var isActive = false;
var isActiveLinks = false;
var timeId = 0;

function hideLinksPopup() {
	if (!isActive && !isActiveLinks) {
		var div = document.getElementById("SocialLinksPopup");
		div.style.display = "none";
		div = document.getElementById("SocialLinksIcons");
		div.style.borderBottom = '';
	} else {
		timeId = setTimeout(hideLinksPopup, 200);
	}
}

function showLinksPopup() {
	var div = document.getElementById("SocialLinksPopup");
	div.style.display = "block";
	div = document.getElementById("SocialLinksIcons");
	div.style.borderBottom = 'solid 1px #ffffff';
}

function on_mouseoverSocialBookmarking() {
	if (!isActive) {
		isActive = true;
		showLinksPopup();
	}

	clearTimeout(timeId);
	timeId = setTimeout(hideLinksPopup, 200);
}

function on_mouseoverLinks() {
	if (!isActiveLinks) {
		isActiveLinks = true;
		showLinksPopup();
	}

	clearTimeout(timeId);
	timeId = setTimeout(hideLinksPopup, 200);
}

function on_mouseoutLinks() {
	isActiveLinks = false;
}

/* End DetailPage */

/* Begin InventoryPage */
function OnMouseOverImg(id, over) {
	var img1 = document.getElementById(id);
	var img2 = document.getElementById(id + 'hover');
	if (over) {
		img1.style.display = 'none';
		img2.style.display = 'inline';
	} else {
		img1.style.display = 'inline';
		img2.style.display = 'none';
	}
}
function OnMouseOverSection(id, over, hoverColor) {
	var content = document.getElementById(id + 'Body');
	OnMouseOverImg(id + (content.style.display != 'none' ? 'Close' : 'Open'), over);
	if (over)
		document.getElementById(id + 'Hdr').style.color = hoverColor;
	else
		document.getElementById(id + 'Hdr').style.color = '';;
}

function SwitchVisibility(id) {
	var content = document.getElementById(id + 'Content');
	if (content.style.display != 'none') {
		content.style.display = 'none';
		document.getElementById(id + 'Close').style.display = 'none';
		document.getElementById(id + 'Open').style.display = 'inline';
	} else {
		content.style.display = 'block';
		document.getElementById(id + 'Close').style.display = 'inline';
		document.getElementById(id + 'Open').style.display = 'none';
	}
}

// show / hide tip text
function onfocus_input(tipText, ID, className) {
	var inputControl = document.getElementById(ID);
	if (className)
		inputControl.className = className;

	if (inputControl.value == tipText)
		inputControl.value = "";
}
function onblur_input(tipText, ID, className) {
	var inputControl = document.getElementById(ID);

	if (inputControl.value == "") {
		if (className)
			inputControl.className = className;
		inputControl.value = tipText;
	}
}

function RefineSearchYears(url, ctrYearLowName, ctrYearHighName) {
	var newQuery = '';
	var path = '';

	if (url.indexOf('?') != -1) {
		path = url.substring(0, url.indexOf('?') + 1);
		newQuery = url.substring(url.indexOf('?') + 1);
	} else
		path = url;

	if (newQuery.length > 0)
		newQuery += '&';
	else
		newQuery = '?';

	var ctrYearLow = document.getElementById(ctrYearLowName);
	var ctrYearHigh = document.getElementById(ctrYearHighName);
	var yearLow, yearHigh;

	if (ctrYearLow.value > ctrYearHigh.value) {
		yearLow = ctrYearHigh.value;
		yearHigh = ctrYearLow.value;
	} else {
		yearLow = ctrYearLow.value;
		yearHigh = ctrYearHigh.value;
	}

	newQuery = path + newQuery + ctrYearLow.name + '=' + yearLow + '&' + ctrYearHigh.name + '=' + yearHigh;
	window.location.href = newQuery;
}

function setPageSize(rows, refreshURL) {
	var expire = new Date();

	expire.setTime (expire.getTime() + (2592000000)); //30 days from now!
	document.cookie = 'EBizAutosBuyersSiteCookiePageSize=' + rows + ';expires=' + expire.toGMTString() + ';path=/';

	if (refreshURL == '?') {
		refreshURL = document.URL;

		var pos = refreshURL.indexOf('?');

		if (pos != -1)
			refreshURL = refreshURL.substr(0, pos);
	}

	if (refreshURL == '')
		refreshURL = document.URL;
	
	if (document.all) { // if is IE
		window.navigate(refreshURL);
	} else {
		window.location.reload(true);
		window.location.href = refreshURL;
	}
}

function setInventoryView(view, refreshURL) {
	var expire = new Date();

	expire.setTime (expire.getTime() + (2592000000)); //30 days from now!
	document.cookie = 'EBizAutosBuyersSiteCookieInventoryView=' + view + ';expires=' + expire.toGMTString() + ';path=/';

	if (refreshURL == '?') {
		refreshURL = document.URL;

		var pos = refreshURL.indexOf('?');

		if (pos != -1)
			refreshURL = refreshURL.substr(0, pos);
	}

	if (refreshURL == '')
		refreshURL = document.URL;
	
	if (document.all) { // if is IE
		window.navigate(refreshURL);
	} else {
		window.location.reload(true);
		window.location.href = refreshURL;
	}
}

function toggleHeaderDescriptionText() {
	var span = $("#DescriptionText span");
	var link = $("#DescriptionText a.moreLessLink");
	if (span.css("display") == "none") {
		span.css("display", "inline");
		link.html("less");
	} else {
		span.css("display", "none");
		link.html("more");
	}
}

function TruncateChromeDescription(link, desiredHeight) {
	var description = document.getElementById("DescriptionText");
	if (description) {
		if (description.offsetHeight > desiredHeight) {
			var hiddenSpan = '<span>';
			var text = description.innerHTML + ' ' + hiddenSpan + ' ' + '</span>... <a class="moreLessLink" href=\"' + link + '\">more</a>';
			var wordsArray = text.split(' ');
			var lastPos = jQuery.inArray(hiddenSpan.toString(), wordsArray);
			description.innerHTML = text;
			for (i=lastPos; i>0; i--){
				wordsArray[i] = wordsArray[i-1];
				wordsArray[i-1] = hiddenSpan;
				description.innerHTML = wordsArray.join(' ');
				$("#DescriptionText span").css("display", "none");
				if (description.offsetHeight < desiredHeight) {
					break;
				}
			}
		}
		description.style.visibility = 'visible';
	}
}

function selectShowLocation(showLocation, url) {
	var value = showLocation.options[showLocation.selectedIndex].value

	if (value != "none") {
		window.location.href = url + value;
	}
}

/* End InventoryPage */

/* Begin PaymentCalculator */
// Loan section
var salesPriceLoan = 0.00;
var salesTaxLoan = 0.00;
var loanTermLoan = 0.00;
var interestRateLoan = 0.00;
var downPaymentLoan = 0.00;
var tradeInValueLoan = 0.00;
var rebatesLoan = 0.00;

// Lease section
var salesPriceLease = 0.00;
var salesTaxLease = 0.00;
var loanTermLease = 0.00;
var interestRateLease = 0.00;
var residualValueLease = 0.00;
var downPaymentLease = 0.00;
var tradeInValueLease = 0.00;
var rebatesLease = 0.00;

function CalculateLoan(id) {
	salesPriceLoan = 0.00;
	salesTaxLoan = 0.00;
	loanTermLoan = 0.00;
	interestRateLoan = 0.00;
	downPaymentLoan = 0.00;
	tradeInValueLoan = 0.00;
	rebatesLoan = 0.00;

	var loan = document.getElementById('loan' + id);
	var loanAmount = document.getElementById('loanAmount' + id);
	var loanAmountWarning = document.getElementById('loanAmountWarning' + id);

	loanAmountWarning.style.display = 'none';

	if (doLoanValidation(id)) {
		interestRateLoan = interestRateLoan / 100;
		interestRateLoan = interestRateLoan / 12;
		salesTaxLoan = salesTaxLoan / 100;

		var loanAmt = (salesPriceLoan * (1 + salesTaxLoan)) - downPaymentLoan - tradeInValueLoan - rebatesLoan;
		var loanPayment = loanAmt * (interestRateLoan * Math.pow(1 + interestRateLoan, loanTermLoan)) / (Math.pow(1 + interestRateLoan, loanTermLoan) - 1);

		if (loanPayment < 0.00 || isNaN(loanPayment) )
			loanPayment = 0.00;

		loan.innerHTML = loanPayment.toFixed(2);
		loanAmount.style.display = '';
		loanAmountWarning.style.display = 'none';
	} else {
		loanAmount.style.display = 'none';
		loanAmountWarning.style.display = '';
	}
}

function CalculateLease(id) {
	salesPriceLease = 0.00;
	salesTaxLease = 0.00;
	loanTermLease = 0.00;
	interestRateLease = 0.00;
	residualValueLease = 0.00;
	downPaymentLease = 0.00;
	tradeInValueLease = 0.00;
	rebatesLease = 0.00;

	var lease = document.getElementById('lease' + id);
	var leaseAmount = document.getElementById('leaseAmount' + id);
	var leaseAmountWarning = document.getElementById('leaseAmountWarning' + id);

	leaseAmountWarning.style.display = 'none';

	if (doLeaseValidation(id)) {
		if (salesTaxLease >= 1)
			salesTaxLease = salesTaxLease / 100;

		var clearPrice = salesPriceLease - downPaymentLease - tradeInValueLease - rebatesLease;
		var loanAmount = clearPrice - residualValueLease; 
		var basePayment = 0.00;

		if(loanTermLease >= 1)
			basePayment = loanAmount / loanTermLease;

		basePayment = Math.round(basePayment * 100) / 100;
		var moneyFactor = interestRateLease / 2400;

		moneyFactor = Math.round(moneyFactor * 100000) / 100000;

		var leasePayment = (clearPrice + residualValueLease) * moneyFactor + basePayment;
		leasePayment = Math.round(leasePayment * 100) / 100;
		leasePayment = leasePayment + leasePayment * salesTaxLease;

		if (leasePayment < 0.00 || isNaN(leasePayment) )
			leasePayment = 0.00;

		lease.innerHTML = leasePayment.toFixed(2);
		leaseAmount.style.display = '';
		leaseAmountWarning.style.display = 'none';
	} else {
		leaseAmount.style.display = 'none';
		leaseAmountWarning.style.display = '';
	}
}

function doCalculation(id) {
	if (document.getElementById('loan' + id))
		CalculateLoan(id);
	if (document.getElementById('lease' + id))
		CalculateLease(id);
}

// Lease code
function doLeaseValidation(id) {
	if (doFieldValidation(document.getElementById('_txtSalesPriceLease' + id), false))
		salesPriceLease = parseFloat(document.getElementById('_txtSalesPriceLease' + id).value);
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtSalesTaxLease' + id), true))
		salesTaxLease = parseFloat(document.getElementById('_txtSalesTaxLease' + id).value);
	else if (isEmpty(document.getElementById('_txtSalesTaxLease' + id).value))
		salesTaxLease = 0;
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtTermLease' + id), false))
		loanTermLease = parseFloat(document.getElementById('_txtTermLease' + id).value);
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtInterestRateLease' + id), false))
		interestRateLease = parseFloat(document.getElementById('_txtInterestRateLease' + id).value);
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtResidualValueLease' + id), false))
		residualValueLease = parseFloat(document.getElementById('_txtResidualValueLease' + id).value);
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtDownPaymentLease' + id), true))
		downPaymentLease = parseFloat(document.getElementById('_txtDownPaymentLease' + id).value);
	else if (isEmpty(document.getElementById('_txtDownPaymentLease' + id).value))
		downPaymentLease = 0;
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtTradeInValueLease' + id), true))
		tradeInValueLease = parseFloat(document.getElementById('_txtTradeInValueLease' + id).value);
	else if (isEmpty(document.getElementById('_txtTradeInValueLease' + id).value))
		tradeInValueLease = 0;
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtRebatesLease' + id), true))
		rebatesLease = parseFloat(document.getElementById('_txtRebatesLease' + id).value);
	else if (isEmpty(document.getElementById('_txtRebatesLease' + id).value))
		rebatesLease = 0;
	else
		return false;

	return true;
}

// Loan code
function doLoanValidation(id) {
	if (doFieldValidation(document.getElementById('_txtSalesPriceLoan' + id), false))
		salesPriceLoan = parseFloat(document.getElementById('_txtSalesPriceLoan' + id).value);
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtSalesTaxLoan' + id), true))
		salesTaxLoan = parseFloat(document.getElementById('_txtSalesTaxLoan' + id).value);
	else if (isEmpty(document.getElementById('_txtSalesTaxLoan' + id).value))
		salesTaxLoan = 0;
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtTermLoan' + id), false))
		loanTermLoan = parseFloat(document.getElementById('_txtTermLoan' + id).value);
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtInterestRateLoan' + id), false))
		interestRateLoan = parseFloat(document.getElementById('_txtInterestRateLoan' + id).value);
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtDownPaymentLoan' + id), true))
		downPaymentLoan = parseFloat(document.getElementById('_txtDownPaymentLoan' + id).value);
	else if (isEmpty(document.getElementById('_txtDownPaymentLoan' + id).value))
		downPaymentLoan = 0;
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtTradeInValueLoan' + id), true))
		tradeInValueLoan = parseFloat(document.getElementById('_txtTradeInValueLoan' + id).value);
	else if (isEmpty(document.getElementById('_txtTradeInValueLoan' + id).value))
		tradeInValueLoan = 0;
	else
		return false;

	if (doFieldValidation(document.getElementById('_txtRebatesLoan' + id), true))
		rebatesLoan = parseFloat(document.getElementById('_txtRebatesLoan' + id).value);
	else if (isEmpty(document.getElementById('_txtRebatesLoan' + id).value))
		rebatesLoan = 0;
	else
		return false;

	return true;
}

function doFieldValidation(field, isEmptyAllowed) {
		var input = field.value;
		
		if (!isEmptyAllowed && isEmpty(input)) {
			select(field);
			return false;
		} else if (isEmptyAllowed && isEmpty(input))
			return false;

		input = parseFloat(field.value, 10);

		if (isNaN(input) || (input != field.value)) {
			alert(field.name + " must be a number.");
			select(field);
			return false;
		}

		return true;
}

function isEmpty(inputStr) {
	if (inputStr == "" || inputStr == null)
		return true;

	return false;
}

function select(field) {
	field.focus();
	field.select();
}

function SwitchToLease(id) {
	var div = document.getElementById('_loanCalculator' + id);
	div.style.display = 'none';
	div = document.getElementById('_leaseCalculator' + id);
	div.style.display = 'block';
}

function SwitchToLoan(id) {
	var div = document.getElementById('_loanCalculator' + id);
	div.style.display = 'block';
	div = document.getElementById('_leaseCalculator' + id);
	div.style.display = 'none';
}

/* End PaymentCalculator */

/* Begin PrintAd */

function resizePrintAdImage(el) {
			if ($(el).width() > 870) {
				$(el).width(870);
			}
}

/* End PrintAd * /

/* Begin QuickQuote */
var QQerrorString = 'Please enter the required information';
var QQYearErrorString = 'Required';
var ZipCodeError = 'Please provide a 5 digit numeric zip code';

function onQQinput_focus(obj) {
	if (obj.value == QQerrorString || obj.value == QQYearErrorString || ZipCodeError) {
		obj.value = '';
	}
	obj.style.color = '';
}

$(document).ready(function () {
		setInterval('VehicleRowCycle()', 100);
		
		$("#udm").mousemove( function(event) {
			removeSelect();
		});

		$('#QuickQuoteButton input.basic, #QuickQuoteButtonHover input.basic, #QuickQuoteButton a.basic, #QuickQuoteButton div.basic, span.specialItemClickHere, div.specialItemRightSideBoxClickHere').click(function (e) {
			e.preventDefault();

			InitializationQuickQuote();
		});

		syncPopup();
		syncFreeFormPopup();
	});

function removeSelect() {
	$("#QuickQuoteMake").blur();
	$("#QuickQuoteModel").blur();
	$("#YearFrom").blur();
	$("#YearTo").blur();
}

function syncPopup() {
	if($("#MakeIDHidden").val() != null)
		$("#QuickQuoteMakeModal").val($("#MakeIDHidden").val());
}

function InitializationQuickQuote() {
	var specialQuoteArrows = document.getElementById('specialQuoteArrows');
	var widthQuickQuote;

	if (specialQuoteArrows)
		specialQuoteArrows.style.visibility = 'hidden';

	var hasToDisplayFreeForm = $('#HasToDisplayFreeFormHidden').val()

	if(hasToDisplayFreeForm == 'False')
		syncPopup();
	else
		syncFreeFormPopup();

	if($.browser.msie)
		widthQuickQuote = '590px';
	else
		widthQuickQuote = '610px';


	$('#QuickQuotePopup').modal({
			zIndex: 20000,
			close: true,
			containerId: 'QuickQuoteContainer',
			positionStyle: 'absolute',
			containerCss: {width: widthQuickQuote},
			position: [73,],
			onHide: function() {
				if (specialQuoteArrows)
					specialQuoteArrows.style.visibility = 'visible';
			}
		});


	$('.ClosePopup').bind('click.simplemodal', function (e) {
		e.preventDefault();
	});
	$('body').animate({scrollTop:0}, 'slow'); 
}

function syncFreeFormPopup() {
	$('#QuickQuoteMakeModalInput').val($('#MakeNameHidden').val());
	$('#QuickQuoteModelModalInput').val($('#ModelNameHidden').val());
	$('#QuickQuoteYearFromModalInput').val($('#YearFromHidden').val());
	$('#QuickQuoteYearToModalInput').val($('#YearToHidden').val());
}

function getModels(hostURL, accountId, isCrossPromotionOn, isModelsFranchisedOnly) {
	$('#QuickQuoteModel').append('<option value="0">Select Model</option>').empty();
	$('#QuickQuoteModel').append('<option value="0">Loading...</option>');

	$.ajax({
		type: "POST",
		url: hostURL + "masterpagewebservice.asmx/GetModelList",
		data: "{accountId: " + accountId + ", makeId: " + $('#QuickQuoteMake').val() + ", makeName: '" + $('#' + "QuickQuoteMake :selected").text()+"', isCrossPromotionOn: '"+isCrossPromotionOn+"', isModelsFranchisedOnly: "+isModelsFranchisedOnly+"}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			var cars = (typeof response) == 'string' ? eval('(' + response + ')') : response;

			$('#QuickQuoteModel').append('<option value="0">Select Model</option>').empty();
			$('#QuickQuoteModel').append('<option value="0">Select Model</option>');

			$('#QuickQuoteModelModal').append('<option value="0">Select Model</option>').empty();
			$('#QuickQuoteModelModal').append('<option value="0">Select Model</option>');

			var quickQuoteMake_selected = $('#QuickQuoteMake').val();
			$('#QuickQuoteMakeModal').val(quickQuoteMake_selected);

			$('#YearFrom').append('<option value="0">Year</option>').empty();
			$('#YearTo').append('<option value="0">Year</option>').empty();

			$('#YearFrom').append('<option value="0">Year</option>');
			$('#YearTo').append('<option value="0">Year</option>');

			for (var i = 0; i < cars.length; i++)
				$('#QuickQuoteModel').append('<option value="' + cars[i].replace(' ','_') + '">' + cars[i] + '</option>');
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}


function getYears(hostURL, accountId, isModelsFranchisedOnly) {
	$.ajax({
		type: "POST",
		url: hostURL + "masterpagewebservice.asmx/GetYearList",
		data: "{accountId:"+accountId+", modelName: '"+ $('#' + "QuickQuoteModel :selected").text()+"', isModelsFranchisedOnly: '"+isModelsFranchisedOnly+"' }",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			var years = (typeof response) == 'string' ? eval('(' + response + ')') : response;
			$('#YearFrom').append('<option value="0">Year</option>').empty();
			$('#YearTo').append('<option value="0">Year</option>').empty();

			$('#QuickQuoteYearFrom').append('<option value="0">Year</option>').empty();
			$('#QuickQuoteYearTo').append('<option value="0">Year</option>').empty();

			var quickQuoteModel_selected = $('#QuickQuoteModel').val();
			$('#QuickQuoteModelModal').val(quickQuoteModel_selected);

			$('#YearFrom').append('<option value="0">Year</option>');
			$('#YearTo').append('<option value="0">Year</option>');

			$('#QuickQuoteYearFrom').append('<option value="0">Year</option>');
			$('#QuickQuoteYearTo').append('<option value="0">Year</option>');

			for (var i = 0; i < years.length; i++) {
				$('#QuickQuoteYearFrom').append('<option value="' + years[i] + '">' + years[i] + '</option>')
				$('#YearFrom').append('<option value="' + years[i] + '">' + years[i] + '</option>')
			}
			for (var i = years.length - 1; i >= 0; i--) {
				$('#QuickQuoteYearTo').append('<option value="' + years[i] + '">' + years[i] + '</option>')
				$('#YearTo').append('<option value="' + years[i] + '">' + years[i] + '</option>')
			}
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}

function getYearsModel(hostURL, accountId, isModelsFranchisedOnly) {
	var modelName = "";

	modelName = $("#ModelNameHidden").val().toLowerCase();

	if(modelName == 0)
		modelName = $('#' + "QuickQuoteModelModal :selected").text();

	$.ajax({
		type: "POST",
		url: hostURL + "masterpagewebservice.asmx/GetYearList",
		data: "{accountId:"+accountId+", modelName: '"+ modelName +"', isModelsFranchisedOnly: '"+isModelsFranchisedOnly+"' }",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			var years = (typeof response) == 'string' ? eval('(' + response + ')') : response;
			$('#QuickQuoteYearFrom').append('<option value="0">Year</option>').empty();
			$('#QuickQuoteYearTo').append('<option value="0">Year</option>').empty();

			$('#QuickQuoteYearFrom').append('<option value="0">Year</option>');
			$('#QuickQuoteYearTo').append('<option value="0">Year</option>');

			for (var i = 0; i < years.length; i++)
				$('#QuickQuoteYearFrom').append('<option value="' + years[i] + '">' + years[i] + '</option>')

			for (var i = years.length - 1; i >= 0; i--)
				$('#QuickQuoteYearTo').append('<option value="' + years[i] + '">' + years[i] + '</option>')

			if($("#YearFromHidden").val() != null)
				$("#QuickQuoteYearFrom").val($("#YearFromHidden").val());

			if($("#YearToHidden").val() != null)
				$("#QuickQuoteYearTo").val($("#YearToHidden").val());

			$("#ModelNameHidden").val("");
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}

function getModelsModal(hostURL, accountId, isCrossPromotionOn, isModelsFranchisedOnly) {
	$('#QuickQuoteModelModal').append('<option value="0">Select Model</option>').empty();
	$('#QuickQuoteModelModal').append('<option value="0">Loading...</option>');

	$.ajax({
		type: "POST",
		url: hostURL + "masterpagewebservice.asmx/GetModelList",
		data: "{accountId: "+accountId+", makeId: "+$('#QuickQuoteMakeModal').val()+", makeName: '"+ $('#' + "QuickQuoteMakeModal :selected").text() +"', isCrossPromotionOn: '"+isCrossPromotionOn+"', isModelsFranchisedOnly: "+isModelsFranchisedOnly+"}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			var cars = (typeof response) == 'string' ? eval('(' + response + ')') : response;
			$('#QuickQuoteModelModal').append('<option value="0">Select Model</option>').empty();
			$('#QuickQuoteModelModal').append('<option value="0">Select Model</option>');

			$('#QuickQuoteYearFrom').append('<option value="0">Year</option>').empty();
			$('#QuickQuoteYearTo').append('<option value="0">Year</option>').empty();

			$('#QuickQuoteYearFrom').append('<option value="0">Year</option>');
			$('#QuickQuoteYearTo').append('<option value="0">Year</option>');

			for (var i = 0; i < cars.length; i++) {
				$('#QuickQuoteModelModal').append('<option value="' + cars[i].toLowerCase().replace(' ','_') + '">' + cars[i] + '</option>')
			}

			if($("#ModelNameHidden").val() != null) {
				$("#QuickQuoteModelModal").val($("#ModelNameHidden").val().toLowerCase());
			}
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}

function saveGetAQuoteLead(siteId, hostURL, sourcePage, siteDefaultUrl, isToBeExecuted, conversionTrackingCode, linkIndex, isSubmit, isEbizTrackingOn) {
	if(!validateQQForm())
		return;

	var hasToDisplayFreeForm = $('#HasToDisplayFreeFormHidden').val();
	var hasToHideYearHidden = $('#HasToHideYearHidden').val();

	var exportID = $('#ExportIDHidden').val();
	var originalUrlEncoded = $('#OriginalUrlEncodedHidden').val();
	var initialTargetEncoded = $('#InitialTargetEncodedHidden').val();

	var yearTo = 0;
	var yearFrom = 0;
	var yearStartYearEnd = 0;

	if(hasToDisplayFreeForm == 'False') {
		var make = getSelectedText("QuickQuoteMakeModal");
		var model = getSelectedText("QuickQuoteModelModal");

		if(hasToHideYearHidden == 'False') {
			yearFrom = getSelectedText("QuickQuoteYearFrom");
			yearTo = getSelectedText("QuickQuoteYearTo");
		}
	} else {
		var make = $('#QuickQuoteMakeModalInput').attr('value');
		var model = $('#QuickQuoteModelModalInput').attr('value');

		if(hasToHideYearHidden == 'False') {
			yearFrom = $('#QuickQuoteYearFromModalInput').attr('value');
			yearTo = $('#QuickQuoteYearToModalInput').attr('value');
		}
	}

	var bodyStyle = getSelectedText("QuickQuoteBodyStyle");
	var extColor = getSelectedText("QuickQuoteExtColor");
	var milesFrom = getSelectedText("QuickQuoteMilesFrom");
	var milesTo = getSelectedText("QuickQuoteMilesTo");
	var week = getSelectedText("QuickQuoteWeek");
	var transmission = getSelectedText("QuickQuoteTransmission");
	var intColor = getSelectedText("QuickQuoteIntColor");
	var priceFrom = getSelectedText("QuickQuotePriceFrom");
	var priceTo = getSelectedText("QuickQuotePriceTo");

	var firstName = $("#QuickQuoteFirstName").attr('value').replace('\'','\\\'').replace('"','\\"');
	var lastName = $("#QuickQuoteLastName").attr('value').replace('\'','\\\'').replace('"','\\"');
	var dayPhone = $("#QuickQuoteDayPhone").attr('value');
	var zip = $('#QuickQuoteDayZip').attr('value');
	var message = encodeURI($('#' + "QuickQuoteMessage").attr('value').replace('\'','\\\'').replace('"','\\"'));
	var email = $("#QuickQuoteEmail").attr('value');

	var emailPhone = email + ((dayPhone != undefined && dayPhone.length > 0) ? (' or ' + dayPhone + ' ') : ' ');

	if(yearFrom == yearTo)
		yearStartYearEnd = yearFrom;
	else
		yearStartYearEnd = yearFrom + ((yearTo.length > 0) ? (' to ' + yearTo + '') : ' ');

	if(firstName != null && firstName != "")
		$("#spnFirstName").html(firstName + ",");

	$("#spnYearStartYearEnd").html(yearStartYearEnd);

	if(yearFrom == 0 && yearTo == 0) {
		document.getElementById('spnYearStartYearEnd').style.display = 'none';
		$("#spnMake").html("<br />" + make);
	} else {
		$("#spnMake").html(make);
	}

	$("#spnModel").html(model);
	$("#spnEmailPhone").html(emailPhone);

	$.ajax({
		type: "POST",
		url: hostURL + "masterpagewebservice.asmx/SaveGetAQuoteLead",
		data: '{"make": "'+make+'","model": "'+model+'","yearFrom": "'+yearFrom+'","yearTo": "'+yearTo+'","bodyStyle": "'+bodyStyle+'","extColor": "'+extColor+'","milesFrom": "'+milesFrom+'","milesTo": "'+milesTo+'","week": "'+week+'","transmission": "'+transmission+'","intColor": "'+intColor+'","priceFrom": "'+priceFrom+'","priceTo": "'+priceTo+'","firstName": "'+firstName+'","lastName": "'+lastName+'","dayPhone": "'+(dayPhone != undefined ? dayPhone : '')+'", zip: "'+(zip != undefined ? zip : '')+'","message": "'+message+'","email": "'+email+'","siteId": "'+siteId+'","sourcePage": "'+sourcePage+'","exportID": "'+exportID+'", "originalUrlEncoded": "'+originalUrlEncoded+'","initialTargetEncoded": "'+initialTargetEncoded+'"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			PageTracking(linkIndex, isSubmit, false, isEbizTrackingOn, siteDefaultUrl, isToBeExecuted)
			ExecuteConversionTrackingCode("#QuickQuoteModalContentResponse", conversionTrackingCode);
			$("#QuickQuoteModalContentResponse2").hide();
			$("#QuickQuoteModalContentResponse").show();
			$('body').animate({scrollTop:0}, 'slow'); 
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}

function validateQQForm() {
	var returnValue = true;
	var hasToDisplayFreeForm = $('#HasToDisplayFreeFormHidden').val();
	var hasToHideYearHidden = $('#HasToHideYearHidden').val();
	var firstNameRequiredHiden = $('#FirstNameRequiredHiden').val();
	var lastNameRequiredHidden = $('#LastNameRequiredHidden').val();
	var phoneNumberRequiredHiden = $('#PhoneNumberRequiredHiden').val();
	var zipCodeRequiredHiden = $('#ZipCodeRequiredHiden').val();
	var zip = document.getElementById("QuickQuoteDayZip");
	
	if (zip != null && !/\d{5}/.test(zip.value) && (!isNullOrEmpty(zip.value) || zipCodeRequiredHiden == "True")) {
		zip.value = "Please provide a 5 digit numeric zip code";
		zip.style.color = 'red';
		returnValue = false;
	}
	
	if(hasToDisplayFreeForm == 'False')
		obj = document.getElementById('QuickQuoteMakeModal');
	else
		obj = document.getElementById('QuickQuoteMakeModalInput');

	if (obj.value == '0') {
		document.getElementById('QuickQuoteMakeMessage').style.visibility = 'visible';
		returnValue = false;
	}
	else
		document.getElementById('QuickQuoteMakeMessage').style.visibility = 'hidden';

	document.getElementById('spnMake').innerText = obj.value;

	if(hasToDisplayFreeForm == 'False')
		obj = document.getElementById('QuickQuoteModelModal');
	else
		obj = document.getElementById('QuickQuoteModelModalInput');

	if (obj.value == '0' ) {
		document.getElementById('QuickQuoteModelMessage').style.visibility = 'visible';
		returnValue = false;
	}
	else
		document.getElementById('QuickQuoteModelMessage').style.visibility = 'hidden';

	document.getElementById('spnModel').innerText = obj.value;

	if(hasToDisplayFreeForm == 'False' && hasToHideYearHidden == 'False') {
		if (document.getElementById('QuickQuoteYearFrom').value == '0' || document.getElementById('QuickQuoteYearTo').value == '0') {
			document.getElementById('QuickQuoteYearsMessage').style.visibility = 'visible';
			returnValue = false;
		}
		else
			document.getElementById('QuickQuoteYearsMessage').style.visibility = 'hidden';

		document.getElementById('spnYearStartYearEnd').innerText = document.getElementById('QuickQuoteYearFrom').value + ' to ' + document.getElementById('QuickQuoteYearTo').value;
	}

	if(hasToDisplayFreeForm == 'True') {
		obj = document.getElementById('QuickQuoteMakeModalInput');
		if (obj.value.length == 0 || obj.value == QQerrorString) {
			obj.value = QQerrorString;
			obj.style.color = 'red';
			returnValue = false;
		}

		obj = document.getElementById('QuickQuoteModelModalInput');
		if (obj.value.length == 0 || obj.value == QQerrorString) {
			obj.value = QQerrorString;
			obj.style.color = 'red';
			returnValue = false;
		}

		if(hasToHideYearHidden == 'False') {
			obj = document.getElementById('QuickQuoteYearFromModalInput');
			if (obj.value.length == 0 || obj.value == QQYearErrorString) {
				obj.value = QQYearErrorString;
				obj.style.color = 'red';
				returnValue = false;
			}

			obj = document.getElementById('QuickQuoteYearToModalInput');
			if (obj.value.length == 0 || obj.value == QQYearErrorString) {
				obj.value = QQYearErrorString;
				obj.style.color = 'red';
				returnValue = false;
			}
		}
	}

	if(firstNameRequiredHiden.toLowerCase() == 'true') {
		obj = document.getElementById('QuickQuoteFirstName');
		if (obj.value.length == 0 || obj.value == QQerrorString) {
			obj.value = QQerrorString;
			obj.style.color = 'red';
			returnValue = false;
		}
	}

	obj = document.getElementById('QuickQuoteEmail');
	if (obj.value.length == 0 || obj.value == QQerrorString) {
		obj.value = QQerrorString;
		obj.style.color = 'red';
		returnValue = false;
	}
	else
		if (!checkEmailStr(obj.value)) {
			obj.style.color = 'red';
			returnValue = false;
	}

	if(lastNameRequiredHidden.toLowerCase() == 'true') {
		obj = document.getElementById('QuickQuoteLastName');
		if (obj.value.length == 0 || obj.value == QQerrorString) {
			obj.value = QQerrorString;
			obj.style.color = 'red';
			returnValue = false;
		}
	}

	obj = document.getElementById('QuickQuoteDayPhone');
	if (obj) {
		if(phoneNumberRequiredHiden.toLowerCase() == 'true') {
			if (obj.value.length == 0 || obj.value == QQerrorString) {
				obj.value = QQerrorString;
				obj.style.color = 'red';
				returnValue = false;
			}
		}
	}

	return returnValue;
}

/* End QuickQuote */

/* Begin Specials */
function toggleDescriptionDiv (i) {
	var oDiv = document.getElementById("specialItemDescription"+i);
	if (oDiv.className.indexOf("hidden")>-1){
		oDiv.className = oDiv.className.split(" ")[0];
	} else {
		oDiv.className = oDiv.className + " hidden";
	}
}

/*#region specials */
var _specialsDataList = null;
var _specialsData = null;
var _specialsAnimation = false;
var _specialsWebService = true; 
var _fadeTime = 500;

function LoadSpecialsData(hostURL, accountId) {
	_specialsWebService = true; 
	$.ajax({
		type: "POST",
		url: hostURL + "masterpagewebservice.asmx/GetSpecialsList",
		data: "{accountId: "+accountId+"}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			specialsDataList = (typeof response) == 'string' ? eval('(' + response + ')') : response;
			_specialsDataList = [];

			for (var i = 0; i < specialsDataList.length; i++) 
				_specialsDataList[i] = eval('(' + specialsDataList[i] + ')');

			_specialsWebService = false;

			GetData(accountId, '', '');
			PrepareSpecialsContent();
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}

function GetIndex(id) {
	for (var i = 0; i < _specialsDataList.length; i++)
		if (_specialsDataList[i].SpecialId == id)
			return i;
	return 0;
}

function GetData(accountId, direction, id1) {
	if (id1 == '')
		direction = '';
	_specialsData = [];
	if (_specialsDataList == null || _specialsDataList.length == 0)
		return;
	switch (direction) {
		case "next":
			currentIndex = GetIndex(id1);
			if (currentIndex + 3 < _specialsDataList.length) {
				_specialsData = [_specialsDataList[currentIndex + 2], _specialsDataList[currentIndex + 3]];
			} else if (currentIndex + 3 == _specialsDataList.length) {
				_specialsData = [_specialsDataList[currentIndex + 2]];
			} else {
				GetData(accountId, '', '');
			}
			break;
		case "previous":
			currentIndex = GetIndex(id1);
			if (currentIndex > 1) {
				_specialsData = [_specialsDataList[currentIndex - 2], _specialsDataList[currentIndex - 1]];
			} else if (currentIndex == 0) {
				if (_specialsDataList.length % 2 == 1)
					_specialsData = [_specialsDataList[_specialsDataList.length - 1]];
				else
					_specialsData = [_specialsDataList[_specialsDataList.length - 2], _specialsDataList[_specialsDataList.length - 1]];
			} else {
				GetData(accountId, '', '');
			}
			break;
		default:
			if (_specialsDataList.length == 0)
				_specialsData = [];
			else if (_specialsDataList.length == 1)
				_specialsData = [_specialsDataList[0]];
			else 
				_specialsData = [_specialsDataList[0], _specialsDataList[1]];
			break;
	}
}

function getSpecials(hostURL, accountId, direction) {
	if (_specialsDataList == null) 
		LoadSpecialsData(hostURL, accountId);

	if (_specialsDataList == null || _specialsDataList.length < 3) 
		return;

	var hiddenSpecialIdFirst = $("#hiddenSpecialIdFirst").val();
	var hiddenSpecialIdSecond = $("#hiddenSpecialIdSecond").val();

	_specialsAnimation = true;

	$(".homeSpecialItems, .homeSpecialItemsEmpty").fadeTo(_fadeTime, 0,
		function() {
			_specialsAnimation = false; 

			GetData(accountId, direction, hiddenSpecialIdFirst);
			PrepareSpecialsContent();
		}
	);
}

function PrepareSpecialsContent() {
	if (!_specialsAnimation && !_specialsWebService){
		_specialsAnimation = true;
		FillOutSpecialsContent();
		$(this).oneTime(200, function(){ 
			$(".homeSpecialItems, .homeSpecialItemsEmpty").fadeTo(_fadeTime,1, function(){
				// fixing IE Fading issue
				$(".homeSpecial").css('background', $(".homeSpecial").css('background')); 
				$(".itemsFoundDiv").css('background', $(".itemsFoundDiv").css('background'));
			});	
		});
	}
}

function FillOutSpecialsContent() {
	if (_specialsData == "undefined" || _specialsData.length < 1) {
		$(".homeSpecialItems").addClass("hidden");
		$(".homeSpecialItemsEmpty").removeClass("hidden");
		$("#hiddenSpecialIdFirst").val(-1);
		$("#hiddenSpecialIdSecond").val(-1);
	} else {
		$(".homeSpecialItems").removeClass("hidden");
		$(".homeSpecialItemsEmpty").addClass("hidden");
		for(var i = 1; i <= 2; i++){
			var itemSuffix = "First";
			if(i == 2) 
				itemSuffix = "Second";

			if (i > _specialsData.length){
				$(".specialSwapDiv" + itemSuffix).addClass("hidden");
				$(".specialItemsNotFound" + itemSuffix).removeClass("hidden");
				$("#hiddenSpecialId" + itemSuffix).val(-1);
			} else {
				$(".specialSwapDiv" + itemSuffix).removeClass("hidden");
				$(".specialItemsNotFound" + itemSuffix).addClass("hidden");

				var special = _specialsData[i-1];
				$("#hiddenSpecialId" + itemSuffix).val(special.SpecialId);
				$("#a" + itemSuffix).attr("href", special.SpecialDetailLink);
				$("#image" + itemSuffix).attr("src", special.PhotoPath);

				if(special.AllAligible) {
					$("#itemsFoundNumberDiv" + itemSuffix).addClass("itemsFoundNumberDiv fArial fBold fs26");
					$("#itemsFoundNumberDiv" + itemSuffix).html("ALL");
					$("#itemsFoundTextDiv" + itemSuffix).html("Customers Eligible ");
				} else {
					if(special.VehicleNum == '0') {
						$("#itemsFoundNumberDiv" + itemSuffix).removeClass("itemsFoundNumberDiv fArial fBold fs26");
						$("#itemsFoundNumberDiv" + itemSuffix).addClass("itemsFoundTextDiv fArial fs10");
						$("#itemsFoundNumberDiv" + itemSuffix).html("<div style=\"padding-top: 7px; margin-left: 5px; margin-right: 5px;\">Currently no inventory for this special. Need a Quote?</div>");
						$("#itemsFoundTextDiv" + itemSuffix).html("<a href=\""+quickQuoteUrl+"\" rel='nofollow'>Click Here</a>");
					} else {
						$("#itemsFoundNumberDiv" + itemSuffix).removeClass("itemsFoundTextDiv fArial fs10");
						$("#itemsFoundNumberDiv" + itemSuffix).addClass("itemsFoundNumberDiv fArial fBold fs26");
						$("#itemsFoundNumberDiv" + itemSuffix).html(special.VehicleNum);
						$("#itemsFoundTextDiv" + itemSuffix).html("<a href="+special.InventoryLink+">Vehicles Found<br />With This Special</a>");
					}
				}
				$("#titleDiv" + itemSuffix).html("<a href="+special.SpecialDetailLink+">"+special.HeaderText+"</a>");
				$("#line1" + itemSuffix).html(special.Line1Text);
				$("#line2" + itemSuffix).html(special.Line2Text);
			}
		}
	}
}

/*#endregion*/


var _specPopupEventTimer = 0;
var _specPopupMouseMoveTime = 0; 
var _specPopupNeedToShow = false;
var _specPopupActiveItemId = null;
var _specPopupActiveItemNativeColor;
var _specPopupActiveItemTextColor;

var _specPopupMouseX = 0;
var _specPopupMouseY = 0;
var _specPopupVehicleInfoRowId;
var _specPopupVehicleHeader; 
var _specPopupVihiclePrice; 
var _specPopupVehicleImage; 
var _specPopupVehicleDescription; 
var _specPopupVehicleLink;

function VehicleRowCycle() {
	_specPopupEventTimer++;
	if ( (_specPopupEventTimer - _specPopupMouseMoveTime) == 4){
		if (_specPopupNeedToShow){
			ShowVehicleInfoPopup();
			_specPopupNeedToShow = false;
			}
	}
}

function mX(evt) {
	if (evt.pageX && !$.browser.msie)
		return evt.pageX;
	else
		if (evt.clientX)
			return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
	else
		return null;
}

function mY(evt) {
	if (evt.pageY && !$.browser.msie)
		return evt.pageY;
	else
		if (evt.clientY)
			return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	else
		return null;
}

function HideVehicleInfoPopup(){
	popupBody = document.getElementById('vehicleInfoPopup');
	if (popupBody == null) return;
	popupBody.style.display = 'none';
	if (_specPopupActiveItemId != null){
		document.getElementById(_specPopupActiveItemId).style.backgroundColor = _specPopupActiveItemNativeColor;
		document.getElementById(_specPopupActiveItemId).style.color = _specPopupActiveItemTextColor;

		_specPopupActiveItemId = null;
		}
}


function SpecialVehilceRowEventHandler(vehicleInfoRowId,vehicleHeader, vihiclePrice, vehicleImage, vehicleDescription, vehicleLink, e){
	_specPopupVehicleInfoRowId = vehicleInfoRowId;
	_specPopupVehicleHeader = vehicleHeader; 
	_specPopupVihiclePrice = vihiclePrice; 
	_specPopupVehicleImage = vehicleImage; 
	_specPopupVehicleDescription = vehicleDescription; 
	_specPopupVehicleLink = vehicleLink;
	_specPopupMouseMoveTime = _specPopupEventTimer;
	_specPopupNeedToShow = true;

	_specPopupMouseX = mX(e);
	_specPopupMouseY = mY(e);
}


function ShowVehicleInfoPopup() {
	if (_specPopupActiveItemId != null){
		document.getElementById(_specPopupActiveItemId).style.backgroundColor = _specPopupActiveItemNativeColor;
		document.getElementById(_specPopupActiveItemId).style.color = _specPopupActiveItemTextColor;
		}
	_specPopupActiveItemId = _specPopupVehicleInfoRowId;

	_specPopupActiveItemNativeColor = document.getElementById(_specPopupVehicleInfoRowId).style.backgroundColor;
	document.getElementById(_specPopupVehicleInfoRowId).style.backgroundColor = '#' + _attentionColor;
	_specPopupActiveItemTextColor = document.getElementById(_specPopupVehicleInfoRowId).style.color;
	document.getElementById(_specPopupVehicleInfoRowId).style.color = '#' + _pageColor;

	popupBody = document.getElementById('vehicleInfoPopup');

	if (popupBody == null)
		return;
	if (document.getElementById('vehicleInfoPopupLink').href != _specPopupVehicleLink) {
		document.getElementById('vehicleInfoPopupVehicleHeader').innerHTML = _specPopupVehicleHeader;
		document.getElementById('vehicleInfoPopupVehiclePrice').innerHTML = _specPopupVihiclePrice;
		document.getElementById('vehicleInfoPopupImage').src = _specPopupVehicleImage;
		document.getElementById('vehicleInfoPopupDescription').innerHTML = _specPopupVehicleDescription;
		document.getElementById('vehicleInfoPopupLink').href = _specPopupVehicleLink;
	}
	popupBody.style.display = 'block';

	var vehicleInfoTop;
	var vehicleInfoLeft;

	var popupHeight = document.getElementById('vehicleInfoPopup').offsetHeight;
	var vehicleInfoPopupArea = document.getElementById('vehicleInfoPopupArea').offsetHeight;
	var vehicleInfoArrowHeight = document.getElementById('vehicleInfoArrow').offsetHeight
	
	var wraperHeight = 10;
	if($.browser.msie)
		wraperHeight = 16;

	vehicleInfoTop = _specPopupMouseY - vehicleInfoPopupArea - vehicleInfoArrowHeight - wraperHeight;

	vehicleInfoLeft = _specPopupMouseX;

	popupBody.style.top = vehicleInfoTop;
	popupBody.style.left = vehicleInfoLeft;
}

// auto opening/closing sections
function ShowHideSection(index, show, sectionId) {
	var section = document.getElementById(sectionId + index + 'Body');
	if (section) {
		if (show == null)
			show = section.style.display == 'none';
		var hover = document.getElementById(sectionId + index + 'Closehover').style.display == 'inline' 
				|| document.getElementById(sectionId + index + 'Openhover').style.display == 'inline';
		if (show) {
			section.style.display = 'block';
			if (hover) {
				document.getElementById(sectionId + index + 'Closehover').style.display = 'inline';
				document.getElementById(sectionId + index + 'Openhover').style.display = 'none';
				document.getElementById(sectionId + index + 'Close').style.display = 'none';
				document.getElementById(sectionId + index + 'Open').style.display = 'none';
			} else {
				document.getElementById(sectionId + index + 'Closehover').style.display = 'none';
				document.getElementById(sectionId + index + 'Openhover').style.display = 'none';
				document.getElementById(sectionId + index + 'Close').style.display = 'inline';
				document.getElementById(sectionId + index + 'Open').style.display = 'none';
			}
		}
		else
		{
			section.style.display = 'none';
			if (hover) {
				document.getElementById(sectionId + index + 'Closehover').style.display = 'none';
				document.getElementById(sectionId + index + 'Openhover').style.display = 'none';
				document.getElementById(sectionId + index + 'Close').style.display = 'none';
				document.getElementById(sectionId + index + 'Open').style.display = 'inline';
			} else {
				document.getElementById(sectionId + index + 'Closehover').style.display = 'none';
				document.getElementById(sectionId + index + 'Openhover').style.display = 'none';
				document.getElementById(sectionId + index + 'Close').style.display = 'none';
				document.getElementById(sectionId + index + 'Open').style.display = 'inline';
			}
		}
	}
}

function SwitchSection(index, n, sectionId) {
	if (document.getElementById(sectionId + index + 'Body').style.display == 'none') {
		for (i=1; i <= n; i++)
			ShowHideSection(i, i == index, sectionId);
	} else {
		ShowHideSection(index, false, sectionId);
	}
}

function SwitchSectionSimple(index, n, sectionId) {
	if (document.getElementById(sectionId + index + 'Content').style.display == 'none') {
		for (i=1; i <= n; i++)
			ShowHideSectionSimple(i, i == index, sectionId);
	} else {
		ShowHideSectionSimple(index, false, sectionId);
	}
}

// auto opening/closing sections
function ShowHideSectionSimple(index, show, sectionId) {
	var section = document.getElementById(sectionId + index + 'Content');
	if (section) {
		if (show == null)
			show = section.style.display == 'none';
		if (show) {
			section.style.display = 'block';
			document.getElementById(sectionId + index + 'Close').style.display = 'inline';
			document.getElementById(sectionId + index + 'Open').style.display = 'none';
		}
		else
		{
			section.style.display = 'none';
			document.getElementById(sectionId + index + 'Close').style.display = 'none';
			document.getElementById(sectionId + index + 'Open').style.display = 'inline';
		}
	}
}

/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );

/* End Specials */

/* Begin SubmitForms */

//Submit a quote lead logic
function submitAQuoteLead(hostURL, siteId, iid, spItemId, pageType, sourcePage, siteDefaultUrl, isConversionCodeToBeExecuted, conversionTrackingCode) {
	var firstName = $("#TxtAQuoteFirstName").val().replace('\'','\\\'').replace('"','\\"');
	var lastName = $("#TxtAQuoteLastName").val().replace('\'','\\\'').replace('"','\\"');
	var phone = $("#TxtAQuotePhone").val();
	var zip = $("#TxtAQuoteZip").val();
	var email = $("#TxtAQuoteEmail").val();
	var comments = $("#TxtAQuoteComments").val().replace('\'','\\\'').replace('"','\\"');

	var exportID = $('#ExportIDHidden').val();
	var originalUrlEncoded = $('#OriginalUrlEncodedHidden').val();
	var initialTargetEncoded = $('#InitialTargetEncodedHidden').val();

	if(isValidAQuoteLead()) {
		$.ajax({
			type: "POST",
			url: hostURL + "masterpagewebservice.asmx/SubmitAQuoteLead",
			data: "{siteId: '"+ siteId +"', iid: '"+ iid +"', spItemId: '"+ spItemId +"', pageType: '"+ pageType +"', firstName: '"+ firstName +"', lastName: '"+ lastName + "', phone: '"+ ( phone == undefined ? "" : phone )+ "', zip: '"+ ( zip == undefined ? "" : zip )  +"', email: '"+ email +"', comments: '"+ comments +"', sourcePage: '"+ sourcePage +"', exportID: '"+ exportID +"', originalUrlEncoded: '"+ originalUrlEncoded +"', initialTargetEncoded: '"+ initialTargetEncoded +"' }",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			cache: false,
			success: function(response) {
				PageTracking(0, false, false, false, siteDefaultUrl, isConversionCodeToBeExecuted);
				ExecuteConversionTrackingCode("#_GetAQuoteConfirmation", conversionTrackingCode);
				$("#_GetAQuoteLeadForm").hide();
				$("#_GetAQuoteConfirmation").show();
			},
			failure: function(msg) {
				$('#output').text(msg);
			}
		});
	}
}

function isValidAQuoteLead() {
	var firstName = $("#TxtAQuoteFirstName").val();
	var lastName = $("#TxtAQuoteLastName").val();
	var phone = $("#TxtAQuotePhone").val();
	var email = $("#TxtAQuoteEmail").val();
	var zip = $("#TxtAQuoteZip").val();
	var price = '';
	var priceObj = $("#TxtAQuoteEmail");
	if (priceObj)
		price = priceObj.val();

	var isAQuoteFirstNameRequiredHidden = $("#IsAQuoteFirstNameRequiredHidden").val().toLowerCase();
	var isAQuoteLastNameRequiredHidden = $("#IsAQuoteLastNameRequiredHidden").val().toLowerCase();
	var isAQuotePhoneNumberRequiredHidden = (phone == undefined ? "false" : $("#IsAQuotePhoneNumberRequiredHidden").val().toLowerCase());
	var isAQuoteZipCodeRequiredHidden = (zip == undefined ? "false" : $("#IsAQuoteZipCodeRequiredHidden").val().toLowerCase());

	var isValid = true;
	var errorMessage = "You must enter a value in the following fields: \n";

	if (isNullOrEmpty(price)) {
		errorMessage += "- Please enter a price.\n";
		isValid = false;
	}

	if(isAQuoteFirstNameRequiredHidden == "true") {
		if(isNullOrEmpty(firstName) || firstName == "First Name") {
			errorMessage += "- Please enter first name.\n";
			isValid = false;
		}
	}

	if(isAQuoteLastNameRequiredHidden == "true") {
		if(isNullOrEmpty(lastName) || lastName == "Last Name") {
			errorMessage += "- Please enter last name.\n";
			isValid = false;
		}
	}

	if(isAQuotePhoneNumberRequiredHidden == "true") {
		if(isNullOrEmpty(phone) || phone == "Phone") {
			errorMessage += "- Please enter phone number.\n";
			isValid = false;
		}
	}
	
	if(zip && !/\d{5}/.test(zip) && ((!isNullOrEmpty(zip) && zip != "Zip Code") || isAQuoteZipCodeRequiredHidden == "true")) {
		errorMessage += "- Please provide a 5 digit numeric zip code.\n";
		isValid = false;
	}

	if (checkEmailStr(email) && !isNullOrEmpty(email) && isValid) {
		isValid = true;
	} else if(isNullOrEmpty(email)) {
		errorMessage += "- Please enter email address.\n";
		isValid = false;
	} else if(!checkEmailStr(email)) {
		errorMessage += "- Email address has wrong format.\n";
		isValid = false;
	}

	if(!isValid)
		alert(errorMessage);

	return isValid;
}

function isValidateNumber(oEvent) {
	var key = window.event ? oEvent.keyCode : oEvent.which;
	return ((key > 47 && key < 58) || key == 0 || key == 8 || key == 13);
}

//Submit a test drive logic
function submitATestDrive(hostURL, siteId, iid, sourcePage) {
	var firstName = $("#RequestATestDriveFirstName").val().replace('\'','\\\'').replace('"','\\"');
	var lastName = $("#RequestATestDriveLastName").val().replace('\'','\\\'').replace('"','\\"');
	var phone = $("#RequestATestDrivePhone").val();
	var email = $("#RequestATestDriveEmailAddress").val();
	var comments = $("#RequestATestDriveComments").val().replace('\'','\\\'').replace('"','\\"');

	var exportID = $('#ExportIDHidden').val();
	var originalUrlEncoded = $('#OriginalUrlEncodedHidden').val();
	var initialTargetEncoded = $('#InitialTargetEncodedHidden').val();

	if(isValidATestDrive()) {
		$.ajax({
			type: "POST",
			url: hostURL + "masterpagewebservice.asmx/SubmitATestDrive",
			data: "{siteId: '"+ siteId +"', iid: '"+ iid +"', firstName: '"+ firstName +"', lastName: '"+ lastName +"', phone: '"+ phone +"', email: '"+ email +"', comments: '"+ comments + "', sourcePage: '"+ sourcePage +"', exportID: '"+ exportID +"', originalUrlEncoded: '"+ originalUrlEncoded +"', initialTargetEncoded: '"+ initialTargetEncoded +"' }",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			cache: false,
			success: function(response) {
				$("#RequestATestDriveLeadForm").hide();
				$("#RequestATestDriveConfirmation").show();
			},
			failure: function(msg) {
				$('#output').text(msg);
			}
		});
	}
}

function isValidATestDrive() {
	var firstName = $("#RequestATestDriveFirstName").val();
	var lastName = $("#RequestATestDriveLastName").val();
	var phone = $("#RequestATestDrivePhone").val();
	var email = $("#RequestATestDriveEmailAddress").val();
	var comments = $("#RequestATestDriveComments").val();

	var isFirstNameRequiredHidden = $("#IsFirstNameRequiredHidden").val().toLowerCase();
	var isLastNameRequiredHidden = $("#IsLastNameRequiredHidden").val().toLowerCase();
	var isPhoneNumberRequiredHidden = $("#IsPhoneNumberRequiredHidden").val().toLowerCase();

	var isValid = true;
	var errorMessage = "You must enter a value in the following fields: \n";

	if(isFirstNameRequiredHidden == "true") {
		if(isNullOrEmpty(firstName)) {
			errorMessage += "- Please enter first name.\n";
			isValid = false;
		}
	}

	if(isLastNameRequiredHidden == "true") {
		if(isNullOrEmpty(lastName)) {
			errorMessage += "- Please enter last name.\n";
			isValid = false;
		}
	}

	if(isPhoneNumberRequiredHidden == "true") {
		if(isNullOrEmpty(phone)) {
			errorMessage += "- Please enter phone number.\n";
			isValid = false;
		}
	}

	if (checkEmailStr(email) && !isNullOrEmpty(email)) {
		isValid = true;
	} else if(isNullOrEmpty(email)) {
		errorMessage += "- Please enter email address.\n";
		isValid = false;
	} else if(!checkEmailStr(email)) {
		errorMessage += "- Email address has wrong format.\n";
		isValid = false;
	}

	if(!isValid)
		alert(errorMessage);

	return isValid;
}

//Submit contact logic
function submitContact(hostURL, pageId, siteId, siteDefaultUrl, isCampaignConversionsToBeExecuted, linkIndex) {
	var firstName = $('#TxtFirstName').val().replace('\'','\\\'').replace('"','\\"');
	var lastName = $('#TxtLastName').val().replace('\'','\\\'').replace('"','\\"');
	var email = $('#TxtEmail').val();
	var phone = $('#TxtPhone').val();
	var zip = $('#TxtZip').val();
	var emailMessage = $('#TxtEmailMessage').val().replace('\'','\\\'').replace('"','\\"');
	
	if(isValidContactInputs(email, phone, zip)) {
		$.ajax({
			type: "POST",
			url: hostURL + "masterpagewebservice.asmx/SubmitContact",
			data: "{firstName: '"+ firstName +"', lastName: '"+ lastName +"', email: '"+ email +"', phone: '"+ (phone == null ? "" : phone) + "', zip: '" + (zip == null ? "" : zip) +"', emailMessage: '"+ emailMessage +"', pageId: '"+ pageId +"', siteId: '" + siteId + "'}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			cache: false,
			success: function(response) {
				PageTracking(linkIndex, true, false, true, siteDefaultUrl, isCampaignConversionsToBeExecuted);
				$("#InputFieldBox").hide();
				$("#ContactFormThankYou").show();
				$("#ErrorMessageBox").hide();
			},
			failure: function(msg) {
				$('#output').text(msg);
			}
		});
	}
}

function isValidContactInputs(email, phone, zip) {
	var phoneRequired = $("#IsPhoneRequiredHidden").val();
	var zipRequired = $("#IsZipRequiredHidden").val();
	var isZipRequired = zipRequired == null ? "false" : zipRequired;
	var isPhoneRequired = phoneRequired == null ? "false" : phoneRequired;
	var result = true;
	
	$("#PhoneMessageContainer").empty();
	$("#ZipMessageContainer").empty();
	
	if (isNullOrEmpty(phone) && isPhoneRequired == "true") {
		$("#PhoneMessageContainer").append("<br />* Please provide your Phone Number in 999-999-9999 format.");
		result = false;
	}
	
	if (zip && !/\d{5}/.test(zip) && (!isNullOrEmpty(zip.value) || isZipRequired == "true")) {
		$("#ZipMessageContainer").append("<br />* Please provide a 5 digit numeric zip code.");
		result = false;
	}
	
	$("#ErrorMessageBox").show();
	return (isValidEmail(email) && result);
}

function isValidEmail(email) {
	$("#EmailMessageContainer").empty();

	if (checkEmailStr(email) && email.length != 0)
		return true;
	else if(email.length == 0)
		$("#EmailMessageContainer").append("* Please fill out Email Address.");
	else if(!checkEmailStr(email))
		$("#EmailMessageContainer").append("* Email address has wrong format.");

	$("#ErrorMessageBox").show();

	return false;
}

//Submit trade appraisal
function submitTradeAppraisal(hostURL, siteId, contactEmail, sourcePage, conversionTrackingCode, linkIndex) {
	var vinNumber = $('#_txtVin').val();
	var year = $('#_txtYear').val();
	var make = $('#_txtMake').val();
	var comments = $('#_txtComments').val();
	var mileage = $('#_txtMileage').val();
	var model = $('#_txtModel').val();
	var intColor = $('#_txtIntColor').val();
	var extColor = $('#_txtExtColor').val();
	var payOffBalance = $('#_txtPayOffBalance').val();
	var firstName = $('#_txtFirstName').val().replace('\'','\\\'').replace('"','\\"');
	var email = $('#_txtEmail').val();
	var lastName = $('#_txtLastName').val().replace('\'','\\\'').replace('"','\\"');
	var phone = $('#_txtPhone').val();
	var zip = $('#_txtZip').val();
	var message = $('#_txtMessage').val().replace('\'','\\\'').replace('"','\\"');
	var condition = $("#_ddlCondition").val();
	var bestTime = $("#_ddlBestTime").val();
	var purchaseTime = $("#_ddlPurchaseTime").val();

	var exportID = $('#ExportIDHidden').val();
	var originalUrlEncoded = $('#OriginalUrlEncodedHidden').val();
	var initialTargetEncoded = $('#InitialTargetEncodedHidden').val();

	if(isValidForm()) {
		$.ajax({
			type: "POST",
			url: hostURL + "masterpagewebservice.asmx/SubmitTradeAppraisal",
			data: "{vinNumber: '"+ vinNumber +"', year: '"+ year +"', make: '"+ make +"', comments: '"+ comments +"', mileage: '"+ mileage +"', model: '"+ model +"', intColor: '"+ intColor +"', extColor: '"+ extColor +"', payOffBalance: '"+ payOffBalance +"', firstName: '"+ firstName +"', email: '"+ email +"', lastName: '"+ lastName +"', phone: '"+ phone +"', zip: '" + zip + "', message: '"+ message +"', condition: '"+ condition +"', bestTime: '"+ bestTime +"', purchaseTime: '"+ purchaseTime +"', siteId: '"+ siteId +"', contactEmail: '"+ contactEmail +"', sourcePage: '"+ sourcePage +"', exportID: '"+ exportID +"', originalUrlEncoded: '"+ originalUrlEncoded +"', initialTargetEncoded: '"+ initialTargetEncoded +"' }",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			cache: false,
			success: function(response) {
				PageTracking(linkIndex, true, false, true, "", false);
				ExecuteConversionTrackingCode("#ThankYouContainer", conversionTrackingCode);
				$("#TradeAppraisalFormContainer").hide();
				$("#ThankYouContainer").show();
			},
			failure: function(msg) {
				$('#output').text(msg);
			}
		});
	}
}

function isValidForm() {
	var year = $("#_txtYear").val();
	var make = $("#_txtMake").val();
	var mileage = $("#_txtMileage").val();
	var model = $("#_txtModel").val();
	var intColor = $("#_txtIntColor").val();
	var extColor = $("#_txtExtColor").val();
	var payOffBalance = $("#_txtPayOffBalance").val();
	var comment = $("#_txtComments").val();
	var firstName = $("#_txtFirstName").val();
	var email = $("#_txtEmail").val();
	var lastName = $("#_txtLastName").val();
	var phone = $("#_txtPhone").val();
	var zip = $("#_txtZip").val();
	var message = $("#_txtMessage").val();
	
	var phoneRequired = $("#IsPhoneTradeRequiredHidden").val();
	var zipRequired = $("#IsZipTradeRequiredHidden").val();
	var isZipRequired = zipRequired == null ? "false" : zipRequired;
	var isPhoneRequired = phoneRequired == null ? "false" : phoneRequired;

	var isValid = true;

	var errorMessage = "You must enter a value in the following fields: \n";

	if(year.length == 0) {
		errorMessage += "- Vehicle Year.\n";
		isValid = false;
	}

	if(make.length == 0) {
		errorMessage += "- Vehicle Make.\n";
		isValid = false;
	}

	if(!IsValueValid(comment)) {
		errorMessage += "- Please fill out Condition Comments with plain text. No HTML allowed.\n";
		isValid = false;
	}

	if(mileage.length == 0) {
		var vehicleMileage = $("#VehicleValidationMessage").val();
		errorMessage += "- "+vehicleMileage+".\n";
		isValid = false;
	}

	if(model.length == 0) {
		errorMessage += "- Vehicle Model.\n";
		isValid = false;
	}

	if(intColor.length == 0) {
		errorMessage += "- Vehicle Interior Color.\n";
		isValid = false;
	}

	if(extColor.length == 0) {
		errorMessage += "- Vehicle Exterior Color.\n";
		isValid = false;
	}

	if(payOffBalance.length == 0) {
		errorMessage += "- Vehicle Payoff Balance.\n";
		isValid = false;
	}

	if(firstName.length == 0) {
		errorMessage += "- Vehicle Payoff Balance.\n";
		isValid = false;
	}

	if (checkEmailStr(email) && email.length != 0) {
		isValid = true;
	} else if(email.length == 0) {
		errorMessage += "- Email Address.\n";
		isValid = false;
	} else if(!checkEmailStr(email)) {
		errorMessage += "- Email Address.\n";
		isValid = false;
	}

	if(lastName.length == 0) {
		errorMessage += "- Last Name.\n";
		isValid = false;
	}

	if(isNullOrEmpty(phone) && isPhoneRequired == "true") {
		errorMessage += "- Phone Number.\n";
		isValid = false;
	}
	
	if (zip != null && !/\d{5}/.test(zip) && (!isNullOrEmpty(zip) || isZipRequired == "true")) {
		errorMessage += "- Please provide a 5 digit numeric zip code.\n";
		isValid = false;
	}

	if(!IsValueValid(message)) {
		errorMessage += "- Please fill out Message with plain text. No HTML allowed.\n";
		isValid = false;
	}

	if(!isValid)
		alert(errorMessage);

	return isValid;
}

function IsValueValid(value) {
	var filter = /^[^<>\\]*$/;
	return filter.test(value);
}


function IsPhoneNumberValid(value) {
	var filter = /\d{3}-\d{3}-\d{4}/;
	return filter.test(value);
}

//Submit request
function submitRequest(hostURL, contactEmail, contactId, pageType, siteId, sourcePage, siteDefaultUrl, isConversionCodeToBeExecuted, conversionTrackingCode, linkIndex, isSubmit, isEbizTrackingOn) {
	var firstName = $("#_txtFirstName").val().replace('\'','\\\'').replace('"','\\"');
	var lastName = $("#_txtLastName").val().replace('\'','\\\'').replace('"','\\"');
	var dayPhone = $("#_txtDayPhone").val();
	var evePhone = $("#_txtEvePhone").val();
	var email = $("#_txtEmail").val();
	var address = $("#_txtAddress").val().replace('\'','\\\'').replace('"','\\"');
	var city = $("#_txtCity").val().replace('\'','\\\'').replace('"','\\"');
	var state = $("#_txtState").val().replace('\'','\\\'').replace('"','\\"');
	var zip = $("#_txtZip").val();
	var contactMethod = $("#_txtContactMethod").val();
	var year = $("#_txtYear").val();
	var make = $("#_txtMake").val().replace('\'','\\\'').replace('"','\\"');
	var model = $("#_txtModel").val().replace('\'','\\\'').replace('"','\\"');
	var vin = $("#_txtVIN").val();
	var mileage = $("#_txtMileage").val();
	var apptDate = $("#_txtApptDate").val();
	var apptTime = $("#_txtApptTime").val();
	var partsDescription = '';
	if (document.getElementById('_txtPartsDescription'))
		partsDescription = $("#_txtPartsDescription").val().replace('\'','\\\'').replace('"','\\"');
	var comment = $("#_txtComment").val().replace('\'','\\\'').replace('"','\\"');

	var exportID = $('#ExportIDHidden').val();
	var originalUrlEncoded = $('#OriginalUrlEncodedHidden').val();
	var initialTargetEncoded = $('#InitialTargetEncodedHidden').val();
	if(isValidRequestForm()) {
		$.ajax({
			type: "POST",
			url: hostURL + "masterpagewebservice.asmx/SubmitRequest",
			data: "{contactEmail: '"+ contactEmail +"', firstName: '"+ firstName +"', lastName: '"+ lastName +"', address: '"+ address +"', city: '"+ city +"', state: '"+ state +"', dayPhone: '"+ (dayPhone == null ? "" : dayPhone) + "', zip: '"+(zip == null ? "" : zip)+"', evePhone: '"+ evePhone +"', email: '"+ email +"', contactMethod: '"+ contactMethod +"', year: '"+ year +"', make: '"+ make +"', model: '"+ model +"', vin: '"+ vin +"', mileage: '"+ mileage +"', apptDate: '"+ apptDate +"', apptTime: '"+ apptTime +"', partsDescription: '"+ partsDescription +"', comment: '"+ comment +"', contactId: '"+ contactId +"', pageType: '"+ pageType +"', siteId: '"+ siteId +"', sourcePage: '"+ sourcePage +"', exportID: '"+ exportID +"', originalUrlEncoded: '"+ originalUrlEncoded +"', initialTargetEncoded: '"+ initialTargetEncoded +"' }",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			cache: false,
			success: function(response) {			
				PageTracking(linkIndex, isSubmit, false, isEbizTrackingOn, siteDefaultUrl, isConversionCodeToBeExecuted);
				ExecuteConversionTrackingCode("#ThankYouContent", conversionTrackingCode);
				$("#RequestContent").empty();
				$("#RequestContent").hide();
				$("#ThankYouContent").show();
			},
			failure: function(msg) {
				$('#output').text(msg);
			}
		});
	}
}

function isValidRequestForm() {
	var firstName = $("#_txtFirstName").val();
	var lastName = $("#_txtLastName").val();
	var dayPhone = $("#_txtDayPhone").val();
	var evePhone = $("#_txtEvePhone").val();
	var email = $("#_txtEmail").val();
	var address = $("#_txtAddress").val();
	var city = $("#_txtCity").val();
	var state = $("#_txtState").val();
	var zip = $("#_txtZip").val();
	var contactMethod = $("#_txtContactMethod").val();
	var year = $("#_txtYear").val();
	var make = $("#_txtMake").val();
	var model = $("#_txtModel").val();
	var vin = $("#_txtVIN").val();
	var mileage = $("#_txtMileage").val();
	var apptDate = $("#_txtApptDate").val();
	var apptTime = $("#_txtApptTime").val();
	var partsDescription = $("#_txtPartsDescription").val();
	var comment = $("#_txtComment").val();

	var isFirstNameRequired = $("#IsFirstNameHidden").val();
	var isLastNameRequired = $("#IsLastNameHidden").val();
	var IsPhoneNumberRequired= $("#IsPhoneNumberRequiredHidden").val();
	var IsZipRequired= $("#IsZipCodeRequiredHidden").val();
	var isToValidatePhoneFormat = $("#IsToValidatePhoneFormatHidden").val();

	var isValid = true;

	var errorMessage = "You must enter a value in the following fields: \n";

	//$("#ErrorMessageContainer").empty();
	$("#FirstNameError").empty();
	$("#LastNameError").empty();
	$("#DayPhoneError").empty();

	if(firstName.length == 0 && isFirstNameRequired == "true") {
		errorMessage += "- Please fill out First Name. \n";
		$("#FirstNameError").html("*");
		isValid = false;
	}

	if(lastName.length == 0 && isLastNameRequired == "true") {
		errorMessage += "- Please fill out Last Name. \n";
		$("#LastNameError").html("*");
		isValid = false;
	}

	if(dayPhone != null && dayPhone.length == 0 && IsPhoneNumberRequired == "true") {
		errorMessage += "- Please fill out Day Phone. \n";
		$("#DayPhoneError").html("*");
		isValid = false;
	} else if(dayPhone != null && isToValidatePhoneFormat == "true" && !IsPhoneNumberValid(dayPhone)) {
			errorMessage += "- Day Phone has wrong format (999-999-9999). \n";
		isValid = false;
	}
	
	if (zip != null && !/\d{5}/.test(zip) && (!isNullOrEmpty(zip) || IsZipRequired == "true")) {
		errorMessage += "- Please provide a 5 digit numeric zip code.\n";
		isValid = false;
	}

	if(email.length == 0) {
		errorMessage += "- Please fill out Email Address. \n";
		isValid = false;
	} else if(!checkEmailStr(email)) {
		errorMessage += "- Email address has wrong format. \n";
		isValid = false;
	}

	if(year.length == 0) {
		errorMessage += "- Please fill out Vehicle Year. \n";
		isValid = false;
	} else if(!IsYearValid(year)) {
		errorMessage += "- Vehicle Year has wrong format. \n";
		isValid = false;
	}

	if(make.length == 0) {
		errorMessage += "- Please fill out Vehicle Make. \n";
		isValid = false;
	}

	if(model.length == 0) {
		errorMessage += "- Please fill out Vehicle Model. \n";
		isValid = false;
	}

	if(!IsValueValid(comment)) {
		errorMessage += "- Please fill out Comment with plain text. No HTML allowed. \n";
		isValid = false;
	}

	if(!isValid)
		alert(errorMessage);

	return isValid;
}

function IsYearValid(value) {
	var filter = /^[^<>]*$/;
	return filter.test(value);
}

//Tell a friend
function submitTellAFriend(hostURL, vehiclePath, iid, siteId, linkIndex) {
	var name = $("#_txtName").val().replace('\'','\\\'').replace('"','\\"');
	var sendersEmail = $("#_txtSendersEmail").val();
	var recipientEmailAddress = $("#_txtEmail").val();
	var customMessage = $("#_txtCustomMessage").val().replace(/'/g, "_ampersand_");
	var isSendCopy = false;

	if($("#_chkSendCopy").is(':checked'))
		isSendCopy = true;

	//encodeURIComponent(JSON.stringify(string));

	if(isValidTellAFriendForm()) {
		$.ajax({
			type: "POST",
			url: hostURL + "masterpagewebservice.asmx/SubmitTellAFriend",
			data: "{vehiclePath: '"+ vehiclePath +"', iid: '"+ iid +"', name: '"+ name +"', sendersEmail: '"+ sendersEmail +"', recipientEmailAddress: '"+ recipientEmailAddress +"', customMessage: '"+ customMessage +"', isSendCopy: '"+ isSendCopy +"', siteId: "+ siteId +"}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			cache: false,
			success: function(response) {
				if(response == true) {
					PageTracking(linkIndex, true, false, true, '', false);
					$("#ThankYouBox").show();
					$("#RejectedMessageBox").hide();
				} else {
					$("#RejectedMessageBox").show();
					$("#ThankYouBox").hide();
				}
			},
			failure: function(msg) {
				$('#output').text(msg);
				$("#ThankYouBox").hide();
				$("#RejectedMessageBox").show();
			}
		});
	}
}

function clearForm() {
	$("#_txtName").val("");
	$("#_txtSendersEmail").val("");
	$("#_txtEmail").val("");
	$("#_txtCustomMessage").val("");
	$("#_chkSendCopy").removeAttr('checked');
	$("#ThankYouBox").hide();
	$("#RejectedMessageBox").hide();
}

//Tell a friend inventory
function submitTellAFriendInventory(hostURL, currentUrl, dashboardUrlTail, currentTitle, currentSource, linkIndex) {
	var name = $("#_txtName").val().replace('\'','\\\'').replace('"','\\"');
	var sendersEmail = $("#_txtSendersEmail").val();
	var recipientEmailAddress = $("#_txtEmail").val();
	var customMessage = $("#_txtCustomMessage").val().replace(/'/g, "_ampersand_");
	var isSendCopy = false;

	customMessage

	if($("#_chkSendCopy").is(':checked'))
		isSendCopy = true;

	if(isValidTellAFriendForm()) {
		$.ajax({
			type: "POST",
			url: hostURL + "masterpagewebservice.asmx/SubmitTellAFriendInventory",
			data: "{currentUrl: '"+ currentUrl +"', dashboardUrlTail: '"+ dashboardUrlTail +"', currentTitle: '"+ currentTitle.replace("'", '"').replace("'", '"') +"', currentSource: '"+ currentSource +"', name: '"+ name +"', sendersEmail: '"+ sendersEmail +"', recipientEmailAddress: '"+ recipientEmailAddress +"', customMessage: '"+ customMessage +"', isSendCopy: '"+ isSendCopy +"' }",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			cache: false,
			success: function(response) {
				if(response == true) {
					PageTracking(linkIndex, true, false, true, '', false);
					$("#ThankYouBox").show();
					$("#RejectedMessageBox").hide();
				} else {
					$("#RejectedMessageBox").show();
					$("#ThankYouBox").hide();
				}
			},
			failure: function(msg) {
				$('#output').text(msg);
				$("#ThankYouBox").hide();
				$("#RejectedMessageBox").show();
			}
		});
	}
}

function isValidTellAFriendForm() {
	var name = $("#_txtName").val();
	var sendersEmail = $("#_txtSendersEmail").val();
	var recipientEmailAddress = $("#_txtEmail").val();
	var customMessage = $("#_txtCustomMessage").val();

	var errorMessage = "You must enter a value in the following fields: \n";
	var isValid = true;

	$("#NameRequiredFieldValidator").empty();
	$("#RecipientEmailRequiredFieldValidator").empty();
	$("#EmailRequiredFieldValidator").empty();
	$("#PersonalMessageRequiredFieldValidator").empty();

	if(name.length == 0) {
		errorMessage += "- Your Name.\n";
		$("#NameRequiredFieldValidator").html("*");
		isValid = false;
	}
	
	if(sendersEmail.length == 0) {
		errorMessage += "- Your Email Address.\n";
		$("#EmailRequiredFieldValidator").html("*");
		isValid = false;
	} else if(!checkEmailStr(sendersEmail)) {
		errorMessage += "- Your Email Address.\n";
		$("#EmailRequiredFieldValidator").html("*");
		isValid = false;
	}

	if(recipientEmailAddress.length == 0) {
		errorMessage += "- Recipient's Email Address.\n";
		$("#RecipientEmailRequiredFieldValidator").html("*");
		isValid = false;
	} else if(!checkEmailStr(recipientEmailAddress)) {
		errorMessage += "- Recipient's Email Address.\n";
		$("#RecipientEmailRequiredFieldValidator").html("*");
		isValid = false;
	}

	if(customMessage.length == 0) {
		errorMessage += "- Personal Message.\n";
		$("#PersonalMessageRequiredFieldValidator").html("*");
		isValid = false;
	} 
	if (!IsValueValid(name)) {
		errorMessage += "You have entered an invalid character in the field \"Your Name\"\nThese characters are not allowed: \\ > and <\n";
		$("#NameRequiredFieldValidator").html("*");
		isValid = false;
	}
	
	if(!IsValueValid(customMessage)) {
		errorMessage += "You have entered an invalid character in the field \"Personal Message\"\nThese characters are not allowed: \\ > and <\n";
		$("#PersonalMessageRequiredFieldValidator").html("*");
		isValid = false;
	}
	

	if(!isValid)
		alert(errorMessage);

	return isValid;
}

//Credit app
function submitCreditApp() {
	if(IsValidCreditApp()) {
		$("#_chPermission").val('true');
		$("#CreditForm").submit();
	}
}

function showTradeInBox() {
	if($("#_chkShowTradeIn").is(':checked')) {
		$("#ShowTradeInYear").show();
		$("#ShowTradeInMake").show();
		$("#ShowTradeInModel").show();
		$("#ShowTradeInMileage").show();
		$("#_chkShowTradeIn").val('true');
	} else {
		$("#ShowTradeInYear").hide();
		$("#ShowTradeInMake").hide();
		$("#ShowTradeInModel").hide();
		$("#ShowTradeInMileage").hide();
		$("#_chkShowTradeIn").val('false');
	}
}

function showPrevAddress() {
	var isShowPrevAddressHiden = $("#IsShowPrevAddressHiden").val();
	var isShowPrevAddress = $("#_chkShowPrevAddress").is(':checked');

	if(!isNullOrEmpty(isShowPrevAddressHiden) && isShowPrevAddressHiden.toLowerCase() == "true" && isShowPrevAddress) {
		$("#ShowPrevAddress").show();
		$("#ShowPrevCityAndZipCode").show();
	} else {
		$("#ShowPrevAddress").hide();
		$("#ShowPrevCityAndZipCode").hide();
	}
}

function showCoApplicant() {
	var isShowCoApplicantHiden = $("#IsShowCoApplicantHiden").val();
	var isShowCoApplicant = $("#_chkShowCoApplicant").is(':checked');

	if(!isNullOrEmpty(isShowCoApplicantHiden) && isShowCoApplicantHiden.toLowerCase() == "true" && isShowCoApplicant) {
		$("#ShowCoApplicantSocialSecurity").show();
		$("#ShowCoApplicantDateOfBirth").show();
		$("#ShowCoApplicantSpouse").show();
		$("#ShowCoApplicantEmailAddress").show();
		$("#ShowCoApplicantFullName").show();
		$("#ShowCoApplicantHomeAddress").show();
		$("#ShowCoApplicantCityAndZipCode").show();
		$("#ShowCoApplicantRentOrOwn").show();
		$("#ShowCoApplicanRentOrMortgageAmount").show();
		$("#ShowCoApplicanResidencyLength").show();
		$("#ShowCoApplicanHomeTelephone").show();
		$("#ShowCoApplicanMobileTelephone").show();
		$("#PreviousAddressFormText").show();
		$("#PreviousAddressFormTextHeader").show();
		$("#PreviousAddressFormTextBottom").show();
		$("#BankInfoFormText").show();
		$("#BankInfoFormTextHeader").show();
		$("#BankInfoBankName").show();
		$("#BankInfoAccountType").show();
		$("#BankInfoCheckingOrSavingsAccount").show();
		$("#EmploymentInfoFormText").show();
		$("#EmploymentInfoFormTextHeader").show();
		$("#EmploymentInfoEmployer").show();
		$("#EmploymentInfoSelfEmployment").show();
		$("#EmploymentInfoJobTitle").show();
		$("#EmploymentInfoWorkTelephone").show();
		$("#EmploymentInfoEmploymentLength").show();
		$("#EmploymentInfoApproxGrossIncome").show();
		$("#PreviousEmploymentInfoFormText").show();
		$("#PreviousEmploymentInfoFormTextHeader").show();
		$("#PreviousEmploymentInfoBottom").show();
		$("#AdditionalIncomeInfoFormText").show();
		$("#AdditionalIncomeInfoFormTextHeader").show();
		$("#AdditionalIncomeInfoAmount").show();
		$("#AdditionalIncomeInfoSource").show();
	} else {
		$("#ShowCoApplicantSocialSecurity").hide();
		$("#ShowCoApplicantDateOfBirth").hide();
		$("#ShowCoApplicantSpouse").hide();
		$("#ShowCoApplicantEmailAddress").hide();
		$("#ShowCoApplicantFullName").hide();
		$("#ShowCoApplicantHomeAddress").hide();
		$("#ShowCoApplicantCityAndZipCode").hide();
		$("#ShowCoApplicantRentOrOwn").hide();
		$("#ShowCoApplicanRentOrMortgageAmount").hide();
		$("#ShowCoApplicanResidencyLength").hide();
		$("#ShowCoApplicanHomeTelephone").hide();
		$("#ShowCoApplicanMobileTelephone").hide();
		$("#PreviousAddressFormText").hide();
		$("#PreviousAddressFormTextHeader").hide();
		$("#PreviousAddressFormTextBottom").hide();
		$("#ShowCoPrevAddress").hide();
		$("#ShowCoPrevAddressCity").hide();
		$("#BankInfoFormText").hide();
		$("#BankInfoFormTextHeader").hide();
		$("#BankInfoBankName").hide();
		$("#BankInfoAccountType").hide();
		$("#BankInfoCheckingOrSavingsAccount").hide();
		$("#EmploymentInfoFormText").hide();
		$("#EmploymentInfoFormTextHeader").hide();
		$("#EmploymentInfoEmployer").hide();
		$("#EmploymentInfoSelfEmployment").hide();
		$("#EmploymentInfoJobTitle").hide();
		$("#EmploymentInfoWorkTelephone").hide();
		$("#EmploymentInfoEmploymentLength").hide();
		$("#EmploymentInfoApproxGrossIncome").hide();
		$("#PreviousEmploymentInfoFormText").hide();
		$("#PreviousEmploymentInfoFormTextHeader").hide();
		$("#PreviousEmploymentInfoBottom").hide();
		$("#ShowCoPrevEmployment").hide();
		$("#ShowCoPrevEmploymentSelfEmployment").hide();
		$("#ShowCoPrevEmploymentJobTitle").hide();
		$("#ShowCoPrevEmploymentWorkTelephone").hide();
		$("#ShowCoPrevEmploymentLength").hide();
		$("#AdditionalIncomeInfoFormText").hide();
		$("#AdditionalIncomeInfoFormTextHeader").hide();
		$("#AdditionalIncomeInfoAmount").hide();
		$("#AdditionalIncomeInfoSource").hide();

		$("#_chkShowCoPrevEmployment").removeAttr('checked');
		$("#_chkShowCoPrevAddress").removeAttr('checked');
	}
}

function showCoPrevAddress() {
	var isShowCoPrevAddressHiden = $("#IsShowCoApplicantHiden").val();
	var isShowCoPrevAddress = $("#_chkShowCoPrevAddress").is(':checked');

	if(!isNullOrEmpty(isShowCoPrevAddressHiden) && isShowCoPrevAddressHiden.toLowerCase() == "true" && isShowCoPrevAddress) {
		$("#ShowCoPrevAddress").show();
		$("#ShowCoPrevAddressCity").show();
	} else { 
		$("#ShowCoPrevAddress").hide();
		$("#ShowCoPrevAddressCity").hide();
	}
}

function showPrevEmployment(requirePreviousEmploymentInfo) {
	var isShowPrevEmployment = $("#_chkShowPrevEmployment").is(':checked');
	var isShowPrevEmploymentHiden = $("#IsShowPrevEmploymentHiden").val();

	if(!isNullOrEmpty(isShowPrevEmploymentHiden) && isShowPrevEmploymentHiden.toLowerCase() == "true" && isShowPrevEmployment) {
		$("#ShowPrevEmploymentEmployer").show();
		$("#ShowPrevEmploymentSelf").show();
		$("#ShowPrevEmploymentJobTitle").show();
		$("#ShowPrevEmploymentWorkTelephone").show();
		$("#ShowPrevEmploymentLength").show();
	} else {
		$("#ShowPrevEmploymentEmployer").hide();
		$("#ShowPrevEmploymentSelf").hide();
		$("#ShowPrevEmploymentJobTitle").hide();
		$("#ShowPrevEmploymentWorkTelephone").hide();
		$("#ShowPrevEmploymentLength").hide();
	}
}

function showCoPrevEmployment() {
	var isShowCoPrevEmployment = $("#_chkShowCoPrevEmployment").is(':checked');
	var isShowCoPrevEmploymentHiden = $("#IsShowCoPrevEmploymentHiden").val();

	if(!isNullOrEmpty(isShowCoPrevEmploymentHiden) && isShowCoPrevEmploymentHiden.toLowerCase() == "true" && isShowCoPrevEmployment) {
		$("#ShowCoPrevEmployment").show();
		$("#ShowCoPrevEmploymentSelfEmployment").show();
		$("#ShowCoPrevEmploymentJobTitle").show();
		$("#ShowCoPrevEmploymentWorkTelephone").show();
		$("#ShowCoPrevEmploymentLength").show();
	} else {
		$("#ShowCoPrevEmployment").hide();
		$("#ShowCoPrevEmploymentSelfEmployment").hide();
		$("#ShowCoPrevEmploymentJobTitle").hide();
		$("#ShowCoPrevEmploymentWorkTelephone").hide();
		$("#ShowCoPrevEmploymentLength").hide();
	}
}

function IsValidCreditApp() {
	var txtYear = $("#_txtYear").val();
	var txtMake = $("#_txtMake").val();
	var txtModel = $("#_txtModel").val();
	var txtTradeInYear = $("#_txtTradeInYear").val();
	var txtTradeInMake = $("#_txtTradeInMake").val();
	var txtTradeInModel = $("#_txtTradeInModel").val();
	var txtTradeInMealge = $("#_txtTradeInMileage").val();
	var txtSSN1 = $("#_txtSSN1").val();
	var txtSSN2 = $("#_txtSSN2").val();
	var txtSSN3 = $("#_txtSSN3").val();
	var txtDriversLicense = $("#_txtDriversLicense").val();
	var txtDOB = $("#_txtDOB").val();
	var txtEmail = $("#_txtEmail").val();
	var txtFirstName = $("#_txtFirstName").val();
	var txtLastName = $("#_txtLastName").val();
	var txtHomeAddressNumber = $("#_txtHomeAddressNumber").val();
	var txtHomeAddress1 = $("#_txtHomeAddress1").val();
	var txtHomeCity = $("#_txtHomeCity").val();
	var txtHomeZip = $("#_txtHomeZip").val();
	var txtHomePhone1 = $("#_txtHomePhone1").val();
	var txtHomePhone2 = $("#_txtHomePhone2").val();
	var txtHomePhone3 = $("#_txtHomePhone3").val();
	var txtPrevHomeAddressNumber = $("#_txtPrevHomeAddressNumber").val();
	var txtPrevHomeAddress1 = $("#_txtPrevHomeAddress1").val();
	var txtPrevHomeCity = $("#_txtPrevHomeCity").val();
	var txtPrevHomeZip = $("#_txtPrevHomeZip").val();
	var txtBankName = $("#_txtBankName").val();
	var txtEmployer = $("#_txtEmployer").val();
	var txtJobTitle = $("#_txtJobTitle").val();
	var txtWorkPhone1 = $("#_txtWorkPhone1").val();
	var txtWorkPhone2 = $("#_txtWorkPhone2").val();
	var txtWorkPhone3 = $("#_txtWorkPhone3").val();
	var txtPrevEmployer = $("#_txtPrevEmployer").val();
	var txtPrevJobTitle = $("#_txtPrevJobTitle").val();
	var txtPrevWorkPhone1 = $("#_txtPrevWorkPhone1").val();
	var txtPrevWorkPhone2 = $("#_txtPrevWorkPhone2").val();
	var txtPrevWorkPhone3 = $("#_txtPrevWorkPhone3").val();
	var txtReFirstName = $("#_txtReFirstName").val();
	var txtReLastName = $("#_txtReLastName").val();
	var txtReHomePhone1 = $("#_txtReHomePhone1").val();
	var txtReHomePhone2 = $("#_txtReHomePhone2").val();
	var txtReHomePhone3 = $("#_txtReHomePhone3").val();
	var txtReHomeAddressNumber = $("#_txtReHomeAddressNumber").val();
	var txtReHomeAddress1 = $("#_txtReHomeAddress1").val();
	var txtReHomeCity = $("#_txtReHomeCity").val();
	var txtReHomeZip = $("#_txtReHomeZip").val();
	var txtRe2FirstName = $("#_txtRe2FirstName").val();
	var txtRe2LastName = $("#_txtRe2LastName").val();
	var txtRe2HomePhone1 = $("#_txtRe2HomePhone1").val();
	var txtRe2HomePhone2 = $("#_txtRe2HomePhone2").val();
	var txtRe2HomePhone3 = $("#_txtRe2HomePhone3").val();
	var txtRe2HomeAddressNumber = $("#_txtRe2HomeAddressNumber").val();
	var txtRe2HomeCity = $("#_txtRe2HomeCity").val();
	var txtRe2HomeZip = $("#_txtRe2HomeZip").val();
	var txtCoSSN1 = $("#_txtCoSSN1").val();
	var txtCoSSN2 = $("#_txtCoSSN2").val();
	var txtCoSSN3 = $("#_txtCoSSN3").val();
	var txtCoDOB = $("#_txtCoDOB").val();
	var txtCoEmail = $("#_txtCoEmail").val();
	var txtCoFirstName = $("#_txtCoFirstName").val();
	var txtCoLastName = $("#_txtCoLastName").val();
	var txtCoHomeAddressNumber = $("#_txtCoHomeAddressNumber").val();
	var txtCoHomeAddress1 = $("#_txtCoHomeAddress1").val();
	var txtCoHomeCity = $("#_txtCoHomeCity").val();
	var txtCoHomeZip = $("#_txtCoHomeZip").val();
	var txtCoHomePhone1 = $("#_txtCoHomePhone1").val();
	var txtCoHomePhone2 = $("#_txtCoHomePhone2").val();
	var txtCoHomePhone3 = $("#_txtCoHomePhone3").val();
	var txtCoPrevHomeAddressNumber = $("#_txtCoPrevHomeAddressNumber").val();
	var txtCoPrevHomeAddress1 = $("#_txtCoPrevHomeAddress1").val();
	var txtCoPrevHomeCity = $("#_txtCoPrevHomeCity").val();
	var txtCoPrevHomeZip = $("#_txtCoPrevHomeZip").val();
	var txtCoBankName = $("#_txtCoBankName").val();
	var txtCoEmployer = $("#_txtCoEmployer").val();
	var txtCoJobTitle = $("#_txtCoJobTitle").val();
	var txtCoWorkPhone1 = $("#_txtCoWorkPhone1").val();
	var txtCoWorkPhone2 = $("#_txtCoWorkPhone2").val();
	var txtCoWorkPhone3 = $("#_txtCoWorkPhone3").val();
	var txtCoPrevEmployer = $("#_txtCoPrevEmployer").val();
	var txtCoPrevJobTitle = $("#_txtCoPrevJobTitle").val();
	var txtCoPrevWorkPhone1 = $("#_txtCoPrevWorkPhone1").val();
	var txtCoPrevWorkPhone2 = $("#_txtCoPrevWorkPhone2").val();
	var txtCoPrevWorkPhone3 = $("#_txtCoPrevWorkPhone3").val();
	var txtDownPayment = $("#_txtDownPayment").val();
	var txtRentMortgageAmount = $("#_txtRentMortgageAmount").val();
	var txtIncome = $("#_txtIncome").val();
	var txtIncomeAmount = $("#_txtIncomeAmount").val();

	//checked fields
	var isShowPrevAddress = $("#_chkShowPrevAddress").is(':checked');
	var isShowPrevEmployment = $("#_chkShowPrevEmployment").is(':checked');
	var isShowCoApplicant = $("#_chkShowCoApplicant").is(':checked');
	var isShowCoPrevAddress = $("#_chkShowCoPrevAddress").is(':checked');

	//hidden fields
	var isShowPrevEmploymentHiden = $("#IsShowPrevEmploymentHiden").val();
	var isShowCoApplicantHiden = $("#IsShowCoApplicantHiden").val();
	var isRquireEmploymentInfoHidden = $("#IsRquireEmploymentInfoHidden").val();
	var isRequireRelativeSectionHiden = $("#IsRequireRelativeSectionHiden").val();
	var isShowPrevAddressHiden = $("#IsShowPrevAddressHiden").val();
	var isShowCoPrevAddressHiden = $("#IsShowCoApplicantHiden").val();
	var isRequireRelativeSection2Hiden = $("#IsRequireRelativeSection2Hiden").val();
	var isRequireBankInfoHidden = $("#IsRequireBankInfoHidden").val();

	if(isShowCoApplicantHiden != null)
		isShowCoApplicantHiden = isShowCoApplicantHiden.toLowerCase();

	if(isShowPrevAddressHiden != null)
		isShowPrevAddressHiden = isShowPrevAddressHiden.toLowerCase();

	if(isShowCoPrevAddressHiden != null)
		isShowCoPrevAddressHiden = isShowCoPrevAddressHiden.toLowerCase();

	if(isRequireRelativeSectionHiden != null)
		isRequireRelativeSectionHiden = isRequireRelativeSectionHiden.toLowerCase();

	if(isRequireRelativeSection2Hiden != null)
		isRequireRelativeSection2Hiden = isRequireRelativeSection2Hiden.toLowerCase();

	if(isRequireBankInfoHidden != null)
		isRequireBankInfoHidden = isRequireBankInfoHidden.toLowerCase();

	if(isRquireEmploymentInfoHidden != null)
		isRquireEmploymentInfoHidden = isRquireEmploymentInfoHidden.toLowerCase();

	var errorMessage = "You must enter a value in the following fields: \n";
	var isValid = true;

	$("#ErrorMessageContainer").empty();
	$("#ErrorMessageContainer").append("You must enter a value in the following fields:");
	$("#ErrorMessageContainer").append("<ul>");

	// Down Payment
	if(!isNullOrEmpty(txtDownPayment)) {
		if(!parseFloat(txtDownPayment)) {
			errorMessage += "- Your downpayment format.\n";
			$("#ErrorMessageContainer").append("<li>Your downpayment format.</li>");
			isValid = false;
		}
	}

	// Rent Amount
	if(isNullOrEmpty(txtRentMortgageAmount) || !parseFloat(txtRentMortgageAmount)) {
		errorMessage += "- Your Rent or Mortgage Amount.\n";
		$("#ErrorMessageContainer").append("<li>Your Rent or Mortgage Amount.</li>");
		isValid = false;
	}

	var isIncomeHiden = $("#IsIncomeHiden").val();

	// Income
	if(!isNullOrEmpty(isIncomeHiden) && isIncomeHiden.toLowerCase() == "true") {
		if(!isNullOrEmpty(txtIncome)) {
			if(!parseFloat(txtIncome)) {
				errorMessage += "- Your Approx. Monthly Gross Income.\n";
				$("#ErrorMessageContainer").append("<li>Your Approx. Monthly Gross Income.</li>");
				isValid = false;
			}
		}
	}

	var isIncomeAmountHiden = $("#IsIncomeAmountHiden").val();

	// Additional IncomeAmount
	if(!isNullOrEmpty(isIncomeAmountHiden) && isIncomeAmountHiden.toLowerCase() == "true") {
		if(!isNullOrEmpty(txtIncomeAmount)) {
			if(!parseFloat(txtIncomeAmount)) {
				errorMessage += "- Your Additional Amount (annual).\n";
				$("#ErrorMessageContainer").append("<li>Your Additional Amount (annual).</li>");
				isValid = false;
			}
		}
	}

	var homeState = $("#_ddlHomeState").val();

	if(!isNullOrEmpty(homeState) && homeState == "N/A") {
		errorMessage += "- Your Home State.\n";
		$("#ErrorMessageContainer").append("<li>Your Home State.</li>");
		isValid = false;
	}

	var prevHomeState = $("#_ddlPrevHomeState").val();

	if(!isNullOrEmpty(isShowPrevAddressHiden) && isShowPrevAddressHiden == "true" && isShowPrevAddress && !isNullOrEmpty(prevHomeState) && prevHomeState == "N/A") {
		errorMessage += "- Your Previous Address State.\n";
		$("#ErrorMessageContainer").append("<li>Your Previous Address State.</li>");
		isValid = false;
	}

	var coHomeState = $("#_ddlCoHomeState").val();

	if(!isNullOrEmpty(isShowCoApplicantHiden) && isShowCoApplicantHiden == "true" && isShowCoApplicant && coHomeState != null && coHomeState == "N/A") {
		errorMessage += "- Co-Applicant Home State.\n";
		$("#ErrorMessageContainer").append("<li>Co-Applicant Home State.</li>");
		isValid = false;
	}

	var coPrevHomeState = $("#_ddlCoPrevHomeState").val();

	if(!isNullOrEmpty(isShowCoApplicantHiden) && isShowCoApplicantHiden == "true" && isShowCoApplicant && isShowCoPrevAddressHiden == "true" && isShowCoPrevAddress != null && isShowCoPrevAddress && !isNullOrEmpty(coPrevHomeState) && coPrevHomeState == "N/A") {
		errorMessage += "- Co-Applicant Previous Address State.\n";
		$("#ErrorMessageContainer").append("<li>Co-Applicant Previous Address State.</li>");
		isValid = false;
	}

	var reHomeState = $("#_ddlReHomeState").val();

	if (!isNullOrEmpty(isRequireRelativeSectionHiden) && isRequireRelativeSectionHiden == "true" && reHomeState != null && reHomeState == "N/A") {
		errorMessage += "- Relative Address State.\n";
		$("#ErrorMessageContainer").append("<li>Relative Address State.</li>");
		isValid = false;
	}

	var re2HomeState = $("#_ddlRe2HomeState").val();

	if(!isNullOrEmpty(isRequireRelativeSection2Hiden) && re2HomeState != null && re2HomeState == "N/A") {
		errorMessage += "- Friend's Address State.\n";
		$("#ErrorMessageContainer").append("<li>Friend's Address State.</li>");
		isValid = false;
	}

	var itemDataHidden = $("#ItemDataHidden").val();

	if(isNullOrEmpty(itemDataHidden)) {
		if(isNullOrEmpty(txtYear)) {
			errorMessage += "- Year of vehicle of interest.\n";
			$("#ErrorMessageContainer").append("<li>Year of vehicle of interest.</li>");
			isValid = false;
		}

		if(isNullOrEmpty(txtMake)) {
			errorMessage += "- Make of vehicle on interest.\n";
			$("#ErrorMessageContainer").append("<li>Make of vehicle on interest.</li>");
			isValid = false;
		}

		if(isNullOrEmpty(txtModel)) {
			errorMessage += "- Model of vehicle of interest.\n";
			$("#ErrorMessageContainer").append("<li>Model of vehicle of interest.</li>");
			isValid = false;
		}
	}

	if($("#_chkShowTradeIn").is(':checked')) {
		if(isNullOrEmpty(txtTradeInYear)) {
			errorMessage += "- Year of Trade-In vehicle.\n";
			$("#ErrorMessageContainer").append("<li>Year of Trade-In vehicle.</li>");
			isValid = false;
		}

		if(isNullOrEmpty(txtTradeInMake)) {
			errorMessage += "- Make of Trade-In vehicle.\n";
			$("#ErrorMessageContainer").append("<li>Make of Trade-In vehicle.</li>");
			isValid = false;
		}

		if(isNullOrEmpty(txtTradeInModel)) {
			errorMessage += "- Model of Trade-In vehicle.\n";
			$("#ErrorMessageContainer").append("<li>Model of Trade-In vehicle.</li>");
			isValid = false;
		}

		if(isNullOrEmpty(txtTradeInMealge)) {
			errorMessage += "- Mileage/KMs of Trade-In vehicle.\n";
			$("#ErrorMessageContainer").append("<li>Mileage/KMs of Trade-In vehicle.</li>");
			isValid = false;
		}
	}

	var isCountryCode = $("#IsCountryCodeUSAHiden").val();

	if(!isNullOrEmpty(isCountryCode))
		isCountryCode = isCountryCode.toLowerCase();

	if(isNullOrEmpty(txtSSN1)) {
		errorMessage += "- First three digits of your social security number.\n";
		$("#ErrorMessageContainer").append("<li>First three digits of your social security number.</li>");
		isValid = false;
	} else if(!isNullOrEmpty(txtSSN1) && !IsSSNValid(txtSSN1, "SSN1", isCountryCode)) {
		errorMessage += "- First three digits of your social security number.\n";
		$("#ErrorMessageContainer").append("<li>First three digits of your social security number.</li>");
		isValid = false;
	}

	if(isNullOrEmpty(txtSSN2)) {
		errorMessage += "- Second digits of your social security number.\n";
		$("#ErrorMessageContainer").append("<li>Second digits of your social security number.</li>");
		isValid = false;
	} else if(!isNullOrEmpty(txtSSN2) && !IsSSNValid(txtSSN2, "SSN2", isCountryCode)) {
		if(isCountryCode == "true") {
			errorMessage += "- Second two digits of your social security number.";
			$("#ErrorMessageContainer").append("<li>Second two digits of your social security number.</li>");
		} else {
			errorMessage += "- Second three digits of your social security number.";
			$("#ErrorMessageContainer").append("<li>Second three digits of your social security number.</li>");
		}

		isValid = false;
	}

	if(isNullOrEmpty(txtSSN3)) {
		$("#ErrorMessageContainer").append("<li>Last digits of your social security number.</li>");
		errorMessage += "- Last digits of your social security number.\n";
		isValid = false;
	} else if(!isNullOrEmpty(txtSSN3) && !IsSSNValid(txtSSN3, "SSN3", isCountryCode)) {
		if(isCountryCode == "true") {
			errorMessage += "- Last four digits of your social security number.\n";
			$("#ErrorMessageContainer").append("<li>Last four digits of your social security number.</li>");
		} else {
			errorMessage += "- Last three digits of your social security number.";
			$("#ErrorMessageContainer").append("<li>Last three digits of your social security number.</li>");
		}

		isValid = false;
	}

	if(isNullOrEmpty(txtDriversLicense)) {
		errorMessage += "- Your Drivers License.\n";
		$("#ErrorMessageContainer").append("<li>Your Drivers License.</li>");
		isValid = false;
	}

	if(isNullOrEmpty(txtDOB)) {
		errorMessage += "- Your date of birth. Date format expecting to be as mm-dd-yyyy or mm.dd.yyyy or mm/dd/yyyy.\n";
		$("#ErrorMessageContainer").append("<li>Your date of birth.</li>");
		isValid = false;
	} else if(!isNullOrEmpty(txtDOB) && !checkDate(txtDOB)) {
		errorMessage += "- Date format expecting to be as mm-dd-yyyy or mm.dd.yyyy or mm/dd/yyyy.\n";
		$("#ErrorMessageContainer").append("<li>Date format expecting to be as mm-dd-yyyy or mm.dd.yyyy or mm/dd/yyyy.</li>");
		isValid = false;
	}

	if(isNullOrEmpty(txtEmail)) {
		errorMessage += "- Your email address.  Email format expecting to be as username@domain.\n";
		$("#ErrorMessageContainer").append("<li>Your email address.</li>");
		isValid = false;
	} else if(!isNullOrEmpty(txtEmail) && !checkEmailStr(txtEmail)) {
		$("#ErrorMessageContainer").append("<li>Your email address.</li>");
		errorMessage += "- Your email address.\n";
		isValid = false;
	}

	if(isNullOrEmpty(txtFirstName)) {
		$("#ErrorMessageContainer").append("<li>Your first name.</li>");
		errorMessage += "- Your first name.\n";
		isValid = false;
	}

	if(isNullOrEmpty(txtLastName)) {
		$("#ErrorMessageContainer").append("<li>Your last name.</li>");
		errorMessage += "- Your last name.\n";
		isValid = false;
	}

	if(isNullOrEmpty(txtHomeAddressNumber)) {
		$("#ErrorMessageContainer").append("<li>Your home address number.</li>");
		errorMessage += "- Your home address number.\n";
		isValid = false;
	}

	if(isNullOrEmpty(txtHomeAddress1)) {
		$("#ErrorMessageContainer").append("<li>Your home address.</li>");
		errorMessage += "- Your home address.\n";
		isValid = false;
	}

	if(isNullOrEmpty(txtHomeCity)) {
		$("#ErrorMessageContainer").append("<li>Your home city.</li>");
		errorMessage += "- Your home city.\n";
		isValid = false;
	}

	if(isNullOrEmpty(txtHomeZip)) {
		$("#ErrorMessageContainer").append("<li>Your home zip.</li>");
		errorMessage += "- Your home zip.\n";
		isValid = false;
	}

	if(isNullOrEmpty(txtHomePhone1)) {
		$("#ErrorMessageContainer").append("<li>Your home phone number.</li>");
		errorMessage += "- Your home phone number.\n";
		isValid = false;
	}

	if(isNullOrEmpty(txtHomePhone2)) {
		$("#ErrorMessageContainer").append("<li>Your home phone number.</li>");
		errorMessage += "- Your home phone number.\n";
		isValid = false;
	}

	if(isNullOrEmpty(txtHomePhone3)) {
		$("#ErrorMessageContainer").append("<li>Your home phone number.</li>");
		errorMessage += "- Your home phone number.\n";
		isValid = false;
	}

	if(isShowPrevAddressHiden == "true" && isShowPrevAddress) {
		if(isNullOrEmpty(txtPrevHomeAddressNumber)) {
			$("#ErrorMessageContainer").append("<li>Your previous home address number.</li>");
			errorMessage += "- Your previous home address number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtPrevHomeAddress1)) {
			$("#ErrorMessageContainer").append("<li>Your previous home address.</li>");
			errorMessage += "- Your previous home address.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtPrevHomeCity)) {
			$("#ErrorMessageContainer").append("<li>Your previous home city.</li>");
			errorMessage += "- Your previous home city.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtPrevHomeZip)) {
			$("#ErrorMessageContainer").append("<li>Your previous home zip.</li>");
			errorMessage += "- Your previous home zip.\n";
			isValid = false;
		}
	}

	if(!isNullOrEmpty(isRequireBankInfoHidden) && isRequireBankInfoHidden == "true") {
		if(isNullOrEmpty(txtBankName)) {
			$("#ErrorMessageContainer").append("<li>Your banks name.</li>");
			errorMessage += "- Your banks name.\n";
			isValid = false;
		}
	}

	if(!isNullOrEmpty(isRquireEmploymentInfoHidden) && isRquireEmploymentInfoHidden == "true") {
		if(isNullOrEmpty(txtEmployer)) {
			$("#ErrorMessageContainer").append("<li>Your employers name.</li>");
			errorMessage += "- Your employers name.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtJobTitle)) {
			$("#ErrorMessageContainer").append("<li>Your job title.</li>");
			errorMessage += "- Your job title.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtWorkPhone1)) {
			$("#ErrorMessageContainer").append("<li>Your work phone number.</li>");
			errorMessage += "- Your work phone number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtWorkPhone2)) {
			$("#ErrorMessageContainer").append("<li>Your work phone number.</li>");
			errorMessage += "- Your work phone number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtWorkPhone3)) {
			$("#ErrorMessageContainer").append("<li>Your work phone number.</li>");
			errorMessage += "- Your work phone number.\n";
			isValid = false;
		}
	}

	if(!isNullOrEmpty(isShowPrevEmploymentHiden) && isShowPrevEmploymentHiden.toLowerCase() == "true" && isShowPrevEmployment) {
		if(isNullOrEmpty(txtPrevEmployer)) {
			$("#ErrorMessageContainer").append("<li>Your previous employers name.</li>");
			errorMessage += "- Your previous employers name.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtPrevJobTitle)) {
			$("#ErrorMessageContainer").append("<li>Your previous job title.</li>");
			errorMessage += "- Your previous job title.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtPrevWorkPhone1)) {
			$("#ErrorMessageContainer").append("<li>Your previous work phone number.</li>");
			errorMessage += "- Your previous work phone number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtPrevWorkPhone2)) {
			$("#ErrorMessageContainer").append("<li>Your previous work phone number.</li>");
			errorMessage += "- Your previous work phone number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtPrevWorkPhone3)) {
			$("#ErrorMessageContainer").append("<li>Your previous work phone number.</li>");
			errorMessage += "- Your previous work phone number.\n";
			isValid = false;
		}
	}

	//Start Validation RELATIVE PERSONAL INFORMATION
	if (!isNullOrEmpty(isRequireRelativeSectionHiden) && isRequireRelativeSectionHiden == "true") {
		if(isNullOrEmpty(txtReFirstName)) {
			$("#ErrorMessageContainer").append("<li>Relative First Name.</li>");
			errorMessage += "- Relative First Name.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtReLastName)) {
			$("#ErrorMessageContainer").append("<li>Relative Last Name.</li>");
			errorMessage += "- Relative Last Name.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtReHomePhone1)) {
			$("#ErrorMessageContainer").append("<li>Relative Phone Number.</li>");
			errorMessage += "- Relative Phone Number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtReHomePhone2)) {
			$("#ErrorMessageContainer").append("<li>Relative Phone Number.</li>");
			errorMessage += "- Relative Phone Number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtReHomePhone3)) {
			$("#ErrorMessageContainer").append("<li>Relative Phone Number.</li>");
			errorMessage += "- Relative Phone Number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtReHomeAddressNumber)) {
			$("#ErrorMessageContainer").append("<li>Relative home address number.</li>");
			errorMessage += "- Relative home address number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtReHomeAddress1)) {
			$("#ErrorMessageContainer").append("<li>Relative home address.</li>");
			errorMessage += "- Relative home address.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtReHomeCity)) {
			$("#ErrorMessageContainer").append("<li>Relative home city.</li>");
			errorMessage += "- Relative home city.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtReHomeZip)) {
			$("#ErrorMessageContainer").append("<li>Relative home zip.</li>");
			errorMessage += "- Relative home zip.\n";
			isValid = false;
		}
	}
	//End Validation RELATIVE PERSONAL INFORMATION

	//Start Validation FRIEND PERSONAL INFORMATION
	if(!isNullOrEmpty(isRequireRelativeSection2Hiden) && isRequireRelativeSection2Hiden == "true") {
		if(isNullOrEmpty(txtRe2FirstName)) {
			$("#ErrorMessageContainer").append("<li>Friend's First Name.</li>");
			errorMessage += "- Friend's First Name.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtRe2LastName)) {
			$("#ErrorMessageContainer").append("<li>Friend's Last Name.</li>");
			errorMessage += "- Friend's Last Name.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtRe2HomePhone1)) {
			$("#ErrorMessageContainer").append("<li>Friend's Phone Number.</li>");
			errorMessage += "- Friend's Phone Number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtRe2HomePhone2)) {
			$("#ErrorMessageContainer").append("<li>Friend's Phone Number.</li>");
			errorMessage += "- Friend's Phone Number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtRe2HomePhone3)) {
			$("#ErrorMessageContainer").append("<li>Friend's Phone Number.</li>");
			errorMessage += "- Friend's Phone Number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtRe2HomeAddressNumber)) {
			$("#ErrorMessageContainer").append("<li>Friend's home address number.</li>");
			errorMessage += "- Friend's home address number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtRe2HomeCity)) {
			$("#ErrorMessageContainer").append("<li>Friend's home city.</li>");
			errorMessage += "- Friend's home city.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtRe2HomeZip)) {
			$("#ErrorMessageContainer").append("<li>Friend's home zip.</li>");
			errorMessage += "- Friend's home zip.\n";
			isValid = false;
		}
	}
	//End Validation FRIEND PERSONAL INFORMATION

	if(isShowCoApplicantHiden == "true" && isShowCoApplicant) {
		if(isNullOrEmpty(txtCoSSN1)) {
			errorMessage += "- First three digits of co-applicant social security number.\n";
			$("#ErrorMessageContainer").append("<li>First three digits of co-applicant social security number.</li>");
			isValid = false;
		} else if(!isNullOrEmpty(txtCoSSN1) && !IsSSNValid(txtCoSSN1, "SSN1", isCountryCode)) {
			errorMessage += "- First three digits of co-applicant social security number.\n";
			$("#ErrorMessageContainer").append("<li>First three digits of co-applicant social security number.</li>");
			isValid = false;
		}

		if(isNullOrEmpty(txtCoSSN2)) {
			$("#ErrorMessageContainer").append("<li>Second digits of co-applicant social security number.</li>");
			errorMessage += "- Second digits of co-applicant social security number.\n";
			isValid = false;
		} else if(!isNullOrEmpty(txtCoSSN2) && !IsSSNValid(txtCoSSN2, "SSN2", isCountryCode)) {
			if(isCountryCode == "true") {
				errorMessage += "- Second two digits of co-applicant social security number.";
				$("#ErrorMessageContainer").append("<li>Second two digits of co-applicant social security number.</li>");
			} else {
				errorMessage += "- Second three digits of co-applicant social security number.";
				$("#ErrorMessageContainer").append("<li>Second three digits of co-applicant social security number.</li>");
			}

			isValid = false;
		}

		if(isNullOrEmpty(txtCoSSN3)) {
			$("#ErrorMessageContainer").append("<li>Last digits of co-applicant social security number.</li>");
			errorMessage += "- Last digits of co-applicant social security number.\n";
			isValid = false;
		} else if(!isNullOrEmpty(txtCoSSN3) && !IsSSNValid(txtCoSSN3, "SSN3", isCountryCode)) {
			if(isCountryCode == "true") {
				errorMessage += "- Last four digits of co-applicant social security number.";
				$("#ErrorMessageContainer").append("<li>Last four digits of co-applicant social security number.</li>");
			} else {
				errorMessage += "- Second three digits of co-applicant social security number.";
				$("#ErrorMessageContainer").append("<li>Last three digits of co-applicant social security number.</li>");
			}

			isValid = false;
		}

		if(isNullOrEmpty(txtCoDOB)) {
			$("#ErrorMessageContainer").append("<li>Co-applicant date of birth.</li>");
			errorMessage += "- Co-applicant date of birth.\n";
			isValid = false;
		} else if(!isNullOrEmpty(txtCoDOB) && !checkDate(txtCoDOB)) {
			$("#ErrorMessageContainer").append("<li>Co-Applicant date format expecting to be as mm-dd-yyyy or mm.dd.yyyy or mm/dd/yyyy.</li>");
			errorMessage += "- Co-Applicant date format expecting to be as mm-dd-yyyy or mm.dd.yyyy or mm/dd/yyyy.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtCoEmail)) {
			$("#ErrorMessageContainer").append("<li>Co-applicant email address.</li>");
			errorMessage += "- Co-applicant email address.\n";
			isValid = false;
		} else if(!isNullOrEmpty(txtCoEmail) && !checkEmailStr(txtCoEmail)) {
			$("#ErrorMessageContainer").append("<li>Co-applicant email address.</li>");
			errorMessage += "- Co-applicant email address.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtCoFirstName)) {
			errorMessage += "- Co-applicant first name.\n";
			$("#ErrorMessageContainer").append("<li>Co-applicant first name.</li>");
			isValid = false;
		}

		if(isNullOrEmpty(txtCoHomeAddressNumber)) {
			errorMessage += "- Your coapplicant home address number.\n";
			$("#ErrorMessageContainer").append("<li>Your coapplicant home address number.</li>");
			isValid = false;
		}

		if(isNullOrEmpty(txtCoHomeAddress1)) {
			$("#ErrorMessageContainer").append("<li>Your coapplicant home address.</li>");
			errorMessage += "- Your coapplicant home address.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtCoHomeCity)) {
			$("#ErrorMessageContainer").append("<li>Co-applicant previous home city.</li>");
			errorMessage += "- Co-applicant previous home city.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtCoHomeZip)) {
			$("#ErrorMessageContainer").append("<li>Co-applicant previous home zip.</li>");
			errorMessage += "- Co-applicant previous home zip.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtCoHomePhone1)) {
			$("#ErrorMessageContainer").append("<li>Your co-applicant home phone number.</li>");
			errorMessage += "- Your co-applicant home phone number.\n";
			isValid = false;
		}

		var txtCoRentMortgageAmount = $("#_txtCoRentMortgageAmount").val();

		// Co Rent Amount
		if(!isNullOrEmpty(txtCoRentMortgageAmount)) {
			if(!parseFloat(txtCoRentMortgageAmount)) {
				errorMessage += "- Co-Applicant Rent or Mortgage Amount.\n";
				$("#ErrorMessageContainer").append("<li>Co-Applicant Rent or Mortgage Amount.</li>");
				isValid = false;
			}
		}

		var txtCoIncome = $("#_txtCoIncome").val();

		// Co Income
		if(!isNullOrEmpty(txtCoIncome)) {
			if(!parseFloat(txtCoIncome)) {
				errorMessage += "- Co-Applicant Approx. Monthly Gross Income.\n";
				$("#ErrorMessageContainer").append("<li>Co-Applicant Approx. Monthly Gross Income.</li>");
				isValid = false;
			}
		}

		var txtCoIncomeAmount = $("#_txtCoIncomeAmount").val();

		// Co Additional IncomeAmount
		if(!isNullOrEmpty(txtCoIncomeAmount)) {
			if(!parseFloat(txtCoIncomeAmount)) {
				errorMessage += "- Co-Applicant Additional Amount (annual).\n";
				$("#ErrorMessageContainer").append("<li>Co-Applicant Additional Amount (annual).</li>");
				isValid = false;
			}
		}

		if(isNullOrEmpty(txtCoHomePhone2)) {
			errorMessage += "- Your co-applicant home phone number.\n";
			$("#ErrorMessageContainer").append("<li>Your co-applicant home phone number.</li>");
			isValid = false;
		}

		if(isNullOrEmpty(txtCoHomePhone3)) {
			errorMessage += "- Your co-applicant home phone number.\n";
			$("#ErrorMessageContainer").append("<li>Your co-applicant home phone number.</li>");
			isValid = false;
		}

		if(isShowCoPrevAddressHiden == "true" && isShowCoPrevAddress) {
			if(isNullOrEmpty(txtCoPrevHomeAddressNumber)) {
				errorMessage += "- Your coapplicant previous home address number.\n";
				$("#ErrorMessageContainer").append("<li>Your coapplicant previous home address number.</li>");
				isValid = false;
			}

			if(isNullOrEmpty(txtCoPrevHomeAddress1)) {
				errorMessage += "- Your coapplicant previous home address.\n";
				$("#ErrorMessageContainer").append("<li>Your coapplicant previous home address.</li>");
				isValid = false;
			}

			if(isNullOrEmpty(txtCoPrevHomeCity)) {
				$("#ErrorMessageContainer").append("<li>Co-applicant previous home city.</li>");
				errorMessage += "- Co-applicant previous home city.\n";
				isValid = false;
			}

			if(isNullOrEmpty(txtCoPrevHomeZip)) {
				errorMessage += "- Co-applicant previous home zip.\n";
				$("#ErrorMessageContainer").append("<li>Co-applicant previous home zip.</li>");
				isValid = false;
			}
		}

		if(!isNullOrEmpty(isRequireBankInfoHidden) && isRequireBankInfoHidden == "true") {
			if(isNullOrEmpty(txtCoBankName)) {
				$("#ErrorMessageContainer").append("<li>Your co-applicant banks name.</li>");
				errorMessage += "- Your co-applicant banks name.\n";
				isValid = false;
			}
		}

		if(isNullOrEmpty(txtCoEmployer)) {
			$("#ErrorMessageContainer").append("<li>Co-applicant previous employers name.</li>");
			errorMessage += "- Co-applicant previous employers name.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtCoJobTitle)) {
			$("#ErrorMessageContainer").append("<li>Co-applicant previous job title.</li>");
			errorMessage += "- Co-applicant previous job title.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtCoWorkPhone1)) {
			$("#ErrorMessageContainer").append("<li>Co-applicant previous work phone number.</li>");
			errorMessage += "- Co-applicant previous work phone number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtCoWorkPhone2)) {
			$("#ErrorMessageContainer").append("<li>Co-applicant previous work phone number.</li>");
			errorMessage += "- Co-applicant previous work phone number.\n";
			isValid = false;
		}

		if(isNullOrEmpty(txtCoWorkPhone3)) {
			$("#ErrorMessageContainer").append("<li>Co-applicant previous work phone number.</li>");
			errorMessage += "- Co-applicant previous work phone number.\n";
			isValid = false;
		}

		var isShowCoPrevEmployment = $("#_chkShowCoPrevEmployment").is(':checked');
		var isShowCoPrevEmploymentHiden = $("#IsShowCoPrevEmploymentHiden").val();

		if(!isNullOrEmpty(isShowCoPrevEmploymentHiden))
			isShowCoPrevEmploymentHiden = isShowCoPrevEmploymentHiden.toLowerCase();

		if(!isNullOrEmpty(isShowCoPrevEmploymentHiden) && isShowCoPrevEmploymentHiden == "true" && isShowCoPrevEmployment) {
			if(isNullOrEmpty(txtCoPrevEmployer)) {
				$("#ErrorMessageContainer").append("<li>Co-applicant previous employers name.</li>");
				errorMessage += "- Co-applicant previous employers name.\n";
				isValid = false;
			}

			if(isNullOrEmpty(txtCoPrevJobTitle)) {
				$("#ErrorMessageContainer").append("<li>Co-applicant previous job title.</li>");
				errorMessage += "- Co-applicant previous job title.\n";
				isValid = false;
			}

			if(isNullOrEmpty(txtCoPrevWorkPhone1)) {
				$("#ErrorMessageContainer").append("<li>Co-applicant previous work phone number.</li>");
				errorMessage += "- Co-applicant previous work phone number.\n";
				isValid = false;
			}

			if(isNullOrEmpty(txtCoPrevWorkPhone2)) {
				$("#ErrorMessageContainer").append("<li>Co-applicant previous work phone number.</li>");
				errorMessage += "- Co-applicant previous work phone number.\n";
				isValid = false;
			}

			if(isNullOrEmpty(txtCoPrevWorkPhone3)) {
				$("#ErrorMessageContainer").append("<li>Co-applicant previous work phone number.</li>");
				errorMessage += "- Co-applicant previous work phone number.\n";
				isValid = false;
			}
		}
	}

	if(!$("#_chPermission").is(':checked')) {
		errorMessage += "- You must agree with terms and conditions of this application.\n";
		$("#ErrorMessageContainer").append("<li>You must agree with terms and conditions of this application.</li>");
		isValid = false;
	}

	if(!isValid){
		$("#ErrorMessageContainer").append("</ul>");
		$("#ErrorMessageContainer").show();
		alert(errorMessage);
	}

	return isValid;
}

function isNullOrEmpty(value) {
	if(value == null || value == "")
		return true;

	return false;
}

function IsSSNValid(value, type, isCountryCode) {
	var filter;

	if(type == "SSN1" && isCountryCode == "true")
		filter = /\d{3}/;
	else if(type == "SSN2" && isCountryCode == "true")
		filter = /\d{2}/;
	else if(type == "SSN3" && isCountryCode == "true")
		filter = /\d{4}/;
	else if(type == "SSN1" && isCountryCode == "false")
		filter = /\d{3}/;
	else if(type == "SSN2" && isCountryCode == "false")
		filter = /\d{3}/;
	else if(type == "SSN3" && isCountryCode == "false")
		filter = /\d{3}/;

	return filter.test(value);
}

/* End SubmitForms */

/* Begin EventsTicker */

jQuery.extend(jQuery.easing,
{
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	}
});

jQuery.fn.liScroll = function(settings) {

	return this.each(function(){
		var $strip = jQuery(this);
		$strip.addClass("newsticker")
		var mouseOver = 0;
		var stripWidth = 0;
		var itemWidth = 0;
		var $mask = $strip.wrap("<div class='mask'></div>");
		var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");
		$tickercontainer.width($strip.parent().parent().width());

		$("ul#ticker01").css('display','block');
		$('ul.newsticker a').css('font-size',$('.newsEventContainer').css('font-size'));
		$('ul.newsticker a').css('text-decoration',$('.newsEventContainer').css('text-decoration'));
		$('ul.newsticker a').css('color',$('.newsEventContainer').css('color'));

		if ($strip.find("li").length === 0)
			return;

		$strip.append('<li>' + $strip.find("li")[0].innerHTML + '</li>');
		itemWidth = $strip.parent().parent().width();

		$strip.find("li").each(function(i) {
			jQuery(this, i).css();
			jQuery(this, i).width(itemWidth);
			stripWidth += jQuery(this, i).width();
			});

		var itemNumber = $strip.find("li").length;
		$strip.width(stripWidth);

		var nextAnimatePoint = 0;
		var mouseTriger = 0;

		function scrollItem(){
			if (mouseTriger === 0){
				if ($strip.position().left <= - itemWidth * (itemNumber - 1) + 1 ){
						$strip.css('left', '0px');
						nextAnimatePoint = 0;
						}
				if ($strip.position().left < nextAnimatePoint + 2);
					nextAnimatePoint -= itemWidth;
			} else {
				mouseTriger = 0;
			}

			$strip.animate({left: nextAnimatePoint},
				settings.scrolltime, "easeInOutCubic", 
				function(){});
		}

		function animateScroler(){
			if (mouseOver === 0){
				scrollItem();
				$(this).oneTime(settings.pausetime + settings.scrolltime, function(){ animateScroler(); });
			} else {
				$(this).oneTime(100, function(){ animateScroler(); });
			}
		}

		animateScroler();

		$strip.hover(
			function(){
				mouseOver = 1;
				$(this).oneTime(100, function(){
								if (mouseOver === 1){
									jQuery(this).stop(true); 
									mouseTriger = 1;
									}
								}
							);},
			function(){ mouseOver = 0;});
			});
};

/* End EventsTicker */


/* Begin contactus */

function ValidateContactUs(isFirstNameRequired, isLastNameRequired, isPhoneRequired, isZipRequired) {
	var errorList = '';
	var ctrFirstName = document.getElementById("txtFirstName");

	if (isFirstNameRequired && trim(ctrFirstName.value).length == 0) {
		errorList += '- Please provide your First Name.\n';
	}

	var ctrLastName = document.getElementById("txtLastName");
	if (isLastNameRequired && trim(ctrLastName.value).length == 0) {
		errorList += '- Please provide your Last Name.\n';
	}

	var ctrPhone = document.getElementById("txtPhone");
	if (ctrPhone && isPhoneRequired && trim(ctrPhone.value).length == 0) {
		errorList += '- Please provide your Phone Number in 999-999-9999 format.  \n';
	}
	
	var ctrZip = document.getElementById("txtZip");
	if (ctrZip != null && !/\d{5}/.test(ctrZip.value) && (!isNullOrEmpty(ctrZip.value) || isZipRequired)) {
		errorList += '- Please provide a 5 digit numeric zip code.\n';
	}

	var ctrEmail = document.getElementById("txtEmail");
	if (trim(ctrEmail.value).length == 0) {
		errorList += '- Please provide your Email Address, so we may respond to your inquiry.\n';
	} else {
		if (!checkEmail(ctrEmail)) {
			errorList += '- Please properly fill out your Email Address, so we may respond to your inquiry.\n';
		}
	}

	if (errorList != '') {
		alert('You must enter a value in the following fileds: \n' + errorList);
	} else {
		frmLeads.submit();
	}
}

function clearContactUsForm() {
	$("#txtFirstName").attr("value","");
	$("#txtLastName").attr("value","");
	$("#txtEmail").attr("value","");
	$("#txtPhone").attr("value","");
	$("#txtMessage").attr("value","");
}

/* End contactus */

/* Begin coupons */
/* x_core.js compiled from X 4.0 with XC 0.27b. Distributed by GNU LGPL. For copyrights, license, documentation and more visit Cross-Browser.com */
var xOp7Up,xOp6Dn,xIE4Up,xIE4,xIE5,xNN4,xUA=navigator.userAgent.toLowerCase();if(window.opera){var i=xUA.indexOf('opera');if(i!=-1){var v=parseInt(xUA.charAt(i+6));xOp7Up=v>=7;xOp6Dn=v<7;}}else if(navigator.vendor!='KDE' && document.all && xUA.indexOf('msie')!=-1){xIE4Up=parseFloat(navigator.appVersion)>=4;xIE4=xUA.indexOf('msie 4')!=-1;xIE5=xUA.indexOf('msie 5')!=-1;}else if(document.layers){xNN4=true;}xMac=xUA.indexOf('mac')!=-1;function xBackground(e,c,i){if(!(e=xGetElementById(e))) return '';var bg='';if(e.style) {if(xStr(c)) {if(!xOp6Dn) e.style.backgroundColor=c;else e.style.background=c;}if(xStr(i)) e.style.backgroundImage=(i!='')? 'url('+i+')' : null;if(!xOp6Dn) bg=e.style.backgroundColor;else bg=e.style.background;}return bg;}function xClientHeight(){var h=0;if(xOp6Dn) h=window.innerHeight;else if(document.compatMode == 'CSS1Compat' && !window.opera && document.documentElement && document.documentElement.clientHeight)h=document.documentElement.clientHeight;else if(document.body && document.body.clientHeight)h=document.body.clientHeight;else if(xDef(window.innerWidth,window.innerHeight,document.width)) {h=window.innerHeight;if(document.width>window.innerWidth) h-=16;}return h;}function xClientWidth(){var w=0;if(xOp6Dn) w=window.innerWidth;else if(document.compatMode == 'CSS1Compat' && !window.opera && document.documentElement && document.documentElement.clientWidth)w=document.documentElement.clientWidth;else if(document.body && document.body.clientWidth)w=document.body.clientWidth;else if(xDef(window.innerWidth,window.innerHeight,document.height)) {w=window.innerWidth;if(document.height>window.innerHeight) w-=16;}return w;}function xClip(e,t,r,b,l){if(!(e=xGetElementById(e))) return;if(e.style) {if (xNum(l)) e.style.clip='rect('+t+'px '+r+'px '+b+'px '+l+'px)';else e.style.clip='rect(0 '+parseInt(e.style.width)+'px '+parseInt(e.style.height)+'px 0)';}}function xColor(e,s){if(!(e=xGetElementById(e))) return '';var c='';if(e.style && xDef(e.style.color)) {if(xStr(s)) e.style.color=s;c=e.style.color;}return c;}function xDef(){for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])=='undefined') return false;}return true;}function xDisplay(e,s){if(!(e=xGetElementById(e))) return null;if(e.style && xDef(e.style.display)) {if (xStr(s)) e.style.display = s;return e.style.display;}return null;}function xGetComputedStyle(oEle, sProp, bInt){var s, p = 'undefined';var dv = document.defaultView;if(dv && dv.getComputedStyle){s = dv.getComputedStyle(oEle,'');if (s) p = s.getPropertyValue(sProp);}else if(oEle.currentStyle) {var a = sProp.split('-');sProp = a[0];for (var i=1; i<a.length; ++i) {c = a[i].charAt(0);sProp += a[i].replace(c, c.toUpperCase());}   p = oEle.currentStyle[sProp];}else return null;return bInt ? (parseInt(p) || 0) : p;}function xGetElementById(e){if(typeof(e)!='string') return e;if(document.getElementById) e=document.getElementById(e);else if(document.all) e=document.all[e];else e=null;return e;}function xHasPoint(e,x,y,t,r,b,l){if (!xNum(t)){t=r=b=l=0;}else if (!xNum(r)){r=b=l=t;}else if (!xNum(b)){l=r; b=t;}var eX = xPageX(e), eY = xPageY(e);return (x >= eX + l && x <= eX + xWidth(e) - r &&y >= eY + t && y <= eY + xHeight(e) - b );}function xHeight(e,h){if(!(e=xGetElementById(e))) return 0;if (xNum(h)) {if (h<0) h = 0;else h=Math.round(h);}else h=-1;var css=xDef(e.style);if (e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {h = xClientHeight();}else if(css && xDef(e.offsetHeight) && xStr(e.style.height)) {if(h>=0) {var pt=0,pb=0,bt=0,bb=0;if (document.compatMode=='CSS1Compat') {var gcs = xGetComputedStyle;pt=gcs(e,'padding-top',1);if (pt !== null) {pb=gcs(e,'padding-bottom',1);bt=gcs(e,'border-top-width',1);bb=gcs(e,'border-bottom-width',1);}else if(xDef(e.offsetHeight,e.style.height)){e.style.height=h+'px';pt=e.offsetHeight-h;}}h-=(pt+pb+bt+bb);if(isNaN(h)||h<0) return;else e.style.height=h+'px';}h=e.offsetHeight;}else if(css && xDef(e.style.pixelHeight)) {if(h>=0) e.style.pixelHeight=h;h=e.style.pixelHeight;}return h;}function xHide(e){return xVisibility(e,0);}function xLeft(e, iX){if(!(e=xGetElementById(e))) return 0;var css=xDef(e.style);if (css && xStr(e.style.left)) {if(xNum(iX)) e.style.left=iX+'px';else {iX=parseInt(e.style.left);if(isNaN(iX)) iX=0;}}else if(css && xDef(e.style.pixelLeft)) {if(xNum(iX)) e.style.pixelLeft=iX;else iX=e.style.pixelLeft;}return iX;}function xMoveTo(e,x,y){xLeft(e,x);xTop(e,y);}function xNum(){for(var i=0; i<arguments.length; ++i){if(isNaN(arguments[i]) || typeof(arguments[i])!='number') return false;}return true;}function xOffsetLeft(e){if (!(e=xGetElementById(e))) return 0;if (xDef(e.offsetLeft)) return e.offsetLeft;else return 0;}function xOffsetTop(e){if (!(e=xGetElementById(e))) return 0;if (xDef(e.offsetTop)) return e.offsetTop;else return 0;}function xPageX(e){if (!(e=xGetElementById(e))) return 0;var x = 0;while (e) {if (xDef(e.offsetLeft)) x += e.offsetLeft;e = xDef(e.offsetParent) ? e.offsetParent : null;}return x;}function xPageY(e){if (!(e=xGetElementById(e))) return 0;var y = 0;while (e) {if (xDef(e.offsetTop)) y += e.offsetTop;e = xDef(e.offsetParent) ? e.offsetParent : null;}return y;}function xParent(e, bNode){if (!(e=xGetElementById(e))) return null;var p=null;if (!bNode && xDef(e.offsetParent)) p=e.offsetParent;else if (xDef(e.parentNode)) p=e.parentNode;else if (xDef(e.parentElement)) p=e.parentElement;return p;}function xResizeTo(e,w,h){xWidth(e,w);xHeight(e,h);}function xScrollLeft(e, bWin){var offset=0;if (!xDef(e) || bWin || e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {var w = window;if (bWin && e) w = e;if(w.document.documentElement && w.document.documentElement.scrollLeft) offset=w.document.documentElement.scrollLeft;else if(w.document.body && xDef(w.document.body.scrollLeft)) offset=w.document.body.scrollLeft;}else {e = xGetElementById(e);if (e && xNum(e.scrollLeft)) offset = e.scrollLeft;}return offset;}function xScrollTop(e, bWin){var offset=0;if (!xDef(e) || bWin || e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {var w = window;if (bWin && e) w = e;if(w.document.documentElement && w.document.documentElement.scrollTop) offset=w.document.documentElement.scrollTop;else if(w.document.body && xDef(w.document.body.scrollTop)) offset=w.document.body.scrollTop;}else {e = xGetElementById(e);if (e && xNum(e.scrollTop)) offset = e.scrollTop;}return offset;}function xShow(e) {return xVisibility(e,1);}function xStr(s){for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])!='string') return false;}return true;}function xTop(e, iY){if(!(e=xGetElementById(e))) return 0;var css=xDef(e.style);if(css && xStr(e.style.top)) {if(xNum(iY)) e.style.top=iY+'px';else {iY=parseInt(e.style.top);if(isNaN(iY)) iY=0;}}else if(css && xDef(e.style.pixelTop)) {if(xNum(iY)) e.style.pixelTop=iY;else iY=e.style.pixelTop;}return iY;}function xVisibility(e, bShow){if(!(e=xGetElementById(e))) return null;if(e.style && xDef(e.style.visibility)) {if (xDef(bShow)) e.style.visibility = bShow ? 'visible' : 'hidden';return e.style.visibility;}return null;}function xWidth(e,w){if(!(e=xGetElementById(e))) return 0;if (xNum(w)) {if (w<0) w = 0;else w=Math.round(w);}else w=-1;var css=xDef(e.style);if (e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {w = xClientWidth();}else if(css && xDef(e.offsetWidth) && xStr(e.style.width)) {if(w>=0) {var pl=0,pr=0,bl=0,br=0;if (document.compatMode=='CSS1Compat') {var gcs = xGetComputedStyle;pl=gcs(e,'padding-left',1);if (pl !== null) {pr=gcs(e,'padding-right',1);bl=gcs(e,'border-left-width',1);br=gcs(e,'border-right-width',1);}else if(xDef(e.offsetWidth,e.style.width)){e.style.width=w+'px';pl=e.offsetWidth-w;}}w-=(pl+pr+bl+br);if(isNaN(w)||w<0) return;else e.style.width=w+'px';}w=e.offsetWidth;}else if(css && xDef(e.style.pixelWidth)) {if(w>=0) e.style.pixelWidth=w;w=e.style.pixelWidth;}return w;}function xZIndex(e,uZ){if(!(e=xGetElementById(e))) return 0;if(e.style && xDef(e.style.zIndex)) {if(xNum(uZ)) e.style.zIndex=uZ;uZ=parseInt(e.style.zIndex);}return uZ;}


/* x_slide.js compiled from X 4.0 with XC 0.27b. Distributed by GNU LGPL. For copyrights, license, documentation and more visit Cross-Browser.com */
function xSlideTo(e, x, y, uTime){if (!(e=xGetElementById(e))) return;if (!e.timeout) e.timeout = 25;e.xTarget = x; e.yTarget = y; e.slideTime = uTime; e.stop = false;e.yA = e.yTarget - xTop(e); e.xA = e.xTarget - xLeft(e); if (e.slideLinear) e.B = 1/e.slideTime;else e.B = Math.PI / (2 * e.slideTime); e.yD = xTop(e); e.xD = xLeft(e); var d = new Date(); e.C = d.getTime();if (!e.moving) _xSlideTo(e);}function _xSlideTo(e){if (!(e=xGetElementById(e))) return;var now, s, t, newY, newX;now = new Date();t = now.getTime() - e.C;if (e.stop) { e.moving = false; }else if (t < e.slideTime) {setTimeout("_xSlideTo('"+e.id+"')", e.timeout);if (e.slideLinear) s = e.B * t;else s = Math.sin(e.B * t);newX = Math.round(e.xA * s + e.xD);newY = Math.round(e.yA * s + e.yD);xMoveTo(e, newX, newY);e.moving = true;}  else {xMoveTo(e, e.xTarget, e.yTarget);e.moving = false;}  }

// xPopup, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xPopup(sTmrType, uTimeout, sPos1, sPos2, sPos3, sStyle, sId, sUrl) {
	if (document.getElementById && document.createElement && document.body && document.body.appendChild) {
		// create popup element
		//var e = document.createElement('DIV');
		var e = document.createElement('IFRAME');

		this.ele = e;
		e.id = sId;
		e.style.position = 'absolute';
		e.className = sStyle;
		e.frameBorder = '0';

		//e.innerHTML = sHtml;
		e.src = sUrl;
		document.body.appendChild(e);
		xShow(e);

		this.tmr = xTimer.set(sTmrType, this, sTmrType, uTimeout);
		// init
		this.open = false;
		this.margin = 10;
		this.pos1 = sPos1;
		this.pos2 = sPos2;
		this.pos3 = sPos3;
		this.slideTime = 500; // slide time in ms
		this.interval();
	} 
} // end xPopup
// methods

xPopup.prototype.show = function() {
	this.interval();
};

xPopup.prototype.hide = function() {
	this.timeout();
};

// timer event listeners
xPopup.prototype.timeout = function() { // hide popup
	if (this.open) {
		var e = this.ele;
		var pos = xCardinalPosition(e, this.pos3, this.margin, true);
		xSlideTo(e, pos.x, pos.y, this.slideTime);
		setTimeout("xHide('" + e.id + "')", this.slideTime);
		this.open = false;
	}
};

xPopup.prototype.interval = function() { // size, position and show popup
	if (!this.open) {
		var e = this.ele;
		var pos = xCardinalPosition(e, this.pos1, this.margin, true);
		xMoveTo(e, pos.x, pos.y);
		xShow(e);
		pos = xCardinalPosition(e, this.pos2, this.margin, false);
		xSlideTo(e, pos.x, pos.y, this.slideTime);
		this.open = true;
	}
};

// xTimer, Copyright 2003-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xTimerMgr() {
	this.timers = new Array();
}

// xTimerMgr Methods
xTimerMgr.prototype.set = function(type, obj, sMethod, uTime, data) { // type: 'interval' or 'timeout'
	return (this.timers[this.timers.length] = new xTimerObj(type, obj, sMethod, uTime, data));
};

xTimerMgr.prototype.run = function() {
	var i, t, d = new Date(), now = d.getTime();

	for (i = 0; i < this.timers.length; ++i) {
		t = this.timers[i];
		if (t && t.running) {
			t.elapsed = now - t.time0;

			if (t.elapsed >= t.preset) { // timer event on t
				t.obj[t.mthd](t); // pass listener this xTimerObj

				if (t.type.charAt(0) == 'i') {
					t.time0 = now;
				} else {
					t.stop();
				}
			}
		}
	}
};

// Object Prototype used only by xTimerMgr
function xTimerObj(type, obj, mthd, preset, data) {
	// Public Properties
	this.data = data;
	// Read-only Properties
	this.type = type; // 'interval' or 'timeout'
	this.obj = obj;
	this.mthd = mthd; // string
	this.preset = preset;
	this.reset();
} // end xTimerObj constructor

// xTimerObj Methods
xTimerObj.prototype.stop = function() {
	this.running = false;
};

xTimerObj.prototype.start = function() {
	this.running = true;
}; // continue after a stop

xTimerObj.prototype.reset = function() {
	var d = new Date();
	this.time0 = d.getTime();
	this.elapsed = 0;
	this.running = true;
};

var xTimer = new xTimerMgr(); // applications assume global name is 'xTimer'
setInterval('xTimer.run()', 250);

/* x_misc.js compiled from X 4.0 with XC 0.27b. Distributed by GNU LGPL. For copyrights, license, documentation and more visit Cross-Browser.com */
function xCapitalize(str){var i, c, wd, s='', cap = true;for (i = 0; i < str.length; ++i) {c = str.charAt(i);wd = isWordDelim(c);if (wd) {cap = true;}  if (cap && !wd) {c = c.toUpperCase();cap = false;}s += c;}return s;function isWordDelim(c){return c == ' ' || c == '\n' || c == '\t';}}function xCardinalPosition(e, cp, margin, outside){if(!(e=xGetElementById(e))) return;if (typeof(cp)!='string'){window.status='xCardinalPosition error: cp=' + cp + ', id=' + e.id; return;}var x=xLeft(e), y=xTop(e), w=xWidth(e), h=xHeight(e);var pw,ph,p = xParent(e);if (p == document || p.nodeName.toLowerCase() == 'html') {pw = xClientWidth(); ph = xClientHeight();}else {pw=xWidth(p); ph=xHeight(p);}var sx=xScrollLeft(p), sy=xScrollTop(p);var right=sx + pw, bottom=sy + ph;var cenLeft=sx + Math.floor((pw-w)/2), cenTop=sy + (typeof(ConstPopupMarginTop)=="undefined")?Math.floor((ph-h)/2):ConstPopupMarginTop;if (!margin) margin=0;else{if (outside) margin=-margin;sx +=margin; sy +=margin; right -=margin; bottom -=margin;}switch (cp.toLowerCase()){case 'n': x=cenLeft; if (outside) y=sy - h; else y=sy; break;case 'ne': if (outside){x=right; y=sy - h;}else{x=right - w; y=sy;}break;case 'e': y=cenTop; if (outside) x=right; else x=right - w; break;case 'se': if (outside){x=right; y=bottom;}else{x=right - w; y=bottom - h}break;case 's': x=cenLeft; if (outside) y=sy - h; else y=bottom - h; break;case 'sw': if (outside){x=sx - w; y=bottom;}else{x=sx; y=bottom - h;}break;case 'w': y=cenTop; if (outside) x=sx - w; else x=sx; break;case 'nw': if (outside){x=sx - w; y=sy - h;}else{x=sx; y=sy;}break;case 'cen': x=cenLeft; y=cenTop; break;case 'cenh': x=cenLeft; break;case 'cenv': y=cenTop; break;}var o = new Object();o.x = x; o.y = y;return o;}function xDeg(rad){return rad * (180 / Math.PI);}function xGetURLArguments(){var idx = location.href.indexOf('?');var params = new Array();if (idx != -1) {var pairs = location.href.substring(idx+1, location.href.length).split('&');for (var i=0; i<pairs.length; i++) {nameVal = pairs[i].split('=');params[i] = nameVal[1];params[nameVal[0]] = nameVal[1];}}return params;}function xHex(n, digits, prefix){var p = '', n = Math.ceil(n);if (prefix) p = prefix;n = n.toString(16);for (var i=0; i < digits - n.length; ++i) {p += '0';}return p + n;}function xIntersection(e1, e2, o){var ix1, iy2, iw, ih, intersect = true;var e1x1 = xPageX(e1);var e1x2 = e1x1 + xWidth(e1);var e1y1 = xPageY(e1);var e1y2 = e1y1 + xHeight(e1);var e2x1 = xPageX(e2);var e2x2 = e2x1 + xWidth(e2);var e2y1 = xPageY(e2);var e2y2 = e2y1 + xHeight(e2);if (e1x1 <= e2x1) {ix1 = e2x1;if (e1x2 < e2x1) intersect = false;else iw = Math.min(e1x2, e2x2) - e2x1;}else {ix1 = e1x1;if (e2x2 < e1x1) intersect = false;else iw = Math.min(e1x2, e2x2) - e1x1;}if (e1y2 >= e2y2) {iy2 = e2y2;if (e1y1 > e2y2) intersect = false;else ih = e2y2 - Math.max(e1y1, e2y1);}else {iy2 = e1y2;if (e2y1 > e1y2) intersect = false;else ih = e1y2 - Math.max(e1y1, e2y1);}if (intersect && typeof(o)=='object') {o.x = ix1;o.y = iy2 - ih;o.w = iw;o.h = ih;}return intersect;}function xLinearScale(val,iL,iH,oL,oH){var m=(oH-oL)/(iH-iL);var b=oL-(iL*m);return m*val+b;}function xPad(s,len,c,left){if(typeof s != 'string') s=s+'';if(left) {for(var i=s.length; i<len; ++i) s=c+s;}else {for (var i=s.length; i<len; ++i) s+=c;}return s;}function xRad(deg){return deg*(Math.PI/180);}

/* X Library, Copyright 2001-2005 Michael Foster (Cross-Browser.com). Distributed under the terms of the GNU LGPL */
/* floater_xlib.js compiled with XC v0.22b, see floater_xlib.txt for contributor copyrights, license info and documentation */
var xVersion='4.0',xOp7Up,xOp6Dn,xIE4Up,xIE4,xIE5,xNN4,xUA=navigator.userAgent.toLowerCase();if(window.opera){var i=xUA.indexOf('opera');if(i!=-1){var v=parseInt(xUA.charAt(i+6));xOp7Up=v>=7;xOp6Dn=v<7;}}else if(navigator.vendor!='KDE' && document.all && xUA.indexOf('msie')!=-1){xIE4Up=parseFloat(navigator.appVersion)>=4;xIE4=xUA.indexOf('msie 4')!=-1;xIE5=xUA.indexOf('msie 5')!=-1;}else if(document.layers){xNN4=true;}xMac=xUA.indexOf('mac')!=-1;function xAddEventListener(e,eT,eL,cap){if(!(e=xGetElementById(e))) return;eT=eT.toLowerCase();if((!xIE4Up && !xOp7Up) && e==window) {if(eT=='resize') { window.xPCW=xClientWidth(); window.xPCH=xClientHeight(); window.xREL=eL; xResizeEvent(); return; }if(eT=='scroll') { window.xPSL=xScrollLeft(); window.xPST=xScrollTop(); window.xSEL=eL; xScrollEvent(); return; }}var eh='e.on'+eT+'=eL';if(e.addEventListener) e.addEventListener(eT,eL,cap);else if(e.attachEvent) e.attachEvent('on'+eT,eL);else eval(eh);}function xResizeEvent(){if (window.xREL) setTimeout('xResizeEvent()', 250);var cw = xClientWidth(), ch = xClientHeight();if (window.xPCW != cw || window.xPCH != ch) { window.xPCW = cw; window.xPCH = ch; if (window.xREL) window.xREL(); }}function xScrollEvent(){if (window.xSEL) setTimeout('xScrollEvent()', 250);var sl = xScrollLeft(), st = xScrollTop();if (window.xPSL != sl || window.xPST != st) { window.xPSL = sl; window.xPST = st; if (window.xSEL) window.xSEL(); }}function xClientHeight(){var h=0;if(xOp6Dn) h=window.innerHeight;else if(document.compatMode == 'CSS1Compat' && !window.opera && document.documentElement && document.documentElement.clientHeight)h=document.documentElement.clientHeight;else if(document.body && document.body.clientHeight)h=document.body.clientHeight;else if(xDef(window.innerWidth,window.innerHeight,document.width)) {h=window.innerHeight;if(document.width>window.innerWidth) h-=16;}return h;}function xClientWidth(){var w=0;if(xOp6Dn) w=window.innerWidth;else if(document.compatMode == 'CSS1Compat' && !window.opera && document.documentElement && document.documentElement.clientWidth)w=document.documentElement.clientWidth;else if(document.body && document.body.clientWidth)w=document.body.clientWidth;else if(xDef(window.innerWidth,window.innerHeight,document.height)) {w=window.innerWidth;if(document.height>window.innerHeight) w-=16;}return w;}function xDef(){for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])=='undefined') return false;}return true;}function xGetComputedStyle(oEle, sProp, bInt){var s, p = 'undefined';var dv = document.defaultView;if(dv && dv.getComputedStyle){s = dv.getComputedStyle(oEle,'');if (s) p = s.getPropertyValue(sProp);}else if(oEle.currentStyle) {var a = sProp.split('-');sProp = a[0];for (var i=1; i<a.length; ++i) {c = a[i].charAt(0);sProp += a[i].replace(c, c.toUpperCase());}   p = oEle.currentStyle[sProp];}else return null;return bInt ? (parseInt(p) || 0) : p;}function xGetElementById(e){if(typeof(e)!='string') return e;if(document.getElementById) e=document.getElementById(e);else if(document.all) e=document.all[e];else e=null;return e;}function xHeight(e,h){if(!(e=xGetElementById(e))) return 0;if (xNum(h)) {if (h<0) h = 0;else h=Math.round(h);}else h=-1;var css=xDef(e.style);if (e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {h = xClientHeight();}else if(css && xDef(e.offsetHeight) && xStr(e.style.height)) {if(h>=0) {var pt=0,pb=0,bt=0,bb=0;if (document.compatMode=='CSS1Compat') {var gcs = xGetComputedStyle;pt=gcs(e,'padding-top',1);if (pt !== null) {pb=gcs(e,'padding-bottom',1);bt=gcs(e,'border-top-width',1);bb=gcs(e,'border-bottom-width',1);}else if(xDef(e.offsetHeight,e.style.height)){e.style.height=h+'px';pt=e.offsetHeight-h;}}h-=(pt+pb+bt+bb);if(isNaN(h)||h<0) return;else e.style.height=h+'px';}h=e.offsetHeight;}else if(css && xDef(e.style.pixelHeight)) {if(h>=0) e.style.pixelHeight=h;h=e.style.pixelHeight;}return h;}function xLeft(e, iX){if(!(e=xGetElementById(e))) return 0;var css=xDef(e.style);if (css && xStr(e.style.left)) {if(xNum(iX)) e.style.left=iX+'px';else {iX=parseInt(e.style.left);if(isNaN(iX)) iX=0;}}else if(css && xDef(e.style.pixelLeft)) {if(xNum(iX)) e.style.pixelLeft=iX;else iX=e.style.pixelLeft;}return iX;}function xMoveTo(e,x,y){xLeft(e,x);xTop(e,y);}function xNum(){for(var i=0; i<arguments.length; ++i){if(isNaN(arguments[i]) || typeof(arguments[i])!='number') return false;}return true;}function xPageX(e){if (!(e=xGetElementById(e))) return 0;var x = 0;while (e) {if (xDef(e.offsetLeft)) x += e.offsetLeft;e = xDef(e.offsetParent) ? e.offsetParent : null;}return x;}function xPageY(e){if (!(e=xGetElementById(e))) return 0;var y = 0;while (e) {if (xDef(e.offsetTop)) y += e.offsetTop;e = xDef(e.offsetParent) ? e.offsetParent : null;}return y;}function xScrollLeft(e, bWin){var offset=0;if (!xDef(e) || bWin || e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {var w = window;if (bWin && e) w = e;if(w.document.documentElement && w.document.documentElement.scrollLeft) offset=w.document.documentElement.scrollLeft;else if(w.document.body && xDef(w.document.body.scrollLeft)) offset=w.document.body.scrollLeft;}else {e = xGetElementById(e);if (e && xNum(e.scrollLeft)) offset = e.scrollLeft;}return offset;}function xScrollTop(e, bWin){var offset=0;if (!xDef(e) || bWin || e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {var w = window;if (bWin && e) w = e;if(w.document.documentElement && w.document.documentElement.scrollTop) offset=w.document.documentElement.scrollTop;else if(w.document.body && xDef(w.document.body.scrollTop)) offset=w.document.body.scrollTop;}else {e = xGetElementById(e);if (e && xNum(e.scrollTop)) offset = e.scrollTop;}return offset;}function xShow(e) {return xVisibility(e,1);}function xSlideTo(e, x, y, uTime){if (!(e=xGetElementById(e))) return;if (!e.timeout) e.timeout = 25;e.xTarget = x; e.yTarget = y; e.slideTime = uTime; e.stop = false;e.yA = e.yTarget - xTop(e); e.xA = e.xTarget - xLeft(e); if (e.slideLinear) e.B = 1/e.slideTime;else e.B = Math.PI / (2 * e.slideTime); e.yD = xTop(e); e.xD = xLeft(e); var d = new Date(); e.C = d.getTime();if (!e.moving) _xSlideTo(e);}function _xSlideTo(e){if (!(e=xGetElementById(e))) return;var now, s, t, newY, newX;now = new Date();t = now.getTime() - e.C;if (e.stop) { e.moving = false; }else if (t < e.slideTime) {setTimeout("_xSlideTo('"+e.id+"')", e.timeout);if (e.slideLinear) s = e.B * t;else s = Math.sin(e.B * t);newX = Math.round(e.xA * s + e.xD);newY = Math.round(e.yA * s + e.yD);xMoveTo(e, newX, newY);e.moving = true;}  else {xMoveTo(e, e.xTarget, e.yTarget);e.moving = false;}  }function xStr(s){for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])!='string') return false;}return true;}function xTop(e, iY){if(!(e=xGetElementById(e))) return 0;var css=xDef(e.style);if(css && xStr(e.style.top)) {if(xNum(iY)) e.style.top=iY+'px';else {iY=parseInt(e.style.top);if(isNaN(iY)) iY=0;}}else if(css && xDef(e.style.pixelTop)) {if(xNum(iY)) e.style.pixelTop=iY;else iY=e.style.pixelTop;}return iY;}function xVisibility(e, bShow){if(!(e=xGetElementById(e))) return null;if(e.style && xDef(e.style.visibility)) {if (xDef(bShow)) e.style.visibility = bShow ? 'visible' : 'hidden';return e.style.visibility;}return null;}function xWidth(e,w){if(!(e=xGetElementById(e))) return 0;if (xNum(w)) {if (w<0) w = 0;else w=Math.round(w);}else w=-1;var css=xDef(e.style);if (e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {w = xClientWidth();}else if(css && xDef(e.offsetWidth) && xStr(e.style.width)) {if(w>=0) {var pl=0,pr=0,bl=0,br=0;if (document.compatMode=='CSS1Compat') {var gcs = xGetComputedStyle;pl=gcs(e,'padding-left',1);if (pl !== null) {pr=gcs(e,'padding-right',1);bl=gcs(e,'border-left-width',1);br=gcs(e,'border-right-width',1);}else if(xDef(e.offsetWidth,e.style.width)){e.style.width=w+'px';pl=e.offsetWidth-w;}}w-=(pl+pr+bl+br);if(isNaN(w)||w<0) return;else e.style.width=w+'px';}w=e.offsetWidth;}else if(css && xDef(e.style.pixelWidth)) {if(w>=0) e.style.pixelWidth=w;w=e.style.pixelWidth;}return w;}

/* End coupons */

/* Begin requestpopup */
function SelectNewTab(ctr, newSelectedTabName, showContactContent, vehicleDescription, tabText) {
	var hiddenSelector = document.getElementById("hdnActiveTab");
	var oldSelected = document.getElementById('tab' + hiddenSelector.value);

	if (oldSelected != ctr) {
		ctr.className = 'RequestRightTabsTabSelected';

		if (oldSelected.id == 'tabRequestMoreInfo')
			oldSelected.className = "RequestRightTabsTabUnSelectedFirstTab";
		else
			oldSelected.className = "RequestRightTabsTabUnselected";

		// Changing content
		var divContactContant = document.getElementById('ctrContactInformationContentDiv');
		var divSubmitContactContant = document.getElementById('ctrRequestLeftMainContentSubmit');

		var divToHide = document.getElementById('ctrHeader' + hiddenSelector.value);
		divToHide.style.display = 'none';

		var divToShow = document.getElementById('ctrHeader' + newSelectedTabName);
		divToShow.style.display = 'block';

		if (!showContactContent) {
			divContactContant.style.display = 'none';
			divSubmitContactContant.style.display = 'none';
		} else {
			divContactContant.style.display = 'block';
			divSubmitContactContant.style.display = 'block';
		}

		var divRequestInfoHeader = document.getElementById('ctrRequestInfoHeader');

		divRequestInfoHeader.innerHTML = tabText;
		document.title = tabText + vehicleDescription;
		hiddenSelector.value = newSelectedTabName;
	}
	
	// Making sure content get displayd, not submit content
	var divLeftMainDivBlockSubmited =  document.getElementById('divLeftMainDivBlockSubmited');
	divLeftMainDivBlockSubmited.style.display = 'none';
	var divLeftMainDivBlock = document.getElementById('divLeftMainDivBlock');
	divLeftMainDivBlock.style.display = 'block';    
}

function SelectNewTabNids(ctr, newSelectedTabName, showContactContent, vehicleDescription, tabText) {
	var hiddenSelector = document.getElementById("hdnActiveTab");

	if (newSelectedTabName != hiddenSelector.value) {
		var newTab = $('#tab' + newSelectedTabName);
		var oldTab = $('#tab' + hiddenSelector.value);

		newTab.addClass('RequestTabSelected');
		oldTab.removeClass('RequestTabSelected');

		if (newTab.hasClass('RequestTabFirst'))
			$('#topLeftCorner').addClass('RequestContentTLSelected');

		if (oldTab.hasClass('RequestTabFirst')) {
			$('#topLeftCorner').removeClass('RequestContentTLSelected');
		}

		// Changing content
		var divContactContant = document.getElementById('ctrContactInformationContentDiv');
		var divSubmitContactContant = document.getElementById('ctrRequestLeftMainContentSubmit');

		var divToHide = document.getElementById('ctrHeader' + hiddenSelector.value);  
		divToHide.style.display = 'none';

		var divToShow = document.getElementById('ctrHeader' + newSelectedTabName);  
		divToShow.style.display = 'block';

		if (!showContactContent) {
			divContactContant.style.display = 'none';
			divSubmitContactContant.style.display = 'none';
		} else {
			divContactContant.style.display = 'block';
			divSubmitContactContant.style.display = 'block';
		}

		/*sharedPopupObj.func(tabText);*/

		//var divRequestInfoHeader = document.getElementById('RequestPopupHeaderTitleText');
		//divRequestInfoHeader.innerHTML = tabText;

		hiddenSelector.value = newSelectedTabName;
	}

	// Making sure content get displayd, not submit content
	var divLeftMainDivBlockSubmited =  document.getElementById('divLeftMainDivBlockSubmited');
	divLeftMainDivBlockSubmited.style.display = 'none';

	var divLeftMainDivBlock = document.getElementById('divLeftMainDivBlock');
	divLeftMainDivBlock.style.display = 'block';
}

function RequestMoreInfoValidate(currencySign, isFirstNameRequired, isLastNameRequired, isPhoneRequired, isZipRequired) {
	var errorList = '';
	// Common
	var ctrFirstName = document.getElementById("txtFirstName");
	if (isFirstNameRequired && trim(ctrFirstName.value).length == 0) {
		errorList += '- Please provide your First Name.  \n';
	}

	var ctrLastName = document.getElementById("txtLastName");
	if (isLastNameRequired && trim(ctrLastName.value).length == 0) {
		errorList += '- Please provide your Last Name.  \n';
	}

	var ctrPhone = document.getElementById("txtPhone");
	if (ctrPhone != null && isPhoneRequired && trim(ctrPhone.value).length == 0) {
		errorList += '- Please provide your Phone Number in 999-999-9999 format.  \n';
	}
	
	var ctrZip = document.getElementById("txtZip");
	if (ctrZip != null && !(/\d{5}/.test(ctrZip.value)) && (!isNullOrEmpty(ctrZip.value) || isZipRequired)) {
		errorList += '- Please provide a 5 digit numeric zip code.\n';
	}

	var ctrEmail = document.getElementById("txtEmail");
	if (trim(ctrEmail.value).length == 0) {
		errorList += '- Please provide your Email address, so we may respond to your inquire. \n';
	} else {
		if (!checkEmail(ctrEmail)) {
			errorList += '- Please fill out properly Your Email address, so we may respond to your inquire. \n';
		}
	}

	if (!checkAllowedChars(ctrEmail)) {
		errorList += '- Email control can not have \'<\' or \'>\' chars \n';
	}

	// tab dependant
	var hiddenSelector = document.getElementById("hdnActiveTab");
	if (hiddenSelector.value == 'RequestTestDrive') {
		var ctrFirstTimePreferenceDate = document.getElementById("ctrFirstTimePreferenceDate");
		if (trim(ctrFirstTimePreferenceDate.value).length == 0) {
			errorList += '- Please provide your 1st Time Preference. \n';
		} else {
			if (!checkDate(ctrFirstTimePreferenceDate)) {
				errorList += '- Please fill out properly 1st Time Preference field. I.E. 06/05/2008\n';
			}
		}
		var ctrSecondTimePreferenceDate = document.getElementById("ctrSecondTimePreferenceDate");
		if (trim(ctrSecondTimePreferenceDate.value).length > 0) {
			if (!checkDate(ctrSecondTimePreferenceDate)) {
				errorList += '- Please fill out properly 2nd Time Preference field. I.E. 06/05/2008 \n';
			}
		}
		var ctrNotes = document.getElementById("ctrTimePreferenceComment");
		if (!checkAllowedChars(ctrNotes)) {
			errorList += '- Note control can not have \'<\' or \'>\' chars \n';
		}
	}

	if (hiddenSelector.value == 'MakeAnOffer') {
		var ctrOfferPrice = document.getElementById("ctrOfferPrice");
		if (trim(ctrOfferPrice.value).length == 0) {
			errorList += '- Please provide your Offer Price . \n';
		} else {
			if (currencySign == '$' && !checkOfferPrice(ctrOfferPrice))
				errorList += '- Please fill out properly Offer Price field. I.E. ' + currencySign + '99999 \n';
		}
		var ctrNotes = document.getElementById("ctrMakeAnOfferComment");
		if (!checkAllowedChars(ctrNotes)) {
			errorList += '- Note control can not have \'<\' or \'>\' chars \n';
		}
	}
	
	if (hiddenSelector.value == 'RequestMoreInfo') {
		var ctrNotes = document.getElementById("txtRequestMoreInfoComment");
		if (!checkAllowedChars(ctrNotes)) {
			errorList += '- Note control can not have \'<\' or \'>\' chars \n';
		}
	}
	if (hiddenSelector.value == 'GetAQuote') {
		var ctrNotes = document.getElementById("txtGetAQuoteComment");
		if (!checkAllowedChars(ctrNotes)) {
			errorList += '- Note control can not have \'<\' or \'>\' chars \n';
		}
	}

	if (errorList != '') {
		alert('You must enter a value in the following fileds: \n' + errorList);
		return false;
	}
	return true;
}

function PageTracking(tabIndex, isSubmitted, isGoogleTrackingOn, isEbizTrackingOn, siteDefaultUrl, isToBeExecuted) {
	// NtPage Tracking
	if ( isEbizTrackingOn) {
		var eventTagParam = "";
		switch(tabIndex) {
			case 0: // RequestMoreInfo
				eventTagParam = 'leadview=RequestMoreInfo';
				break;
			case 1: // Make An Offer
				eventTagParam = 'leadview=MakeAnOffer';
				break;
			case 2: // Request Test Drive
				eventTagParam = 'leadview=RequestTestDrive';
				break;
			case 3: // Get a Quote
				eventTagParam = 'leadview=GetAQuote';
				break;
			case 4: // Call Today
				eventTagParam = 'leadview=CallToday';
				break;  
			case 5: // Payment Calculator
				eventTagParam = 'leadview=PaymentCalculator';
				break;
			case 6: // Contact Us                           
				eventTagParam = 'leadview=ContactUs';
				break;                             
			case 7: // TradeInAppraisal                           
				eventTagParam = 'leadview=TradeInAppraisal';
				break;                            
			case 8: // VehicleRequest                           
				eventTagParam = 'leadview=VehicleRequest';
				break;                            
			case 9: // Coupons                           
				eventTagParam = 'leadview=Coupons';
				break;                             
			case 10: // CreditApp                           
				eventTagParam = 'leadview=CreditApp';
				break;                            
			case 11: // ServiceRequest                           
				eventTagParam = 'leadview=ServiceRequest';
				break;                            
			case 12: // PartsRequest                           
				eventTagParam = 'leadview=PartsRequest';
				break;                            
			case 13: // View Tell A Friend Details                           
				eventTagParam = 'leadview=TellAFriendDetails';
				break;                             
			case 14: // View Tell A Friend Inventory                           
				eventTagParam = 'leadview=TellAFriendInventory';
				break;                             
			case 15: // Print Detail
				eventTagParam = 'leadview=PrintDetail';
				break;
			case 16: // Print Inventory                            
				eventTagParam = 'leadview=PrintInventory';
				break;                          
			case 17: // Auto Check                            
				eventTagParam = 'leadview=AutoCheck';
				break;                          
			case 18: // CARFAX                           
				eventTagParam = 'leadview=Carfax';
				break;                             
			case 19: // View Google Maps                          
				eventTagParam = 'leadview=ViewGoogleMaps';
				break;  
			case 20: // View Driving Direction                           
				eventTagParam = 'leadview=ViewDrivingDirection';
				break;                             
			case 21: // View Vehicle Brochure Full                           
				eventTagParam = 'leadview=VehicleBrochureFull';
				break;                             
			case 22: // View Vehicle Brochure Summary                           
				eventTagParam = 'leadview=VehicleBrochureSummary';
				break;                             
			case 23: // View Vehicle Media Viewer                           
				eventTagParam = 'leadview=VehicleMediaViewer';
				break;                             
			case 24: // View Vehicle Compare                           
				eventTagParam = 'leadview=VehicleCompare';
				break;                             
			case 25: // VehicleBrochureChoose                           
				eventTagParam = 'leadview=VehicleBrochureChoose';
				break;                            
			case 26: // Quick Quote                           
				eventTagParam = 'leadview=QuickQuote';
				break;                            
			case 27: // OEM Sticker
				eventTagParam = 'leadview=OEMWindowSticker';
				break;                            
		}
		if (isSubmitted)
			eventTagParam = eventTagParam + '&completed=true';

		if (eventTagParam.length > 0)
			ntptEventTag(eventTagParam);
	}

	if (isGoogleTrackingOn) {
		var trackingTarget = "";
		if (isSubmitted) {
			trackingTarget = '/submitleads.html';
			pageTracker._trackPageview(trackingTarget);
		} else {
			switch(tabIndex) {
				case 0: // RequestMoreInfo
					trackingTarget = '/leadspopuprequestmoreinfo.html';
					break;
				case 1: // Make An Offer
					trackingTarget = '/leadspopupmakeanoffer.html';
					break;
				case 2: // Request Test Drive
					trackingTarget = '/leadspopuprequesttestdrive.html';
					break;
				case 3: // Get a Quote
					trackingTarget = '/leadspopupgetquote.html';
					break;
				case 4: // Call Today 
					trackingTarget = '/leadspopupcalltoday.html';
					break;
				case 5: // Payment Calculator
					trackingTarget = '/leadspopuppaymentcalculator.html';
					break;
				case 6: // ContactUs
					trackingTarget = '/contactus.html';
					break;
				case 7: // Trade Appraisal
					trackingTarget = '/tradeappraisal.html';
					break;
				case 8: // VehicleRequest
					trackingTarget = '/carfinder.html';
					break;
				case 9: // Coupons
					trackingTarget = '/coupon.html';
					break;
				case 10: // Credit App
					trackingTarget = '/creditapp.html';
					break;
				case 11: // Service Request
					trackingTarget = '/servicerequest.html';
					break;
				case 12: // Parts Request
					trackingTarget = '/parts.html';
					break;
				case 13: // Email A Frined Detail
					trackingTarget = '/emailafrineddetail.html';
					break;
				case 14: // Email A Frined Inventory
					trackingTarget = '/emailafrinedinventory.html';
					break;
			}
			if (trackingTarget.length > 0)
				pageTracker._trackPageview(trackingTarget);
		}
	}
	if (isToBeExecuted)
		ExecuteCampaignConversionTrackingCode(siteDefaultUrl);
}

/* End requestpopup */

/*Begin tellafriend */ 
function ValidateTellaFriend() {
	var errorList = '';
	// Common
	var ctrName = document.getElementById("_txtName");
	if (trim(ctrName.value).length == 0) {
		errorList += '- Please provide Your Name.  \n';
	}

	var ctrSendersEmail = document.getElementById("_txtSendersEmail");
	if (trim(ctrSendersEmail.value).length == 0 || !checkEmail(ctrSendersEmail)) {
		errorList += '- Please provide Your Email Address.  \n';
	}

	var ctrEmail = document.getElementById("_txtEmail");
	
	if (trim(ctrEmail.value).length == 0 || !checkEmail(ctrEmail)) {
		errorList += '- Please provide Recipient\'s Email Address.  \n';
	}

	var ctrCustomMessage = document.getElementById("_txtCustomMessage");
	if (trim(ctrCustomMessage.value).length == 0) {
		errorList += '- Please provide Personal Message. \n';
	}
	
	if (/<|>|\\/.test(ctrName.value)) {
		errorList += 'You have entered an invalid character in the field \"Your Name\" \nThese characters are not allowed: \\ > and < \n';
	}
	
	if (/<|>|\\/.test(ctrCustomMessage.value)) {
		errorList += 'You have entered an invalid character in the field \"Personal Message\" \nThese characters are not allowed: \\ > and < \n';
	}
	if (errorList != '') {
		alert('You must enter a value in the following fileds: \n' + errorList);
	} else {
		frmTellAFriend.submit();
	}
}

function clearForm() {
	document.getElementById('_txtName').value = '';
	document.getElementById('_txtSendersEmail').value = '';
	document.getElementById('_txtEmail').value = '';
	document.getElementById('_chkSendCopy').checked = false;
}

/* End tellafriend */ 

function OpenCompareWindow(pageUrl, tabIndex) {
	params = "";
	
	var cnt = 0;
	$("input[type='checkbox']:checked").each(function() {
		if (this.id.substr(0, 2) == "cb") {
			params = params + this.id.substr(2) + ",";
			cnt = cnt + 1;
		}
	});

	if (cnt > 3) {
		alert("A maximum of 3 vehicles can be selected for Vehicle Comparison.");
		return;
	}
	
	if (cnt == 0) {
		alert("You should select at least one vehicle.");
		return;
	}
	
	PageTracking(tabIndex, false, false, true, '', false);
	_popupObject = $('<div id="CompareVehiclesContainer"><div class="ClosePopupBtn" onmouseover="this.className=\'ClosePopupBtn_hover\'" onmouseout="this.className=\'ClosePopupBtn\'"><b></b></div><div class="CompareVehiclesInner"><div class="CompareVehiclesInner2"><div style="height: 200px;">loading...</div></div></div></div>').modal({
		zIndex: 20000,
		close: true,
		positionStyle: 'absolute',
		containerCss: {width: 950},
		containerId: 'PopupLoaderContainer',
		position: [40,]
	});

	$('body').animate({scrollTop:0}, 'slow');

	$('#CompareVehiclesContainer .ClosePopupBtn').bind('click.simplemodal', function (e) {
		e.preventDefault();
		_popupObject.close();
	});

	$.ajax({
		type: "POST",
		url: pageUrl,
		data: "iids=" + params,
		success: function(response) {
			$("#CompareVehiclesContainer .CompareVehiclesInner2").html(response);
		},
		error: function(obj, msg) {
			$("#CompareVehiclesContainer .CompareVehiclesInner2 div").html("Error occured while loading content.");
		}
	});
}


function ExpandCompareOptions() {
	$("#CompareVehiclesContainer .OptionsLink").css("display", "none");
	$("#CompareVehiclesContainer .OptionsData").css("display", "block");
}

function contentBlockRedirect(currentElement, oEvent, link){
	var isIncorrectTag = false;
	var hasDifferentOnClick = false; 
	var element = ( oEvent.target ? oEvent.target : oEvent.srcElement );
	
	isIncorrectTag = (element.tagName == 'A' || element.parentNode.tagName == 'A' || element.tagName == 'INPUT');
	hasDifferentOnClick = (element.onclick != null && element != currentElement);
	
	if (!isIncorrectTag && !hasDifferentOnClick) 
		document.location = link;
}

function checkCompareInput(element){
	var compareCheckedCount = $(".itemCb0 input:checkbox:checked, .itemCb1 input:checkbox:checked, .itemCb2 input:checkbox:checked").length;
	
	if (compareCheckedCount > 3) {
		element.checked = false;
		alert("A maximum of 3 vehicles can be selected for Vehicle Comparison.");
	}
}
