﻿var _imagesRoot0 = 'http://images.ebizautos.com/ebizautoscorporatesite/';
var _imagesRoot1 = 'http://1-images.ebizautos.com/ebizautoscorporatesite/';
var _imagesRoot2 = 'http://2-images.ebizautos.com/ebizautoscorporatesite/';
var _imagesRoot3 = 'http://3-images.ebizautos.com/ebizautoscorporatesite/';
var _imagesRoot4 = 'http://4-images.ebizautos.com/ebizautoscorporatesite/';

var _timeToCallList = [
	{Key: 'Anytime', Value: 'Anytime'},
	{Key: 'Morning', Value: 'Morning'},
	{Key: 'Afternoon', Value: 'Afternoon'},
	{Key: 'Evening', Value: 'Evening'}
];

var _dealerTypeList = [
	{Key: 'Independent', Value: 'Independent'},
	{Key: 'Franchise', Value: 'Franchise'},
	{Key: 'Dealer Group', Value: 'Dealer Group'},
	{Key: 'Other', Value: 'Other'}
];

var _roleTitleList = [
	{Key: 'Owner', Value: 'Owner'},
	{Key: 'General Manager', Value: 'General Manager'},
	{Key: 'General Sales Manager', Value: 'General Sales Manager'},
	{Key: 'Used Car Manager', Value: 'Used Car Manager'},
	{Key: 'Service Manager', Value: 'Service Manager'},
	{Key: 'Other', Value: 'Other'}
];

$(document).ready(
	function () {
		if ($.browser.msie && $.browser.version.substring(0,1) === '6') { //FixPngTransparency();
			$("img.FixIe6Transp").each(function(i) {
				this.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "',sizingMethod='crop')";
			});
		}
	
		//FixPngTransparency();
		
		$("#navigationWhyUseCell").mouseenter( function(event) { NavEnterMenu("NavigationWhyUse"); });
		$("#navigationWhyUseCell").mouseleave( function(event) { NavLeaveMenu("NavigationWhyUse"); });

		$("#navigationServiceCell").mouseenter( function(event) { NavEnterMenu("NavigationService"); });
		$("#navigationServiceCell").mouseleave( function(event) { NavLeaveMenu("NavigationService"); });

		$("#navigationWebsitesCell").mouseenter( function(event) { NavEnterMenu("NavigationWebsites"); });
		$("#navigationWebsitesCell").mouseleave( function(event) { NavLeaveMenu("NavigationWebsites"); });

		$("#navigationSoftwareCell").mouseenter( function(event) { NavEnterMenu("NavigationSoftware"); });
		$("#navigationSoftwareCell").mouseleave( function(event) { NavLeaveMenu("NavigationSoftware"); });

		$("#navigationMarketingCell").mouseenter( function(event) { NavEnterMenu("NavigationMarketing"); });
		$("#navigationMarketingCell").mouseleave( function(event) { NavLeaveMenu("NavigationMarketing"); });
	});

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')";
	}
}

function NavEnterMenu(groupName) {
	$("." + groupName).hide();
	$("." + groupName + "Hover").show();
	$("." + groupName + "Menu").show();
}

function NavLeaveMenu(groupName) {
	$("." + groupName).show();
	$("." + groupName + "Hover").hide();
	$("." + groupName + "Menu").hide();
}

function Switch(loc) {
	window.location.href = loc;
	DetectSubPage();
}

function DetectSubPage() {
	_currentSubPageId = 0;
	for (i = 0; i < _subPagesList.length; i++) {
		if (_subPagesList[i] == window.location.hash)
			_currentSubPageId = i;
	}
	$('#SubPage .ButtonsContainer .Button').removeClass("ButtonSelected");
	$('#SubPage .ButtonsContainer .ButtonFirst').removeClass("ButtonSelectedFirst");
	$('#SubPage .ButtonsContainer .CornerTop').hide();
	$('#SubPage .ButtonsContainer .CornerBottom').hide();
	$('#SubPage .SubPageRightContent .MiddleContentData').hide();

	$('#_btn' + _currentSubPageId + '.Button').addClass("ButtonSelected");
	$('#_btn' + _currentSubPageId + '.ButtonFirst').addClass("ButtonSelectedFirst");
	$('#_data' + _currentSubPageId + '.MiddleContentData').show();
	$('#_btn' + (_currentSubPageId + 1) + ' .CornerBottom').show();
	if (_currentSubPageId > 0) {
		$('#_btn' + (_currentSubPageId - 1) + ' .CornerTop').show();
	}
}

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 SlideImages(ind) {
	for (i = 1; i < 6; i++) {
		var el = document.getElementById('ListImg' + i);
		el.src = el.src.replace('_act', '');
	}
	document.getElementById('ListImg' + ind).src = document.getElementById('ListImg' + ind).src.replace("small" + ind, "small" + ind + "_act");
	el = document.getElementById('CustomWebsitesImg');
	el.src = el.src.substr(0, el.src.length - 5) + ind + ".jpg";
}

function SwitchToHover(el) {
	var imgUrl = el.src;
	var ind = imgUrl.lastIndexOf(".");
	imgUrl = imgUrl.substr(0, ind) + "_hover" + imgUrl.substr(ind);
	el.src = imgUrl;
}

function SwitchToNormal(el) {
	el.src = el.src.replace("_hover", "");
}

function SwitchContent(index) {
	document.getElementById("innerTitlePageContent1").style.display = 'none';
	document.getElementById("innerTitlePageContent2").style.display = 'none';
	document.getElementById("innerTitlePageContent3").style.display = 'none';
	document.getElementById("innerTitlePageContent4").style.display = 'none';
	document.getElementById("innerTitlePageContent5").style.display = 'none';
	document.getElementById("innerTitlePageContent"+index).style.display = 'block';
}

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(email))) {
		return false;
	} else {
		return true;
	}
}

function SubmitContactUs(siteUrl) {
	var isValid = true;
	var message = "";
	var txtName = $("#txtName").val(); 
	var txtDealership = $("#txtDealershipName").val();
	var txtEmail = $("#txtEmail").val(); 
	var txtPhone = $("#txtPhone").val(); 
	var txtComments = $("#txtComments").val();
	var isCurrentDealer = $("#isCurrentDealer2").is(':checked');
	
	if (txtName == "" || txtName == "Your Name") {
		isValid = false;
		message = "Please Enter Your Name\n";
	}
	
	if (txtDealership == "" || txtDealership == "Dealership Name") {
		isValid = false;
		message += "Please Enter Dealership Name\n";
	}
	
	if (txtEmail == "" || txtEmail == "Email Address" || !CheckEmailStr(txtEmail)) {
		isValid = false;
		message += "Please Enter Correct Email Address\n";
	}
	
	if (!checkPhoneNumber('txtPhone') || txtPhone == "Phone") {
		isValid = false;
		message += "Please Enter Phone Number In 999-999-9999 Format\n";
	}
	
	if (!checkComments('txtComments')) {
		isValid = false;
		message += "HTML and XML prohibited. Only plain text allowed.\n";
	}

	if (isValid) {
		//$("#footerContactUsForm").hide();
		//$("#footerAfterSubmitContect").show();

		$.ajax({
			type: "POST",
			url: siteUrl + "webservice/webservice.asmx/ContactUs",
			data: '{"name": "'+txtName+'","dealershipName": "'+txtDealership+'","email": "'+txtEmail+'","phone": "'+txtPhone+'","comments": "'+txtComments+'","isNotify": '+ $('input#chkIsNotify').is(':checked') + ',"isCurrentDealer": ' + isCurrentDealer + '}',
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(response) {
						if (response.length == 0) {
							$("#footerContactUsForm").hide();
							$("#footerAfterSubmitContect").show();
						} else {
							alert(response);
						}
			},
			failure: function(msg) {
				alert(msg);
			}
		});
	} else
		alert(message);
	
}

function SubmitContactUsAccountForm() {
	var form = $('#AccountForm')[0];
	var dealershipName = $('#DealershipName').val();
	var dealershipWebsite = $('#DealershipWebsite').val();
	var dealershipType = $('#DealershipType').val();
	var firstName = $('#FirstName').val();
	var lastName = $('#LastName').val();
	var emailAddress = $('#EmailAddress').val();
	var phoneNumber = $('#PhoneNumber').val();
	var zipCode= $('#ZIPCode').val();
	var bestTimeToCall= $('#BestTimeToCall').val();
	var commentsorQuestions= $('#CommentsorQuestions').val();
	
	var isValid = true;
	var message = "";
	
	if (dealershipName == "") {
		isValid = false;
		message += "Please Enter Dealership Name\n";
	}
	if (dealershipWebsite  == "") {
		isValid = false;
		message += "Please Enter Dealership Website\n";
	}
	if (dealershipType  == "") {
		isValid = false;
		message += "Please Enter Dealership Type\n";
	}
	if (firstName  == "") {
		isValid = false;
		message += "Please Enter First Name\n";
	}
	if (lastName  == "") {
		isValid = false;
		message += "Please Enter Last Name\n";
	}
	if (emailAddress  == "" || !CheckEmailStr(emailAddress)) {
		isValid = false;
		message += "Please Enter Email Address\n";
	}	
	if (isValid) {
		form.submit();
	} else {
		alert(message);
	}
}
function SubmitClientLoginForm(){
	var form = $('#loginform')[0];
	var username = $('#email').val();
	var isValid = true;
	var message = "";

	if (username == "") {
		isValid = false;
		message += "Please Enter Username\n";
	}
	if (isValid) {
		return true;
	} else {
		alert(message);
		return false;
	}
}

function SubmitForgotPasswordForm() {
	var form = $('#FogotPasswordForm')[0];
	var username = $('#username').val();
	var email = $('#email').val();
	var isValid = true;
	var message = "";
	
	if (username == "") {
		isValid = false;
		message += "Please Enter Username\n";
	}
	if (email == "" || !CheckEmailStr(email)) {
		isValid = false;
		message += "Please Enter Email Using Format aaa@aaaaa.aaa\n";
	}		
	if (isValid) {
		return true;
	} else {
		alert(message);
		return false;
	}
}

function SubmitGetStartedForm() {
	var form = $('#getStartedForm')[0];
	var dealershipName = $('#dealershipName').val();
	var dealershipType = $('#dealershipType').val();
	var myName = $('#myName').val();
	var phoneNumber = $('#phoneNumber').val();
	var emailAddress = $('#emailAddress').val();
	var bestTimeToCall= $('#bestTime').val();
	var dealershipWebsite = $('#dealershipWebsite').val();

	var isValid = true;
	var message = "";
	
	if (dealershipName == "") {
		isValid = false;
		message += "Please Enter Dealership Name\n";
	}
	if (dealershipWebsite  == "") {
		isValid = false;
		message += "Please Enter Dealership Website\n";
	}
	if (dealershipType  == "") {
		isValid = false;
		message += "Please Enter Dealership Type\n";
	}
	if (myName  == "") {
		isValid = false;
		message += "Please Enter Your Name\n";
	}
	if (emailAddress  == "" || !CheckEmailStr(emailAddress)) {
		isValid = false;
		message += "Please Enter Email Address\n";
	}	
	if (phoneNumber  == "" || !checkPhoneNumber('phoneNumber')) {
		isValid = false;
		message += "Please Enter Phone Number In 999-999-9999 Format\n";
	}	
	if (isValid) {
		_popupObject = $('#SendRequest').modal({
				zIndex: 20000,
				close: false,
				positionStyle: 'absolute',
				containerCss: {width: 200, height: 200},
				containerId: 'SendRequestOuter',
				position: [0,]
			});
		document.getElementById('simplemodal-overlay').style.opacity = '0';
		form.submit();
	} else {
		alert(message);
	}
}

function checkPhoneNumber(id) {
	var obj = document.getElementById(id);
	if (obj.value.length > 0) {
		if ((/^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$/.test(obj.value))) 
			return true;
		else 
			return false;
	}
	return true;
}


function checkComments(id) {
	var obj = document.getElementById(id);
	if (obj.value.length > 0) {
		if (!(/>|<|"/.test(obj.value))) 
			return true;
		else 
			return false;
	}
	return true;
}

function pricingTabClick(tab) {
	var includedTab = $("#includedTab");
	var upgradedTab = $("#upgradedTab");
	var includedContect = $("#included");
	var upgradedContent = $("#upgraded");
	
	if (tab == includedTab[0] && includedTab[0].className == "pricingTab") {
		includedTab[0].className = "pricingTabSelected";
		upgradedTab[0].className = "pricingTab";
		
		upgradedContent.hide();
		includedContect.show();
	} else if ( tab == upgradedTab[0] && upgradedTab[0].className == "pricingTab" ) {
		upgradedTab[0].className = "pricingTabSelected";
		includedTab[0].className = "pricingTab";
		
		includedContect.hide();
		upgradedContent.show();
	}
}

function UpdateChecks(strItem) {
	//Firefox will cache the page containing lstSelectedFeatures
	//Since we want to clear the previous values once upon page load
	//and this function is also only called once upon page load
	//with ebizautos40 as a parameter to stritem,
	//reset the lstSelectedFeatures to nothing at that time
	if (strItem == "resetall") {
		document.getElementById('lstSelectedFeatures').value = "";
	}
	else {
		var arySelectedFeatures = document.getElementById('lstSelectedFeatures').value.split(',');
		var blnFoundItem = 0;
		var intItemPos = 0;
		var lstSelectedFeatures = "";

		for (i=0;i<arySelectedFeatures.length;i++) {
			if (arySelectedFeatures[i] == strItem) {
				blnFoundItem = 1;
				intItemPos = i;
			}
		}
		if (!blnFoundItem) {
			if( document.getElementById(strItem))
				document.getElementById(strItem).src = _imagesRoot3 + 'common/checkbox_selected.gif';
			arySelectedFeatures.push(strItem);
		} else {
			if( document.getElementById(strItem) )
				document.getElementById(strItem).src = _imagesRoot2 + 'common/checkbox.gif';
			var removearrayelement = arySelectedFeatures.splice(intItemPos,1);
		}

		lstSelectedFeatures = arySelectedFeatures.join();
		lstSelectedFeatures = lstSelectedFeatures.replace(/^\,/,'');

		document.getElementById('lstSelectedFeatures').value = lstSelectedFeatures;
	}
}

var allSelected = false;
function FeaturesSelectAll() {
	if( !allSelected ) {
		UpdateChecks('resetall');

		UpdateChecks('websites');
		UpdateChecks('dealerportals');
		UpdateChecks('marketingoptimization');
		UpdateChecks('sem');
		UpdateChecks('seo');
		UpdateChecks('craigslist');
		UpdateChecks('ebay');
		UpdateChecks('classifieds');
		UpdateChecks('datacollection');
		UpdateChecks('windowstickers');
		allSelected = true;
		document.getElementById('selectall').src = _imagesRoot3 + 'common/checkbox_selected.gif';
	}
	else {
		allSelected = false;
		document.getElementById('selectall').src = _imagesRoot2 + 'common/checkbox.gif';
		if( document.getElementById('websites').src.indexOf('common/checkbox_selected.gif') > 0 )
			UpdateChecks('websites');
		if( document.getElementById('dealerportals').src.indexOf('common/checkbox_selected.gif') > 0 )
			UpdateChecks('dealerportals');
		if( document.getElementById('marketingoptimization').src.indexOf('common/checkbox_selected.gif') > 0 )
			UpdateChecks('marketingoptimization');
		if( document.getElementById('sem').src.indexOf('common/checkbox_selected.gif') > 0 )
			UpdateChecks('sem');
		if( document.getElementById('seo').src.indexOf('common/checkbox_selected.gif') > 0 )
			UpdateChecks('seo');
		if( document.getElementById('craigslist').src.indexOf('common/checkbox_selected.gif') > 0 )
			UpdateChecks('craigslist');
		if( document.getElementById('ebay').src.indexOf('common/checkbox_selected.gif') > 0 )
			UpdateChecks('ebay');
		if( document.getElementById('classifieds').src.indexOf('common/checkbox_selected.gif') > 0 )
			UpdateChecks('classifieds');
		if( document.getElementById('datacollection').src.indexOf('common/checkbox_selected.gif') > 0 )
			UpdateChecks('datacollection');
		if( document.getElementById('windowstickers').src.indexOf('common/checkbox_selected.gif') > 0 )
			UpdateChecks('windowstickers');
	}
}

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 {
		return true;
	}
	return false;
}

function clearForm() {
	document.getElementById('_txtName').value = '';
	document.getElementById('_txtSendersEmail').value = '';
	document.getElementById('_txtEmail').value = '';
	document.getElementById('_txtCustomMessage').value = '';
	document.getElementById('_chkSendCopy').checked = false;
}

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 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 ExecuteCampaignConversionTrackingCode(pathToFile) {
	//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";
	try {
		var obj = document.createElement('object');
		//this object contains data for Conversion Tracking
		obj.data = pathToFile;
		obj.type = "text/html";
		oDiv.appendChild(obj);
	}
	catch (err){
	}
}

function IsZipValid(value) {
	return /(^\d{5}$)|(^\d{5}-\d{3}$)/.test(value);
}

function IsPhoneValid(value) {
	return /^\(\d{3}\)\s\d{3}-\d{4}|\(\d{3}\)-\d{3}-\d{4}|\d{3}\-\d{3}-\d{4}|\d{3}\d{3}\d{4}$/.test(value);
}

function IsEmailValid(value) {
	return /^[_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(value);
}

function BaseValidate(formId) {
	var inputs = $('#' + formId + ' input,' + '#' + formId + ' select,' + '#' + formId + ' textarea,' + '#' + formId + ' div.RadioType');
	
	var input = null;
	var hidenMsgObj = null;
	var errMsg = '';

	inputs.each(function () {
		input = $(this);
		hidenMsgObj = $('#' + (input.attr('name') ? input.attr('name') : input.attr('id')) + 'Msg');

		if (!input.attr('disabled')) {
			if (/<|>|"/.test(input.val())) {
				errMsg += "- ‘<’,‘>’, and quotation marks chars are not allowed.\n";
			}
			if (input.hasClass('TxtType') && input.hasClass('Required') && input.val() == '') {
				if (hidenMsgObj.length > 0) {
					errMsg += hidenMsgObj.text() + '\n';
				} else if (input.attr('title') != '') {
					errMsg += '- ' + input.attr('title') + '\n';
				} else {
					errMsg += '- Field could not be empty. \n';
				}
			}

			if (input.hasClass('SelectType') && input.hasClass('Required') && input.val() == 0) {
				if (hidenMsgObj.length > 0) {
					errMsg += hidenMsgObj.text() + '\n';
				} else if (input.attr('title') != '') {
					errMsg += '- ' + input.attr('title') + '\n';
				} else {
					errMsg += '- Dropdown should be selected. \n';
				}
			}

			if (input.hasClass('ZipCodeType') && ((input.hasClass('Required') || input.val() != '') && !IsZipValid(input.val()))) {
				if (hidenMsgObj.length > 0) {
					errMsg += hidenMsgObj.text() + '\n';
				} else if (input.attr('title') != '') {
					errMsg += '- ' + input.attr('title') + '\n';
				} else {
					errMsg += '- Please provide correct zip code.\n';
				}
			}

			if (input.hasClass('PhoneType') && ((input.hasClass('Required') || input.val() != '') && !IsPhoneValid(input.val()))) {
				if (hidenMsgObj.length > 0) {
					errMsg += hidenMsgObj.text() + '\n';
				} else if (input.attr('title') != '') {
					errMsg += '- ' + input.attr('title') + '\n';
				} else {
					errMsg += '- Please provide correct phone number.\n';
				}
			}

			if (input.hasClass('EmailType') && ((input.hasClass('Required') || input.val() != '') && !IsEmailValid(input.val()))) {
				if (hidenMsgObj.length > 0) {
					errMsg += hidenMsgObj.text() + '\n';
				} else if (input.attr('title') != '') {
					errMsg += '- ' + input.attr('title') + '\n';
				} else {
					errMsg += '- Please provide correct email.\n';
				}
			}

			if (input.hasClass('ChbxType') && input.hasClass('Required') && input.attr('checked') == false) {
				if (hidenMsgObj.length > 0) {
					errMsg += hidenMsgObj.text() + '\n';
				} else if (input.attr('title') != '') {
					errMsg += '- ' + input.attr('title') + '\n';
				} else {
					errMsg += '- Checkbox should be selected. \n';
				}
			}

			if (input.hasClass('RadioType') && input.hasClass('Required') && $('#' + input.attr('id') + ' input:radio:checked').length == 0) {
				if (hidenMsgObj.length > 0) {
					errMsg += hidenMsgObj.text() + '\n';
				} else if (input.attr('title') != '') {
					errMsg += '- ' + input.attr('title') + '\n';
				} else {
					errMsg += '- Radiobox should be selected. \n';
				}
			}

		}
	});
	
	return errMsg;
}

function SubmitForm(idForm, hasTracking) {
	var message = "Please provide the following to complete this form:\n";
	var error = BaseValidate(idForm);

	if (error == "") {
		if (hasTracking === true)
			pageTracker._trackEvent('email leads', 'submit request', 'leads');
		return true;
	} else {
		alert(message + error);
		return false;
	}
}


// jQuery dropdown control
(function($){
	$.fn.dropDown = function(_options) {
		var _self = this;
		
		var _defaults = {
			defaultLabel: "Select Value",
			hasScroll: true,
			slideTime: 100,
			onClick: function(selectedId, selectedValue) {},
			maxHeight: 0
		}
		var _options = $.extend(_defaults, _options);
		var _data = [];
		var _listHeight = 0;
		var _isOpened = false;
		
		if (!(_self._isInitialized)) {
			var _selectedEl = $("<div class='initialLabel'>" + _options.defaultLabel + "</div>");
			_self.append($("<div class='initialLabelWr1' />").append($("<div class='initialLabelWr2' />").append($("<div class='initialLabelWr3' />").append(_selectedEl))));
			$('.initialLabelWr1', _self).click(function () {
				if (_isOpened)
					_self.Close();
				else
					_self.Open();
			});

			var _dropdownEl = $("<div class='dropdown hidden'></div>");
			_self.append(_dropdownEl);
			
			if (_options.hasScroll) {
				var _dropdownButtonUp = $("<div class='dropdownButtonUp'></div>");
				var _dropdownScrollerArea = $("<div class='dropdownScrollerArea'></div>");
				var _dropdownButtonDown = $("<div class='dropdownButtonDown'></div>");
								
				_dropdownEl.append(_dropdownButtonUp);
				_dropdownEl.append(_dropdownScrollerArea);
				_dropdownEl.append(_dropdownButtonDown);
			}
			var _dropdownList = $("<div class='dropdownList'></div>");
			_dropdownEl.append(_dropdownList);
			
			_self.Open = function() {
				_isOpened = true;
				_dropdownEl.removeClass("hidden");
				_dropdownEl.css({
					top: _self.offset().top + 28,
					left: _self.offset().left
				});
				RefreshScroller();
			}
			_self.Close = function() {
				_isOpened = false;
				_isSliding = false;
				_dropdownEl.addClass("hidden");
				_dropdownEl.addClass("hidden");
			}

			//hide if mouse out of control for more than 500ms
			var _popupTimer;
			_self.mouseleave(function() {
				_isSliding = false;
				_popupTimer = setTimeout(function() { _self.Close(); }, 500);
				$(this).toggleClass("selectorHovered");
			})
			_self.mouseenter(function() {
				clearTimeout(_popupTimer);
				$(this).toggleClass("selectorHovered");
			});
			
			_self.Click = function(selectedId, selectedValue) {
				_self.SetSelectedIdAndValue(selectedId, selectedValue);
				if (jQuery.isFunction(_options.onClick)) {
					_options.onClick(selectedId, selectedValue);
				}
			}
			
			var _isSliding = false;
			var _selectedId = "";
			var _selectedValue = "";
			var _selectedDataIndex = -1;
			
			_self.GetSelectedId = function() {
				return _selectedId;
			}
			_self.GetSelectedValue = function() {
				return _selectedValue;
			}
			_self.SetSelectedId = function(newId, noReselect) {
				newId = newId.toString().toLowerCase().replace(/ /g, "_");
				_selectedDataIndex = -1;
				_selectedId = "";
				_selectedValue = "";
				for (x = 0; x < _data.length; x++) {
					if (_data[x].Key == newId) {
						_selectedDataIndex = x;
						_selectedId = _data[x].Key;
						_selectedValue = _data[x].Value;
						break;
					}
				}
				if (!noReselect) {
					ReselectValue();
				}
			}
			_self.SetSelectedValue = function(newValue, noReselect) {
				_selectedDataIndex = -1;
				_selectedId = "";
				_selectedValue = "";
				for (x = 0; x < _data.length; x++) {
					if (_data[x].Value == newValue) {
						_selectedDataIndex = x;
						_selectedId = _data[x].Key;
						_selectedValue = _data[x].Value;
						break;
					}
				}
				if (!noReselect) {
					ReselectValue();
				}
			}
			_self.SetSelectedIdAndValue = function(newId, newValue) {
				_self.SetSelectedId(newId, true);
				if (_selectedDataIndex == -1) {
					_self.SetSelectedValue(newValue, true);
				}
				ReselectValue();
			}

			_self.Refresh = function() {
				//remove item listeners;
				$(".dropdownItem", _dropdownEl).unbind('mouseenter');
				$(".dropdownItem", _dropdownEl).unbind('mouseleave');
				$(".dropdownItem", _dropdownEl).unbind('click');
				//hover style handler;
				$(".dropdownItem", _dropdownEl).mouseenter(function(){
					$(this).toggleClass("itemsHovered");
				});
				$(".dropdownItem", _dropdownEl).mouseleave(function(){
					$(this).toggleClass("itemsHovered");
				});
				//on item click handler for make
				$(".dropdownItem", _dropdownEl).click(function(){
					_self.Close();
					var classes = $(this).attr("class").split(" ");
					for (i = 0; i < classes.length; i++) {
						if (classes[i].indexOf("selectorId") > -1) {
							var selectedId = classes[i].split("-")[1];
							_self.Click(selectedId, $(this).html());
							return;
						}
					}
					_self.Click("", "");
				});
				RefreshScroller();
			}
			
			_self.LoadData = function(arr, IdFieldName, ValueFieldName) {
				_data = [];
				IdFieldName = IdFieldName || 'Key';
				ValueFieldName = ValueFieldName || 'Value';
				for (i = 0; i < arr.length; i++) {
					_data[i] = {
											Key: arr[i][IdFieldName].toString().toLowerCase().replace(/ /g, "_"), 
											Value: arr[i][ValueFieldName].toString() 
										};
				}
				var resultingHTML = "";
				if (_options.defaultLabel) {
					resultingHTML = '<div class="dropdownItem">' + _options.defaultLabel + '</div>\n';
				}
				for (i = 0; i < _data.length; i++) {
					var tmpEl = _data[i];
					resultingHTML += '<div class="dropdownItem selectorId-' + tmpEl.Key + '">' + tmpEl.Value + '</div>\n';
				}
				_dropdownList.html(resultingHTML);
				
				_self.Refresh();
			}

			_self._isInitialized = true;
		}
		
		// helper functions
		function ScrollToTop() {
			var timer;
			if (_isSliding) {
				var currentValue = _dropdownScrollerArea.slider("value");
				currentValue += 15;
				_dropdownScrollerArea.slider("value", currentValue);
				if (currentValue < -_listHeight)
					currentValue = -_listHeight;
				if (currentValue > 0)
					currentValue = 0;
				_dropdownList.css("top", currentValue + "px");
				
				timer = setTimeout(function() {
										ScrollToTop();
									}, 
									_options.slideTime);
			} else {
				clearTimeout(timer);
			}
		}

		function ScrollToBottom() {
			var timer;
			if (_isSliding) {
				var currentValue = _dropdownScrollerArea.slider("value");
				currentValue -= 15;
				_dropdownScrollerArea.slider("value", currentValue);
				if (currentValue < -_listHeight)
					currentValue = -_listHeight;
				if (currentValue > 0)
					currentValue = 0;
				_dropdownList.css("top", currentValue + "px");
				
				timer = setTimeout(function() {
										ScrollToBottom();
									},
									_options.slideTime);
			} else {
				clearTimeout(timer);
			}
		}
		
		function RefreshScroller() {
				if (_options.hasScroll && _dropdownScrollerArea.slider) {
					//clear slider;
					_dropdownScrollerArea.slider("destroy");
					//remove button listeners;
					_dropdownButtonUp.unbind('click');
					_dropdownButtonUp.unbind('click');

					//slider initialization
					_listHeight = _dropdownList.height() - _dropdownEl.height();
					if (_listHeight > 0) {
						_dropdownScrollerArea.slider({
											animate: true, 
											orientation: "vertical", 
											min: -_listHeight, 
											max: 0,
											value: 0,
											slide: function(event, ui) {
														_dropdownList.css("top", ui.value + "px");
													}
						});
						_dropdownButtonUp.mouseup(function() {
							_isSliding = false;
						});
						_dropdownButtonUp.mousedown(function() {
							_isSliding = true;
							ScrollToTop();
						});

						_dropdownButtonDown.mouseup(function() {
							_isSliding = false;
						});
						_dropdownButtonDown.mousedown(function() {
							_isSliding = true;
							ScrollToBottom();
						});
					}
				}
		}
		
		function ReselectValue() {
			//console.log("Control:" + _self.selector + "; Selected Id=<" + _selectedId + ">, Value=<" + _selectedValue + ">, Index=<" + _selectedDataIndex + ">");
			$(".itemsSelected", _dropdownEl).removeClass("itemsSelected");
			if (_selectedId) {
				_selectedEl.html(_selectedValue);
				$(".selectorId-" + _selectedId, _dropdownEl).addClass("itemsSelected");
			} else {
				_selectedEl.html(_options.defaultLabel);
			}
		}
		
		return this;
	}
})(jQuery);

function SelectChkBox(id, idHidden) {
	var chkbox =  $(id);
	var src = chkbox.attr('src');
	var hidden = $('#' + idHidden);

	if (src.indexOf("chkbox_off") > 0) {
		chkbox.attr('src', src.replace('_off','_on'));
		hidden.val("Yes");
	} else if (src.indexOf("chkbox_on") > 0) {
		chkbox.attr('src', src.replace('_on','_off'));
		hidden.val("");
	}
}

function onfocus_search(ID) {
	var inputControl = document.getElementById(ID);
	inputControl.className = 'SerachTextEd';
	if (inputControl.value == 'Search eBizAutos')
		inputControl.value = "";
}
function onblur_search(ID) {
	var inputControl = document.getElementById(ID);
	if (inputControl.value == "") {
		inputControl.className = 'SerachText';
		inputControl.value = 'Search eBizAutos';
	}
}

function selectTab(tab) {
	$('.SelectedTab').addClass('Tab').removeClass('SelectedTab');
	$('#' + tab + 'Tab').addClass('SelectedTab').removeClass('Tab');
	$('.TabContent').hide();
	$('#' + tab).show();
}

function ShowPosition(i) {
	$('.ShowPosition' + i).hide();
	$('.HidePosition' + i).show();
	$('.Position' + i).show();
}
function HidePosition(i) {
	$('.HidePosition' + i).hide();
	$('.ShowPosition' + i).show();
	$('.Position' + i).hide();
}

function OpenWindowCenter(width, height) {
	_width = width;
	_height = height;
	_popupObject = $('#requestADemoContainer').modal({
		zIndex: 20000,
		close: true,
		positionStyle: 'absolute',
		containerCss: { width: _width, height: _height },
		containerId: 'requestADemoContainerOuter',
		position: [100, ]
	});

	$('#simplemodal-overlay').bind('click.simplemodal', function (e) {
		e.preventDefault();
		if (document.getElementById('_extIntViewContainer') != null)
			document.getElementById('_extIntViewContainer').style.visibility = 'visible';
		_popupObject.close();
	});
	$('.ClosePopup').bind('click.simplemodal', function (e) {
		e.preventDefault();
		_popupObject.close();
	});
	scroll(0, 0);
}

function SubmitRequestADemoForm(idForm, asmxUrl, pageTitle) {
	var message = "Please provide the following to complete this form:\n";
	var error = BaseValidate(idForm);

	if (error == "") {
		$.ajax({
			type: "POST", url: asmxUrl,
			data: "{myName: '" + $('#_myName').val() +
					"',emailAddress: '" + $('#_emailAddress').val() +
					"',phoneNumber: '" + $('#_phoneNumber').val() +
					"',dealershipName: '" + $('#_dealershipName').val() +
					"',dealershipWebsite: '" + $('#_dealershipWebsite').val() +
					"',pageTitle: '" + pageTitle + "' }",
			contentType: "application/json; charset=utf-8",
			dataType: "text",
			success: function (response) {
				var sendinfo = (typeof response) == 'string' ? eval('(' + response + ')') : response;
				if (sendinfo != "Server error") {
					$('#divRequestForm').css('display', 'none');
					$('#divRequestResponce').css('display', 'block');
					$('#email').html($('#_emailAddress').val());
				} else {
					alert("Server Error");
				}
			},
			failure: function (msg) {
				alert('Error occured with message: ' + msg);
			}
		});
	} else {
		alert(message + error);
	}
	return false;
}

function SubmitIntel() {
	if ($('#myName').val() == 'Name') {
		$('#myName').val('');
	}
	return SubmitForm('IntelligenceForm', false);
}

