$(function () {
	//--IE6 Warning-------------------------------------------------------------------------------
		if ($('#rootIE6').html() != null) {						
			$('body').append('<div id="IEwarning"><p>You are using an outdated browser. For the best experience using this site, please upgrade to a modern web browser.</p></div>');
			
			$('#IEwarning').css({
				borderBottom: "1px solid #f7941d",
				background: "#feefda",
				textAlign: "center",
				position: "absolute",
				top: 0,
				left: 0,
				zIndex: 100,
				display: "none",
				font: "bold 12px arial, sans-serif",
				padding: "3px",
				width: $('body').width()
			}).slideDown("slow");
		}
	
	
	
	//--Error messages used in form validation-------------------------------------------------------------------------------
		var validationErrorMessage = {};
			validationErrorMessage['email'] = 'Invalid email address';	
			validationErrorMessage['phone'] = 'XXX-XXX-XXXX';
			validationErrorMessage['phone2'] = 'XXX-XXX-XXXX';
			validationErrorMessage['postal_code'] = 'Invalid postal code';
	
	
	
	//--IE select width fix--------------------------------------------------------------------------------------------------
		function ieSelectWidthFix() {
			if (jQuery.browser.msie) {
				$('select').each(function () {
					$(this).data("originalWidth", $(this).css('width'));
				});
				
				$('select').mouseenter(function () {
					$(this).css('width', "auto");
					$(this).data("resizedWidth", $(this).attr('offsetWidth'));
					
					if (parseInt($(this).data("resizedWidth")) < parseInt($(this).data("originalWidth").replace(/px/, ""))) {
						$(this).css('width', $(this).data("originalWidth"));		
					} else {
						$(this).addClass('expanded');	
					}
				});
				
				$('select').change(function () {
					$(this).css('width', $(this).data("originalWidth"));
					$(this).removeClass('expanded');
				});
				
				$(':input').focus(function () {
					if ($(this).attr('class') != 'expanded') {
						$('.expanded').each(function () {
							$(this).css('width', $(this).data("originalWidth"));
							$(this).removeClass('expanded');
						});
					}
				});
			}
		}
	
	
	
	//--Validation checks--------------------------------------------------------------------------------------------------------  
		function isRequired(formField) {
			switch ($(formField).attr('type')) {
				case 'text':
				case 'textarea':
				case 'select-one':
				case 'password':
					if ($(formField).val()) {
						return true;
					}
				return false;
			}
		}
		
		function isPattern(formField, pattern) {
			var regExp = new RegExp("^" + pattern + "$");
			
			var correct = regExp.test($(formField).val());
	
			return correct;
		}
		
		function isValidEmail(formField) { return isPattern(formField, "[a-zA-Z0-9._+%-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$"); }
		
		function isValidPhone(formField) { return isPattern(formField, "^[0-9]{3}-[0-9]{3}-[0-9]{4}$"); }
		
		function isValidZip(formField) { return isPattern(formField, "^[0-9]{5}(-[0-9]{4})?$"); }
		
		function isValidPostalCode(formField) { return isPattern(formField, "^[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1}[0-9]{1}[A-Za-z]{1} *[0-9]{1}[A-Za-z]{1}[0-9]{1}$"); }
	//-----------------------------------------------------------------------------------------------------END Validation checks



	//--Form validation---------------------------------------------------------------------------------------------------------
		function removeError() {
			if (!$(this).data('errorMessage')) return;
			
			$(this).removeClass('errorMessage');	
			$(this).next().remove();
			$(this).removeData('errorMessage');
		}
		
		function validate (step) {
			var validForm = true;
			
			if (step == "stepOne") {
				var formFields = $('#stepOne :input');
			} else {
				var formFields = $(':input');	
			}
			
			for (var i = 0; i < formFields.length; i++) {
				var validation = $(formFields[i]).attr('validation');
				var fieldID = $(formFields[i]).attr('id');
				var OK, requiredFirst = true;
				
				if (!validation) {
					switch (fieldID) {
						case "phone":
						case "phone2":
						case "email":
							if ($(formFields[i]).val() == "") {
								continue;
							}
						break;
						
						default:
							continue;
						break;
					}
				}
				
				switch (fieldID) {
					case "postal_code":
						OK = isRequired(formFields[i]);
						
						if (OK) { 
							if ($('#country').length) {
								switch ($('#country').val()) {
									case "Canada":
										OK = isValidPostalCode(formFields[i]);
									break;
									
									case "USA":
										OK = isValidZip(formFields[i]);
									break;
								}
							} else {
								OK = isValidZip(formFields[i]);	
							}
							
							requiredFirst = false;					
						}
						break;
						
					case "email":
						OK = isRequired(formFields[i]);
						if (OK) { 
							OK = isValidEmail(formFields[i]);
							requiredFirst = false;
						}
						break;
						
					case "phone":
					case "phone2":
						OK = isRequired(formFields[i]);
						if (OK) { 
							OK = isValidPhone(formFields[i]);
							requiredFirst = false;
						}
						break;
						
					default:
						OK = isRequired(formFields[i]);
						break;
				};
				
				if (!OK) {
					var errorMessage = "Required"; 
					
					if (!requiredFirst) {
						errorMessage =  validationErrorMessage[fieldID] || "";
					}
					
					writeError(formFields[i], errorMessage);
					
					validForm = false;
				}
				
			}
			
			return validForm;
		}
		
		function writeError(formField, message) {
			var fieldID = $(formField).attr('id');
			var fieldWidth = $(formField).attr('offsetWidth');
			var fieldHeight = $(formField).attr('offsetHeight');
			
			$(formField).addClass('errorMessage');
							
			$(formField).focus(removeError);
			
			if ($(formField).data('errorMessage')) return;
					
			$(formField).parent().append('<label style="width:'+fieldWidth+'px; height: '+fieldHeight+'px;" class="errorMessage" for="'+fieldID+'" htmlFor="'+fieldID+'">'+message+'</label>');
			
			$(formField).data('errorMessage', message);
		}
	//-------------------------------------------------------------------------------------------------------END Form validation
	
	
	
	
	
	
	//--Page setup-------------------------------------------------------------------------------------------------------------	
	//-----------------------------------------------------------------------------------------------------------END Page setup
	
	
	
	//--Form setup-------------------------------------------------------------------------------------------------------------
			$('#btn_Submit').click(function () {
				var validForm = validate();
				
				if ( validForm ) {
					$('#requestForm').submit();
				}								 
			});
			
			$('#btn_Login').click(function () {
				var validForm = validate();
				
				if ( validForm ) {
					$.getJSON('/global/cdm-server.php?path=http://sitebin.datamark.com/index.php/services/lead_abyss/' + $('#prospect_code').val().toUpperCase() + '/prospects', function (json) {
					if (json.ProspectCode != null) {
						if (json.UserName == $('#username').val().toLowerCase()) {
							$('#loginForm').submit();
						} else {
							$('#username').addClass('errorMessage');
											
							$('#username').focus(removeError);
							
							if ( $('#username').data('errorMessage') ) return;
									
							$('#username').parent().append('<label style="width:'+$('#username').attr('offsetWidth')+'px; height: '+$('#username').attr('offsetHeight')+'px;" class="errorMessage" for="username" htmlFor="username">Username does not match</label>');
							
							$('#username').data('errorMessage', 'No Username match');		
						}
					} else {
						$('#prospect_code').addClass('errorMessage');
										
						$('#prospect_code').focus(removeError);
						
						if ( $('#prospect_code').data('errorMessage') ) return;
								
						$('#prospect_code').parent().append('<label style="width:'+$('#prospect_code').attr('offsetWidth')+'px; height: '+$('#prospect_code').attr('offsetHeight')+'px;" class="errorMessage" for="prospect_code" htmlFor="prospect_code">Invalid Code</label>');
						
						$('#prospect_code').data('errorMessage', 'Invalid Code');	
					}
				});
				}								 
			});
			
			$('#forgot').click(function () {
				$('#loginForm').submit();	
				return false;
			});
			
			$.get('_Includes/code_retrieve.php', function (data) {
				$.getJSON('/global/cdm-server.php?path=http://sitebin.datamark.com/index.php/services/lead_abyss/' + data + '/prospects', function (json) {
					$('#first_name').val(json.FirstName);
					$('#last_name').val(json.LastName);
					$('#address').val(json.Address1);
					$('#city').val(json.City);
					$('#state').val(json.State);
					$('#postal_code').val(json.PostalCode);
					$('#phone').val(json.Phone);
					$('#prospect_code').val(json.ProspectCode);
					$('#job_number').val(json.DMJobNumber);
				});				
			});
		
		
		ieSelectWidthFix();	
	//-------------------------------------------------------------------------------------------------------------END Form setup
});
