function IsZipValid(value) {
	return /^\d{5}$/.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 (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 toggleArrow (el) {
	var homeLeftMenuDiv = document.getElementById ("homeLeftMenu");
	var aDivs = homeLeftMenuDiv.getElementsByTagName("div");
	var aSpans = homeLeftMenuDiv.getElementsByTagName("span");
	var arrowRight = el.getElementsByTagName("span")[0];
	var arrowDown = el.getElementsByTagName("span")[1];

	subitemsDiv = el.parentNode.nextSibling;
	//fix for FF where nextSibling of el is not div with subitems but "\n "
	if (!subitemsDiv.className)
		subitemsDiv = subitemsDiv.nextSibling;

	for (i=0; i < aDivs.length; i++) {
		if (aDivs[i].className.indexOf("subitemsLevel2") > -1 && aDivs[i] != subitemsDiv && aDivs[i].className.indexOf("hidden") < 0) {
			aDivs[i].className = aDivs[i].className + " hidden";
		}
	}
	for (i=0; i < aSpans.length; i++) {
		if (aSpans[i].className.indexOf("arrowDown") > -1 && aSpans[i] != arrowDown && aSpans[i].className.indexOf("hidden") <0) {
			aSpans[i].className = aSpans[i].className + " hidden";
			aSpans[i].previousSibling.className = aSpans[i].previousSibling.className.replace(" hidden", "");
		}
	}
	if (arrowRight.className.indexOf("hidden")<0) {
		arrowRight.className = arrowRight.className + " hidden";
		arrowDown.className = arrowDown.className.replace(" hidden", "");
		subitemsDiv.className = subitemsDiv.className.replace(" hidden", "");
	} else {
		arrowDown.className = arrowDown.className + " hidden";
		arrowRight.className = arrowRight.className.replace(" hidden", "");
		subitemsDiv.className = subitemsDiv.className + " hidden";
	}
}

function DealersLocatorSearch(){
	var location = document.getElementById("_location");
	var state = document.getElementById("_state");
	var brand = document.getElementById("_brand");
	var collision = document.getElementById("_collision");
	var newURL = window.location.protocol + "//" + window.location.host + window.location.pathname;
	var aURL  = newURL.split('/');
	var pageName = aURL[aURL.length-1];
	newURL = newURL.replace(pageName, "");
	newURL = newURL + "dealer-locator.aspx";
	if (location.value != '' || brand.value != '' || collision.checked ){
		var isFirst= true;
		newURL = newURL + "?";
		if (location.value != '') {
			isFirst = false;
			newURL = newURL + '_location=' + location.value;
			if (location.value.toLowerCase() == 'us' && state!= null && state.value != '') {
				newURL = newURL + '&_state=' + state.value;
			}
		}
		if (brand.value != '') {
			if (!isFirst) newURL = newURL + '&'; 
			isFirst = false;
			newURL = newURL + '_brand=' + brand.value;
		}
		if (collision.checked) {
			if (!isFirst) newURL = newURL + '&'; 
			isFirst = false;
			if (collision.checked) newURL = newURL + '_collision=true';
			else  newURL = newURL + '_collision=false';
		}
	}
	window.location = newURL;
}

function OnChangeLocation() {
	var location = document.getElementById("_location");
	var state = document.getElementById("_state");
	if (location.value.toLowerCase() == 'us') {
		state.style.display = "inline";
	} else {
		state.style.display = "none";
	}
}

function clearEmploymetForm() {
	document.getElementById('_dealershipName').value = '';
	document.getElementById('_firstName').value = '';
	document.getElementById('_middleName').value = '';
	document.getElementById('_lastName').value = '';
	document.getElementById('_streetAddress').value = '';
	document.getElementById('_city').value = '';
	document.getElementById('_state').value = '';
	document.getElementById('_zipCode').value = '';
	document.getElementById('_phone').value = '';
	document.getElementById('_mobilePhone').value = '';
	document.getElementById('_emailAddress').value = '';
	document.getElementById('_multiLine').value = '';
	document.getElementById('_position').value = '';
}

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 ValidateEmploymentForm(positionError) {
	var errorList = '';
	if (document.getElementById("_dealershipName").value.length == 0) {
		errorList += '- Please select dealership.\n';
	}

	if (document.getElementById("_firstName").value.length == 0) {
		errorList += '- Please provide your First Name.\n';
	}

	if (document.getElementById("_lastName").value.length == 0) {
		errorList += '- Please provide your Last Name.\n';
	}

	if (document.getElementById("_streetAddress").value.length == 0) {
		errorList += '- Please provide your Street Address.\n';
	}

	if (document.getElementById("_city").value.length == 0) {
		errorList += '- Please provide your City.\n';
	}

	if (document.getElementById("_state").value.length == 0) {
		errorList += '- Please provide your State.\n';
	}

	if (document.getElementById("_state").value.length == 0) {
		errorList += '- Please provide your State.\n';
	}

	if (document.getElementById("_zipCode").value.length == 0) {
		errorList += '- Please provide your Zip Code.\n';
	}

	if (checkEmailStr(document.getElementById("_emailAddress").value) == false) {
		errorList += '- Please provide valid Email.\n';
	}

	if (document.getElementById("_position").value.length == 0) {
		errorList += '- Please provide ' + positionError + '.\n';
	}

	if (errorList != '') {
		alert('You must enter a value in the following fields: \n' + errorList);
		return false;
	} else
		return true;
}

function OpenWindowCenter(url, name, width, height, scroll){
	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;
	popupWin = window.open(url, name, params);
	popupWin.focus();

}

function closeSelf() {
	window.open('','_parent','');
	window.opener = top;        
	window.close();
}

function flashLoader(flashMovie, flashVars, flashHeight, flashWidth, flashAlign, flashQuality, flashBGColor, flashID, flashScale) {
	var flashPluginSpace = 'http://www.macromedia.com/go/getflashplayer';
	document.write('<OBJECT type="application/x-shockwave-flash"  classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" 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 clearForm() {
	document.getElementById("_txtName").value = '';
	document.getElementById("_txtSendersEmail").value = '';
	document.getElementById("_txtEmail").value = '';
	document.getElementById("_txtCustomMessage").value = '';
	document.getElementById("_chkSendCopy").value = '';
	document.getElementById("ThankYouBox").style.display = "none";
	document.getElementById("RejectedMessageBox").style.display = "none";
}

function validateOnSubmit() {
	var errorList = '';
	if (document.getElementById("_txtName").value.length == 0) {
		errorList += '- Please provide your Name.\n';
	}

	if (checkEmailStr(document.getElementById("_txtSendersEmail").value) == false) {
		errorList += '- Please provide your Email address.\n';
	}

	if (checkEmailStr(document.getElementById("_txtEmail").value) == false) {
		errorList += '- Please provide target Email address .\n';
	}

	if (errorList != '') {
		alert('You must enter a value in the following fields: \n' + errorList);
		return false;
	} else
		return true;
}

function ShowHideDepartmentDetail(id) {
	var div = document.getElementById('DepartmentDetails'+id);
	var linkTxt = document.getElementById('DepartmentDetailsLink'+id);
	if (div.style.display == 'none') {
		div.style.display = 'block';
		linkTxt.innerHTML = 'Close';
	} else {
		div.style.display = 'none';
		linkTxt.innerHTML = 'Department Details';
	}
}

function SelectAllDealership() {
	$('.DealerShipTablTdHead input').attr('checked', $('#alldilership').attr('checked'));
}
function submitStep1(asmxUrl, form) {
	if ($('#txtZip').val() != '') {
		ValidateZipCodeAsync(asmxUrl, form);
	} else if ($('#txtState').val() != '') {
		return true;
	} else {
		alert('Please provide the following information:\n ZIP Code or State');
	}
	return false;
}

function submitStep2() {
	var chboxList = $('input:chekbox');
	var isSelected = false;

	for (i=0; i < chboxList.length; i++) {
		if (chboxList[i].checked && (chboxList[i].name == 'dealer_' || chboxList[i].name == 'hqdealer_')) {
			isSelected = true;
			break;
		}
	}
	if(isSelected)
		return true;
	else {
		alert('Select A Penske Location');
		return false;
	}
}

function submitStep3() {
	var chboxList = $('input:chekbox');
	var isSelected = false;

	for (i=0; i < chboxList.length; i++) {
			if(chboxList[i].checked) {
				isSelected = true;
				break;
			}
	}
	if(isSelected)
		return true;
	else {
		alert('Please Select A Department(s)');
		return false;
	}
}

function submitStep4(formId) {
	var errMsg = BaseValidate(formId);
	
	if (errMsg == '')
		//formObj.submit();
		return true;
	else
		alert('Please provide the following information:\n' + errMsg);
		return false;
}

function validateAttachment(idAttachVisible, idAttach) {
	var attachValue = $('#' + idAttach).val();
	var attach = $('#' + idAttach);
	var attachVisible = $('#' + idAttachVisible);
	var htmlStr = $('#'+idAttach+'Div').html();
	if (attachValue.lastIndexOf('.rtf') > 0 || attachValue.lastIndexOf('.txt') > 0) {
		attachVisible.attr('value',attachValue);
	} else {
		$('#'+idAttach+'Div').html(htmlStr);
		attachVisible.attr('value','');
		alert('Only the following file types may be uploaded: .rtf, .txt');
	}
}

function submitSiteFeedback() {
	var isSelected = false;
	var isDidSubmitNo = false;
	var errMsg = '';
	var searchEng = $('input[name="SearchEngineRadio"]');
	var socialMedia = $('input[name="SocialMediaRadio"]');
	var handheldDevice = $('input[name="HandheldDeviceRadio"]');
	var navigate = $('input[name="HowNavigateRadio"]');
	var didSubmit = $('input[name="DidSubmitRadio"]');
	var didSubmitNo = $('input[id="SubmitNo"]');
	var submitDifficulty = $('input[name="SubmitDifficultyRadio"]');
	var comparisonBetter = $('input[name="ComparisonRadio"]');
	var chkbox = $('#SiteFeedbackHowFind input:checkbox');

	for (i = 0; i < chkbox.length; i++) {
		if (chkbox[i].checked) {
			isSelected = true;
			break;
		}
	}
	if (!isSelected) {
		errMsg += 'You must make a selection in Question 1.\n';
	} else {
		if ($('#SearchEngineChk').attr('checked')) {
			isSelected = false;
			for (i = 0; i < searchEng.length; i++) {
				if (searchEng[i].checked) {
					isSelected = true;
					break;
				}
			}
			if (!isSelected)
				errMsg += 'You must make a selection in Question 1 "Search Engine".\n';
		}

		if ($('#DealershipChk').attr('checked') && ($('#dealerName').val() == "" || $('#dealerName').val() == "Dealership Name"))
			errMsg += 'You must enter in Question 1 "Dealership Recommendation".\n';

		if ($('#SocialMediaChk').attr('checked')) {
			isSelected = false;
			for (i = 0; i < socialMedia.length; i++) {
				if (socialMedia[i].checked) {
					isSelected = true;
					break;
				}
			}
			if (!isSelected)
				errMsg += 'You must make a selection in Question 1 "Social Media Network".\n';
		}
	}
	isSelected = false;
	for (i = 0; i < handheldDevice.length; i++) {
		if (handheldDevice[i].checked) {
			isSelected = true;
			break;
		}
	}
	if (!isSelected)
		errMsg += 'You must make a selection in Question 2.\n';

	isSelected = false;
	for (i = 0; i < navigate.length; i++) {
		if (navigate[i].checked) {
			isSelected = true;
			break;
		}
	}
	if (!isSelected)
		errMsg += 'You must make a selection in Question 3.\n';

	isSelected = false;
	for (i = 0; i < didSubmit.length; i++) {
		if (didSubmit[i].checked) {
			isSelected = true;
			break;
		}
	}
	if (!isSelected)
		errMsg += 'You must make a selection in Question 4.\n';

	for (i = 0; i < didSubmitNo.length; i++) {
		if (didSubmitNo[i].checked) {
			isDidSubmitNo = true;
			break;
		}
	}

	isSelected = false;
	for (i = 0; i < submitDifficulty.length; i++) {
		if (submitDifficulty[i].checked) {
			isSelected = true;
			break;
		}
	}
	if (!isSelected && !isDidSubmitNo)
		errMsg += 'You must make a selection in Question 4."easy yes/no".\n';

	if (!checkComments('FavoriteComment')) {
		errMsg += 'In Question 5 HTML and XML prohibited. Only plain text allowed.\n';
	}

	if (!checkComments('ImproveComment')) {
		errMsg += 'In Question 6 HTML and XML prohibited. Only plain text allowed.\n';
	}

	isSelected = false;
	for (i = 0; i < comparisonBetter.length; i++) {
		if (comparisonBetter[i].checked) {
			isSelected = true;
			break;
		}
	}
	if (!isSelected)
		errMsg += 'You must make a selection in Question 7.\n';

	if (errMsg != '') {
		alert(errMsg);
		return false;
	} else {
		return true;
	}
}

function selectChk(Name, id) {
	var chkbox = $('input[name='+ Name +']');
	var chk = $('#'+id);

	 if (!chk.attr('checked')) {
		for (i=0; i < chkbox.length; i++) {
			chkbox[i].checked = false;
		}
	}
}

function selectChk2(idChk, idInput) {
	var chkbox = $('#'+idChk);
	var input = $('#'+idInput);

	 if (!chkbox.attr('checked')) {
		input.attr('value','Dealership Name');
		input.css('color','#999999');
	}
}

function selectRadio(id, idChk) {
	var radio = $('#' + id);
	var chk = $('#' + idChk);
	
	if (radio.attr('checked')) {
		if (!chk.attr('checked')) {
			chk.attr('checked', 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 ValidateZipCodeAsync(asmxUrl, form) {
	var zipCode = $('#txtZip');

	zipCodeRegex = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
	if (zipCode == null || !zipCodeRegex.test(zipCode.val())) {
		alert('Please enter a valid ZIP code');
		return false;
	} else {
		$.ajax({
			type: "POST",
			url: asmxUrl,
			data:	"{zip: '"+ zipCode.val() + "' }",
			contentType: "application/json",
			dataType: "text",
			success: function(response) {
				var sendinfo = (typeof response) == 'string' ? eval('(' + response + ')') : response;
				if (sendinfo != "Ok"){
					alert(sendinfo);
				} else {
					form.submit();
				}
			},
			failure: function(msg) {
				alert(msg);
			}
		});
	}
}

