$(function(){
	
	var formInputControl = function(selector){
		$(selector).each(function(index){
			var startText = $(this).val();
			jQuery.data($(this).get(0),'def',startText);
			$(this).bind('focus',function(e){
				if($(this).val() == jQuery.data($(this).get(0),'def')){
					$(this).val('');
					$(this).css({
						color:'#4d4e4f'
					});
				}
			}).bind('blur',function(e){
				if($(this).val() == ''){
					$(this).val(jQuery.data($(this).get(0),'def'));
					$(this).css({
						color:'#b5b5b5'
					});
				}
			});
		});
	}
	
	if($('#compatibility-map').length > 0){
		if(GBrowserIsCompatible()){
			geocoder = new GClientGeocoder();
			geocoder.getLatLng(
				address,
				function(point){
					if(!point){
						window.location = "index.php?error=1";
					}else{
						var map = new GMap2(document.getElementById("compatibility-map"));
						map.setCenter(point, 13);
						var marker = new GMarker(point);
						map.addOverlay(marker);
						var distanceOverlay = new GScreenOverlay('images/step-2/map-overlay.png',
							new GScreenPoint(0,0,'pixels','pixels'),  // screenXY
							new GScreenPoint(0,0),  // overlayXY
							new GScreenSize(642,524)  // size on screen
						);
						map.addOverlay(distanceOverlay);
						map.addControl(new GScaleControl());
					}
				}
			);
		}

		$(window).unload(function(){
			GUnload();
		});
	}
	
	if($('#step-1-address-form').length > 0){
		$('#step-1-address-form').submit(function(e){
			if(
				$('#step-1-country-input').val() != 'United States' &&
				(
					$('#step-1-name-input').val() == '' || 
					$('#step-1-name-input').val() == jQuery.data($('#step-1-name-input').get(0),'def') || 
					$('#step-1-email-input').val() == '' || 
					$('#step-1-email-input').val() == jQuery.data($('#step-1-email-input').get(0),'def') ||
					$('#step-1-address-input').val() == '' || 
					$('#step-1-address-input').val() == jQuery.data($('#step-1-address-input').get(0),'def') || 
					$('#step-1-city-input').val() == '' || 
					$('#step-1-city-input').val() == jQuery.data($('#step-1-city-input').get(0),'def')
				)
			){ 
				alert('Please fill out all address fields before submitting the form.');
				return false;
			}else if(
				$('#step-1-country-input').val() == 'United States' &&
				(
					$('#step-1-name-input').val() == '' || 
					$('#step-1-name-input').val() == jQuery.data($('#step-1-name-input').get(0),'def') || 
					$('#step-1-email-input').val() == '' || 
					$('#step-1-email-input').val() == jQuery.data($('#step-1-email-input').get(0),'def') ||
					$('#step-1-address-input').val() == '' || 
					$('#step-1-address-input').val() == jQuery.data($('#step-1-address-input').get(0),'def') || 
					$('#step-1-city-input').val() == '' || 
					$('#step-1-city-input').val() == jQuery.data($('#step-1-city-input').get(0),'def') ||
					$('#step-1-state-input').val() == '' || 
					$('#step-1-state-input').val() == jQuery.data($('#step-1-state-input').get(0),'def') || 
					$('#step-1-zip-input').val() == '' || 
					$('#step-1-zip-input').val() == jQuery.data($('#step-1-zip-input').get(0),'def')
				)
			){ 
				alert('Please fill out all address fields before submitting the form.');
				return false;
			}
		});
	}
	
	if($('#step-1-country-input').length > 0){
		$('#step-1-country-input').change(function(e){
			if($('#step-1-country-input').val() == 'United States'){
				if($('#step-1-state-input').val() == jQuery.data($('#step-1-state-input').get(0),'def')){
					$('#step-1-state-input').val('State')
				}
				jQuery.data($('#step-1-state-input').get(0),'def','State');
				if($('#step-1-zip-input').val() == jQuery.data($('#step-1-zip-input').get(0),'def')){
					$('#step-1-zip-input').val('Zip')
				}
				jQuery.data($('#step-1-zip-input').get(0),'def','Zip');
			}else{
				if($('#step-1-state-input').val() == jQuery.data($('#step-1-state-input').get(0),'def')){
					$('#step-1-state-input').val('Province')
				}
				jQuery.data($('#step-1-state-input').get(0),'def','Province');
				if($('#step-1-zip-input').val() == jQuery.data($('#step-1-zip-input').get(0),'def')){
					$('#step-1-zip-input').val('Postal Code')
				}
				jQuery.data($('#step-1-zip-input').get(0),'def','Postal Code');
			}
		});
	}
	
	$('.ui-slider').each(function(e){
		var slideTarget = $(this).siblings('.slider-value');
		$(this).slider({ minValue:0, maxValue:100, stepping:10, startValue:50, slide:function(e,ui){ slideTarget.text(ui.value); } });
	});
	
	var sliderCount = 0;
	var currentQuestion = '';
	$('.slider-question').each(function(e){
		if(sliderCount > 0){
			$(this).hide();
			sliderCount++;
		}else{
			var idArray = $(this).attr('id').split('-');
			currentQuestion = idArray[2];
			sliderCount++;
		}
	});
	
	$('#next-question-button').click(function(e){
		sliderCount--;
		
		saveUserAnswer(currentQuestion,$('#slider-question-' + currentQuestion + ' .ui-slider').slider('value',0));
		$('#slider-question-complete-' + currentQuestion).css({ fontWeight:'bold' });
		
		if(sliderCount == 0){
			$('#next-question-button').unbind('click');
			window.location = $('#next-question-button').attr('href');
		}else{			
			$('#slider-question-' + currentQuestion).fadeOut();
			$('#slider-question-' + currentQuestion).next().fadeIn();
			var idArray = $('#slider-question-' + currentQuestion).next().attr('id').split('-');
			currentQuestion = idArray[2];
		}
	
		return false;
	});
	
	var saveUserAnswer = function(questionId,value){
		$.post('ajax.php',{
			action: 'saveAnswer',
			questionId: questionId,
			value: value
		});
	};
	
	$('#green-form').submit(function(e){
		if(isNaN(parseFloat($('#green-form-distance').val()))){
			alert('Please Enter A Numeric Value For Each Item');
		}else{
			var perGallon = isNaN(parseFloat($('#green-form-price').val())) ? parseFloat($('#green-form-price').attr('rel')) : parseFloat($('#green-form-price').val());
			var economy = isNaN(parseFloat($('#green-form-economy').val())) ? parseFloat($('#green-form-economy').attr('rel')) : parseFloat($('#green-form-economy').val());
			
			$.post('ajax.php',{
				action: 'calculate',
				distanceNum:parseFloat($('#green-form-distance').val()),
				distanceUnit:$('#green-form-distance-unit').val(),
				economyNum:economy,
				economyUnit:$('#green-form-economy-unit').val(),
				ppgNum:perGallon,
				ppgUnit:$('#green-form-price-unit').val()
			},function(data){
				updateGreenResults(data);
			});		
		}
		return false;
	});
	
	var updateGreenResults = function(data){		
		//*
		var results = data.split('|');
		var maxWidth = 0;
		var money = results[1];
		var currency = parseInt(results[2]);
		
		if(results[3] == 'kpg' || results[3] == 'lkm'){
			var segwayCarbon = Math.round((.003 * .45359237) * 1000)/1000;
			var carbon = Math.round((results[0] * .45359237) * 1000)/1000;
			var unit = 'kg';
		}else{
			var segwayCarbon = .003;
			var carbon = results[0];
			var unit = 'lbs';
		}
		
		$('.measurement').css({
			fontWeight:'bold',
			color:'#4D4E4F'
		});
	
		$('#green-calc-carbon-text').html(carbon + ' ' + unit + ' (per month)');
		maxWidth = $('#green-calc-carbon-text').parent().width() - ($('#green-calc-carbon-text').width() + 7);
		$('#green-calc-carbon-bar').animate({
			width: Math.round(carbon) <= maxWidth ? Math.round(carbon) : maxWidth
		},1500,'swing');
	
		$('#green-calc-segway-bar').animate({
			width: '4px'
		},1500,'swing');
		$('#green-calc-segway-text').html(segwayCarbon + ' ' + unit + ' (per month)');
	
		switch(currency){
			case 1:
				var currencyType = '&euro;';
				break;
			case 2:
				var currencyType = '&pound;';
				break;
			default:
				var currencyType = '$';
				break;
		}
		$('#green-calc-money-text').html(currencyType + money + ' (per month)');
		
		maxWidth = $('#green-calc-money-text').parent().width() - ($('#green-calc-money-text').width() + 7);
		$('#green-calc-money-bar').animate({
			width: Math.round(money * 15) <= maxWidth ? Math.round(money * 15) : maxWidth
		},1500,'swing');
		// */	
	};
	
	if($('#green-calculator-next-step').length > 0){
		$('#green-calculator-next-step').click(function(e){
			$.post('ajax.php',{
				action: 'validate'
			},function(data){
				if(data == '1'){
					window.location = $('#green-calculator-next-step').attr('href');
				}else{
					alert('Please complete the energy savings calculation form before continuing.');
				}
			});
			return false;
		});
	}
	
	formInputControl('#step-1-address-form input,#green-form input');
	
	if($('.selected-profile').length > 0){
		$('.profile-information').hide().appendTo('#profile-display');
		$('#' + $('.selected-profile').attr('id') + '-information').show();
		
		$('.segway-profile').each(function(e){
			var currentBgPosition = $(this).css('backgroundPosition').split(' ');
			
			if($(this).hasClass('selected-profile')){
				$(this).css({
					backgroundPosition: currentBgPosition[0] + ' 0'
				});
			}
			
			$(this).click(function(e){
				$('.segway-profile').each(function(e){
					var otherBgPosition = $(this).css('backgroundPosition').split(' ');
					$(this).removeClass('selected-profile').css({
						backgroundPosition: otherBgPosition[0] + ' -237px'
					});	
				});
				
				$(this).addClass('selected-profile').css({
					backgroundPosition: currentBgPosition[0] + ' 0'
				});
				
				$('.profile-information').hide();
				$('#' + $(this).attr('id') + '-information').show();
			}).hover(function(e){
				if(!$(this).hasClass('selected-profile')){
					$(this).css({
						backgroundPosition: currentBgPosition[0] + ' -474px'
					});
				}
			},function(e){
				if(!$(this).hasClass('selected-profile')){
					$(this).css({
						backgroundPosition: currentBgPosition[0] + ' ' + currentBgPosition[1]
					});
				}
			});
		});
	}
	
	$('.profile-checkbox').click(function(e){
		$('.profile-checkbox').attr('checked','');
		$(this).attr('checked','checked');
		$('.profile-information').removeClass('profile-info-selected');
		$.post('ajax.php',{
			action: 'selectProfile',
			profile: $(this).val()
		});		
	});


	$('.profile-average-miles').change(function(e){
		$.post('ajax.php',{	
			action: 'updateProfile',
			type:'miles',
			value:$(this).val()
		});
	});

	
	$('.dollars-bold').each(function(){
		var dollars = $(this).children('li');
		var currentIndex = $(this).children('.dollars-selected').attr('rel');
		
		$(this).siblings('.profile-plus-button').click(function(e){
			if(currentIndex <= 3){
				$(dollars[currentIndex]).removeClass('dollars-selected');
				currentIndex++;
				$(dollars[currentIndex]).addClass('dollars-selected');
				
				$.post('ajax.php',{	
					action: 'updateProfile',	
					type:'savings',
					value:(currentIndex + 1)
				});
			}
		});

		$(this).siblings('.profile-minus-button').click(function(e){
			if(currentIndex >= 1){
				$(dollars[currentIndex]).removeClass('dollars-selected');
				currentIndex--;
				$(dollars[currentIndex]).addClass('dollars-selected');
				
				$.post('ajax.php',{	
					action: 'updateProfile',	
					type:'savings',
					value:(currentIndex + 1)
				});
			}
		});
	});
	
	var log_click = function(type,href){
		$.post('ajax.php',{	
			action: 'logClick',
			type:type
		},function(data){
			if(type == 'custom'){
				window.location = href;
			}
		});
	}
	$('.results-button').click(function(e){
		log_click($(this).attr('rel'),$(this).attr('href'));
		return false;
	});
	
});
