$(document).ready( function() {	
	var form = $('form#vdw4_metaSearch');
	if ( form.length > 0 ){
		//found metaSearch form, continue
		
		//get the elements we need to work on
		var inputBox = $('input#metasearch', this);
		var searchButton = $('button#vwd4_submit1', this)
		
		var defaultText = 'Enter zip code or keyword'
		
		//set the input box to have 'Enter zip or keyword...' as text, greyed out
		if (inputBox.val() == ''){
			inputBox.val(defaultText).css('color', '#CCC');	
		}
		inputBox
			.focus( function(){
				//onFocus, empty box and revert css color
				var thisBox = $(this);
				if (thisBox.val() == defaultText){
					thisBox.val('').css('color', '');				
				}
			})
			.blur( function(){
				//onBlur, revert to defaultText if empty
				var thisBox = $(this);
				if (thisBox.val() == ''){
					thisBox.val(defaultText).css('color', '#CCC');				
				}
			})
			
		form.submit( function(event){
			//form has been submitted, check for zip
			
			var inputBox = $('input#metasearch', this);
			var regEx = new RegExp(/\d{5}|\d{5}\-\d{4}/)
			//test inputBox string with regEx;
			if (regEx.test(inputBox.val())){
				var thisEvent = event;
				event.preventDefault();
				$.getJSON(
					'https://blogs.vw.com/secure/cms/lib/returnDealerJSON.php?callback=?',
					{"zipCode": inputBox.val().match(regEx)},
					function(data) {
						//alert(data.foundDealer);
						console.log(data.foundDealer);
						if (data.foundDealer)
						{
							window.location.href='http://www.vw.com/portal/en/dealers#search=' + inputBox.val().match(regEx);
							//window.location.href='http://dealers.vw.com/dcc/dealerSearch.html#search=' + inputBox.val().match(regEx);
						}
						else
						{
							window.location.href='http://www.vw.com/en/search.html?searchText=' + inputBox.val();			
						}
					}
				);
			}
		})
	}
	
});

