
var Common = {
	init: function(settings) {
		
		// Automatically clear an input value when focus in
		$("input").focusin(function(){
			if ($(this).val().toUpperCase()==$(this).attr('name').toUpperCase()
					|| 
				$(this).val().toUpperCase()==$(this).attr('name').toUpperCase()+'*'
					||
				$(this).val().toUpperCase().indexOf($(this).attr('name').toUpperCase()) != -1
					||
				$(this).val().toUpperCase().replace(" ", "_").indexOf($(this).attr('name').toUpperCase()) != -1){
				$(this).val('');
			}
		});
		
		$("#quoteFirstname").focusout(function(){
			if ($(this).val()==''){
				$(this).val('First Name');
			}
		});
		$("#quoteLastname").focusout(function(){
			if ($(this).val()==''){
				$(this).val('Last Name');
			}
		});
		
		// Behavior of fancy select dropdowns
		$('.fancyselect-select').change(function(event){
			if ($(this).attr('name') == 'radius' && $(this).val()!='Search Radius'){
				$(this).siblings('.fancyselect-fakevalue').html($(this).val()+" miles");
			}
			else{
				$(this).siblings('.fancyselect-fakevalue').html($(this).val());
			}
		});
		if (navigator.appVersion.indexOf('MSIE 6') != -1) {
			$('.fancyselect-select').each(function(event){
				$(this).children().first().html($(this).children().val());
			});
		}
		
		// Behavior of fancy select dropdowns 
		$('.fancyselect-light-select').change(function(event){
			$(this).siblings('.fancyselect-light-fakevalue').html($(this).val());
		});
		if (navigator.appVersion.indexOf('MSIE 6') != -1) {
			$('.fancyselect-light-select').each(function(event){
				$(this).children().first().html($(this).children().val());
			});
		}
		
		// Change store CSS popup
		$('.tires-search-mystorebox-edit a').click(function(){
			$('#changeStoreLocationPopup').slideDown();
		});
		$('#changeStoreLocationPopup .close').css('cursor','pointer').click(function(){
			$('#changeStoreLocationPopup').slideUp();
		});
		
		// Change store CSS popup
		$('#emailQuoteButton').click(function(){
			$('#emailQuotePopup').slideDown();
		});
		$('#emailQuotePopup .close').css('cursor','pointer').click(function(){
			$('#emailQuotePopup').slideUp(function () {
				$('#emailQuotePopup-in1').show();
				$('#emailQuotePopup-in2').hide();
		    });
		});
		$('#emailQuotePopup-in1 .submit').click(function(){
			$('#emailQuotePopup-in1').fadeOut();
			$('#emailQuotePopup-in2').fadeIn();
		});
		
		// Cross browser underline on hover
		$('.underlineOnHover').css('cursor','pointer').hover(
				function(){
					$(this).css('text-decoration','underline');
					},
				function(){
					$(this).css('text-decoration','none');
					}
			);
		
		// Clear the red error border from any input field when its value changes
		$('input').change(function() {
			$(this).css('outline','none');
		});
		
		// Clear the red error border from any input field when its value changes
		$('.fancyselect-select').change(function() {
			$(this).parent().css('border','1px solid #9C9C92');
		});
		// Same with light select
		$('.fancyselect-light-select').change(function() {
			$(this).parent().css('border','1px solid #DFDFDF');
		});
		
		// Dropdowns population
		if ($('#fancyselect-div-year').length) {
			$.post('/_ajax_formFields.php', {purpose: 'years'}, function(years) {
				$('#fancyselect-div-year select').html(years);
				
				//$('#fancyselect-div-year select option').click(function() {
				$('#fancyselect-div-year select').change(function() {
					$('#fancyselect-div-submodel select').html('<option selected="selected" value="Submodel">Select One:</option>');
					$('#fancyselect-div-submodel select').val('Submodel');
					$('#fancyselect-div-submodel .fancyselect-fakevalue').html('Submodel').css('color','#b9b9b9');

					$('#fancyselect-div-model select').html('<option selected="selected" value="Model">Select One:</option>');
					$('#fancyselect-div-model select').val('Model');
					$('#fancyselect-div-model .fancyselect-fakevalue').html('Model').css('color','#b9b9b9');
					
					$('#fancyselect-div-model select').html('<option selected="selected" value="Make">Select One:</option>');
					$('#fancyselect-div-make select').val('Make');
					$('#fancyselect-div-make .fancyselect-fakevalue').html('Make').css('color','#b9b9b9');
					
					$.post('/_ajax_formFields.php', {purpose: 'makes', year: $('#fancyselect-div-year select').val()}, function(makes) {
						$('#fancyselect-div-make select').html(makes);
						$('#fancyselect-div-make .fancyselect-fakevalue').css('color','#333333');

						//$('#fancyselect-div-make select option').click(function() {
						$('#fancyselect-div-make select').change(function() {
							$('#fancyselect-div-submodel select').html('<option selected="selected" value="Submodel">Select One:</option>');
							$('#fancyselect-div-submodel select').val('Submodel');
							$('#fancyselect-div-submodel .fancyselect-fakevalue').html('Submodel').css('color','#b9b9b9');
							
							$('#fancyselect-div-model select').html('<option selected="selected" value="Model">Select One:</option>');
							$('#fancyselect-div-model select').val('Model');
							$('#fancyselect-div-model .fancyselect-fakevalue').html('Model').css('color','#b9b9b9');
							$.post('/_ajax_formFields.php', {purpose: 'models', year: $('#fancyselect-div-year select').val(), make: $('#fancyselect-div-make select').val()}, function(models) {
								$('#fancyselect-div-model select').html(models);
								$('#fancyselect-div-model .fancyselect-fakevalue').css('color','#333333');
								
								//$('#fancyselect-div-model select option').click(function() {
								$('#fancyselect-div-model select').change(function() {
									$('#fancyselect-div-submodel select').html('<option selected="selected" value="Submodel">Select One:</option>');
									$('#fancyselect-div-submodel select').val('Submodel');
									$('#fancyselect-div-submodel .fancyselect-fakevalue').html('Submodel').css('color','#b9b9b9');
									
									$.post('/_ajax_formFields.php', {purpose: 'submodels', year: $('#fancyselect-div-year select').val(), make: $('#fancyselect-div-make select').val(), model: $('#fancyselect-div-model select').val()}, function(submodels) {
										$('#fancyselect-div-submodel select').html(submodels);
										$('#fancyselect-div-submodel .fancyselect-fakevalue').css('color','#333333');
									});	
								});
							});						
						});
					});
				});			
			});	
		}
		if ($('#fancyselect-div-cross').length) {
			$.post('/_ajax_formFields.php', {purpose: 'cross'}, function(cross) {
				$('#fancyselect-div-cross select').html(cross);
				
				//$('#fancyselect-div-cross select option').click(function() {
				$('#fancyselect-div-cross select').change(function() {
					$('#fancyselect-div-rim select').html('<option selected="selected" value="Rim Diameter">Select One:</option>');
					$('#fancyselect-div-rim select').val('Rim Diameter');
					$('#fancyselect-div-rim .fancyselect-fakevalue').html('Rim Diameter').css('color','#b9b9b9');
					$('#fancyselect-div-aspect select').html('<option selected="selected" value="Aspect Ratio">Select One:</option>');
					$('#fancyselect-div-aspect select').val('Aspect Ratio');
					$('#fancyselect-div-aspect .fancyselect-fakevalue').html('Aspect Ratio').css('color','#b9b9b9');
					
					$.post('/_ajax_formFields.php', {purpose: 'aspects', cross: $('#fancyselect-div-cross select').val()}, function(aspects) {
						$('#fancyselect-div-aspect select').html(aspects);
						$('#fancyselect-div-aspect .fancyselect-fakevalue').css('color','#333333');

						//$('#fancyselect-div-aspect select option').click(function() {
						$('#fancyselect-div-aspect select').change(function() {
							$('#fancyselect-div-rim select').html('<option selected="selected" value="Rim Diameter">Select One:</option>');
							$('#fancyselect-div-rim select').val('Rim Diameter');
							$('#fancyselect-div-rim .fancyselect-fakevalue').html('Rim Diameter').css('color','#b9b9b9');
							$.post('/_ajax_formFields.php', {purpose: 'rims', cross: $('#fancyselect-div-cross select').val(), aspect: $('#fancyselect-div-aspect select').val()}, function(rims) {
								$('#fancyselect-div-rim select').html(rims);
								$('#fancyselect-div-rim .fancyselect-fakevalue').css('color','#333333');
							});						
						});
					});
				});			
			});	
		}
		
		
		// Submit a vehicle search - validation (shared)
		$('.submitVehicleSearch').click(function() {
			$form = $(this).closest('form');
			$errorMessageObject = $form.find('.errorMessage');
			if ($form.find('input[name="zip"]').size()>0){
				var hasZipAndRadius = true;
			}
			else
				var hasZipAndRadius = false;
			
			if (hasZipAndRadius){
				$zipObject = $form.find('input[name="zip"]');
				$zipValue = $zipObject.attr('value');
				$radiusObject = $form.find('.fancyselect-select[name="radius"]');
				$radiusValue = $radiusObject.val();
			}
			
			$yearObject = $form.find('.fancyselect-select[name="year"]');
			$yearValue = $yearObject.val();
			$makeObject = $form.find('.fancyselect-select[name="make"]');
			$makeValue = $makeObject.val();
			$modelObject = $form.find('.fancyselect-select[name="model"]');
			$modelValue = $modelObject.val();
			$submodelObject = $form.find('.fancyselect-select[name="submodel"]');
			$submodelValue = $submodelObject.val();
			
			$vehicleSearchLatitudeObject = $form.find('.vehicleSearchLatitude');
			$vehicleSearchLongitudeObject = $form.find('.vehicleSearchLongitude');
			
			var re5digit=/^\d{5}$/;
			if ((hasZipAndRadius && $zipValue.search(re5digit)==-1) || $submodelValue=="Submodel" || (hasZipAndRadius && $radiusValue=="Search Radius")){ 
				if (hasZipAndRadius && $radiusValue=="Search Radius")
					$radiusObject.parent().css('border','1px solid red');
				if ($yearValue=="Year")
					$yearObject.parent().css('border','1px solid red');
				if ($makeValue=="Make")
					$makeObject.parent().css('border','1px solid red');
				if ($modelValue=="Model")
					$modelObject.parent().css('border','1px solid red');
				if ($submodelValue=="Submodel")
					$submodelObject.parent().css('border','1px solid red');
				if (hasZipAndRadius && $zipValue.search(re5digit)==-1){ 
					$zipObject.css('outline','1px solid red');
					$errorMessageObject.text('Please provide a valid zipcode');
				}
				else{
					$errorMessageObject.text('Please fill in all highlighted fields');
				}
				return false;
			}
			
			if (!hasZipAndRadius)
				$form.submit();
			else{
				var geocoder = new google.maps.Geocoder();
			    geocoder.geocode({ 'address': $zipValue }, function (results, status) {
			    	if (status == google.maps.GeocoderStatus.OK) {
			    		$vehicleSearchLatitudeObject.val(results[0].geometry.location.lat());
			    		$vehicleSearchLongitudeObject.val(results[0].geometry.location.lng());
			            $form.submit();
			        }
			        else {
			        	$zipObject.css('outline','1px solid red');
			        	$errorMessageObject.text('Please provide a valid zipcode');
			        	return false;
			        }
			    });
			}
			
		});
		
		$('input').keypress(function(event) {
		     var key;     
		     if(window.event)
		          key = window.event.keyCode; //IE
		     else
		          key = event.which; //firefox   
		     if(key == 13){
		    	 $form = $(this).closest('form');
		    	 // Exception for the get-quote form where we want enter to do nothing
		    	 if ($form.attr('id')=="getQuote-mainForm")
		    		 return true;
		    	 $jsSubmitButton = $form.find('.submit').first();
		    	 if ($jsSubmitButton.size()==1){
		    		 $jsSubmitButton.click();
		    	 }
		    	 else{
		    		 $form.submit();
		    	 }
		         return false;
		     }
		     else
		         return true;
		});

		
		$('.store-search-sumbit').click(function(event){
			$form = $(this).closest('form');
			
			$zipObject = $form.find('input[name="zip"]');
			$zipValue = $zipObject.attr('value');
			
			$radiusObject = $form.find('select[name="radius"]');
			$radiusValue = $radiusObject.val();
			
			$vehicleSearchLatitudeObject = $form.find('.vehicleSearchLatitude');
			$vehicleSearchLongitudeObject = $form.find('.vehicleSearchLongitude');
			
			var re5digit=/^\d{5}$/;
			if ($zipValue.search(re5digit)==-1 || $radiusValue=="" || $radiusValue=="Search Radius"){
				alert('Please complete the fields');
				return false;
			}
				
			var geocoder = new google.maps.Geocoder();
		    geocoder.geocode({ 'address': $zipValue }, function (results, status) {
		    	if (status == google.maps.GeocoderStatus.OK) {
		    		$vehicleSearchLatitudeObject.val(results[0].geometry.location.lat());
		    		$vehicleSearchLongitudeObject.val(results[0].geometry.location.lng());
		    		
		    		//Save the driving directions partially compiled values
		    		$('#hiddenDrivingDirectionsAddress').val($('#directions-address').val());
		    		$('#hiddenDrivingDirectionsCity').val($('#directions-city').val());
		    		$('#hiddenDrivingDirectionsState').val($('#directions-state').val());
		    		$('#hiddenDrivingDirectionsZip').val($('#directions-zip').val());
		    		
		            $form.submit();
		        }
		        else {
		        	alert('Please provide a valid zipcode');
		        	return false;
		        }
		    });
		});
		
		
		// Submit a tire size search - validation (shared)
		$('.submitSizeSearch').click(function() {
			$form = $(this).closest('form');
			$errorMessageObject = $form.find('.errorMessage');
			if ($form.find('input[name="zip"]').size()>0){
				var hasZipAndRadius = true;
			}
			else
				var hasZipAndRadius = false;
			
			if (hasZipAndRadius){
				$zipObject = $form.find('input[name="zip"]');
				$zipValue = $zipObject.attr('value');
				$radiusObject = $form.find('.fancyselect-select[name="radius"]');
				$radiusValue = $radiusObject.val();
			}
			
			$zipObject = $form.find('input[name="zip"]');
			$zipValue = $zipObject.attr('value');
			
			$radiusObject = $form.find('.fancyselect-select[name="radius"]');
			$radiusValue = $radiusObject.val();
			$crossObject = $form.find('.fancyselect-select[name="cross"]');
			$crossValue = $crossObject.val();
			$aspectObject = $form.find('.fancyselect-select[name="aspect"]');
			$aspectValue = $aspectObject.val();
			$rimObject = $form.find('.fancyselect-select[name="rim"]');
			$rimValue = $rimObject.val();
			
			$vehicleSearchLatitudeObject = $form.find('.sizeSearchLatitude');
			$vehicleSearchLongitudeObject = $form.find('.sizeSearchLongitude');

			var re5digit=/^\d{5}$/;
			if ((hasZipAndRadius && $zipValue.search(re5digit)==-1) || $rimValue=="Rim Diameter" || (hasZipAndRadius && $radiusValue=="Search Radius")){ 
				if (hasZipAndRadius && $radiusValue=="Search Radius")
					$radiusObject.parent().css('border','1px solid red');
				if ($crossValue=="Cross Section")
					$crossObject.parent().css('border','1px solid red');
				if ($aspectValue=="Aspect Ratio")
					$aspectObject.parent().css('border','1px solid red');
				if ($rimValue=="Rim Diameter")
					$rimObject.parent().css('border','1px solid red');
				if (hasZipAndRadius && $zipValue.search(re5digit)==-1){ 
					$zipObject.css('outline','1px solid red');
					$errorMessageObject.text('Please provide a valid zipcode');
				}
				else{
					$errorMessageObject.text('Please fill in all highlighted fields');
				}
				return false;
			}
				
			if (!hasZipAndRadius)
				$form.submit();
			else{
				var geocoder = new google.maps.Geocoder();
			    geocoder.geocode({ 'address': $zipValue }, function (results, status) {
			    	if (status == google.maps.GeocoderStatus.OK) {
			    		$vehicleSearchLatitudeObject.val(results[0].geometry.location.lat());
			    		$vehicleSearchLongitudeObject.val(results[0].geometry.location.lng());
			    			            
			            $form.submit();
			        }
			        else {
			        	$zipObject.css('outline','1px solid red');
			        	$errorMessageObject.text('Please provide a valid zipcode');
			        	return false;
			        }
			    });
			}
		});
		
		

		
		//******************* Part 1 **********************//
		$('#home-splash-images').tabs({fx:{opacity:'toggle'}});
		$('#home-banner-left').tabs({fx:{opacity:'toggle'}});
		$('#home-banner-left').tabs();
		$('#extrainfo').extrainfo();
		$('#home-splash-images').tabs('rotate',12000);
		$('#homebanner-originalequipment-left').click(function(event){
			$('#homebanner-originalequipment-right').hide();
			event.preventDefault();
			$('#homebanner-originalequipment-right').show().css({zIndex:5});
		});
		$('#homebanner-originalequipment-right').click(function(event){
			event.preventDefault();
			$(this).hide();
		});
		
		
		//******************* Part 2 **********************//
		var store_search_zip = $('#store_search_zip');
		var store_search_radius = $('#store_search_radius');

		if(store_search_zip.val() != ''){
			store_search_zip.parent('span').removeClass('default');
		}
		if(store_search_radius.val()!=''){
			store_search_radius.parent('span#image-container').removeClass('default');
			store_search_radius.siblings('.fakevalue').text(store_search_radius.val() + ' miles')
		}	

		store_search_zip.focus(function(){
			if ($(this).val()==''){
				$(this).parent('span').removeClass('default');
			}	
		}).blur(function(){
			if ($(this).val()==''){
				$(this).parent('span').addClass('default');
			}else{
			
			}
		}).keyup(function(){
			if ($(this).val()!=''){
				$(this).parent('span').removeClass('default');
			}
		});
		//background-position:0 -176px; 0 -142px default
		store_search_radius.change(function(){
			if($(this).val() == ''){
				$(this).parent().addClass('default');
				$(this).siblings('.fakevalue').text('')
			}else{
				$(this).parent().removeClass('default');
				$(this).siblings('.fakevalue').text($(this).val() + ' miles')
			}
		});
		
		
		//******************* Part 3 **********************//
		$('#videothumbnail1').click(function(event){
			event.preventDefault();
			
			if ($(this).hasClass('videothumbnail-selected')) {
				var player = $('#home-splash-video-replacement1');
				player[0].sendEvent('PLAY','true');
			} else {
				var so = new SWFObject('/flash/player.swf','home-splash-video-replacement1','376','231','9.0.124');
				so.addParam('allowfullscreen','true');
				so.addParam('allowscriptaccess','always');
				so.addVariable('image','/flash/wine_tasting_posterframe.jpg');
				so.addVariable('file','http://www.youtube.com/v/uY_X04SVC9Q');
				so.addVariable('autostart','true');
				so.write('home-splash-video-replacement');
				$('#videothumbnail1').addClass('videothumbnail-selected');
				$('#videothumbnail2').removeClass('videothumbnail-selected');
			}
		});
		
		$('#videothumbnail2').click(function(event){
			event.preventDefault();

			if ($(this).hasClass('videothumbnail-selected')) {
				var player = $('#home-splash-video-replacement2');
				player[0].sendEvent('PLAY','true');
			} else {
				var so = new SWFObject('/flash/player.swf','home-splash-video-replacement2','376','231','9.0.124');
				so.addParam('allowfullscreen','true');
				so.addParam('allowscriptaccess','always');
				so.addVariable('image','/flash/video1_posterframe.jpg');
				so.addVariable('file','http://www.youtube.com/v/K8nAe9sfwzU');
				so.addVariable('autostart','true');
				so.write('home-splash-video-replacement');
				$('#videothumbnail2').addClass('videothumbnail-selected');
				$('#videothumbnail1').removeClass('videothumbnail-selected');
			}
		});
		
		//******************* Part 4 **********************//
		$('#makes_scroller').serialScroll({
			items:'div.swipe',
			duration:150,
			force:true,
			axis:'y',
			easing:'linear',
			lazy:false,
			interval:3500,
			step:1,
			onBefore:function(a,b,c,d,pos){
				$('#what_rolling_buttons_bg').children('.current').removeClass('current').end().children('.what_rolling_button:eq('+pos+')').addClass('current');
				//currentPos = pos;
			}
		}).trigger('start');

		$('#what_rolling_button_1').click(function() { $('#makes_scroller').trigger('goto', [0]); });
		$('#what_rolling_button_2').click(function() { $('#makes_scroller').trigger('goto', [1]); });
		$('#what_rolling_button_3').click(function() { $('#makes_scroller').trigger('goto', [2]); });
		$('#what_rolling_button_4').click(function() { $('#makes_scroller').trigger('goto', [3]); });
		$('#what_rolling_button_5').click(function() { $('#makes_scroller').trigger('goto', [4]); });
		$('#what_rolling_button_6').click(function() { $('#makes_scroller').trigger('goto', [5]); });
		$('#what_rolling_button_7').click(function() { $('#makes_scroller').trigger('goto', [6]); });
		$('#what_rolling_button_8').click(function() { $('#makes_scroller').trigger('goto', [7]); });
	}
};
	
$(document).ready(function () {
	Common.init({});	
});
	


//Create a coupon-colorbox
function addCouponColorbox(elementObject, couponImage){
	var couponPopupHtml = '<div class="couponColorbox">';
	couponPopupHtml += '<div id="colorboxtitle">';
	couponPopupHtml += 'SPECIAL OFFER';
	couponPopupHtml += '<img id="coupons-printColorbox-button-close" src="/images/close.png"/>';
	couponPopupHtml += '<img id="coupons-printColorbox-button-print" src="/images/print.png" onclick="var s=s_gi(\'lwingprimewelltires\');s.linkTrackVars=\'events\';s.linkTrackEvents=\'event12\';s.events=\'event12\';s.tl(this,\'o\',\'Print Coupon Click\');"/>';
	couponPopupHtml += '</div>';
	couponPopupHtml += '<img class="centerImage" src="/images/coupons/'+couponImage+'"/>';
	couponPopupHtml += '</div>';
	elementObject.colorbox({html:couponPopupHtml, width:"750px", initialHeight:"480px", opacity:0.45, onComplete:function(){
		$('#coupons-printColorbox-button-close').click(function(){
			$.colorbox.close();
		});
		$('#coupons-printColorbox-button-print').click(function(){
			window.print();
		});
		$.colorbox.resize();
	}});
}

