$(document).ready(function(){

	// indent radio buttons
	$('input[type=radio]').css('marginLeft','10px');

	// highlight current field (except radio buttons)
	var currentColor = '#ffffff';
	
	//Eventually substitute this option
	$('input,textarea').focus( function() { $(this).addClass('active'); });
	$('input,textarea').blur( function() { $(this).removeClass('active'); });

	// hide "How Hear? (Other) until clicked
	/*
	$('#howhearother').hide();
	$('#otherradio').click(function(){
		$('#howhearother').show();
	});
	*/
	
	//Focus on first field
	$('#firstname').focus();

	// autofill information from ZIP Code
	$("#postalcode").keyup(function(event){
		var keycode = event.keyCode;
		// only fire on a numeric keyUp event
		if ( !(keycode >= 96 && keycode <= 105)  && !(keycode >= 48 && keycode <= 57) ) { return false; }
		//console.log('key: ' + keycode);
		var zipcode = $("#postalcode").val();
		zipcode = zipcode + "";
		var countrysel = $("#country").val();
		// only run if ZIP is 5 digits long, all numbers, and country is US (pre-selected by geocoding)
		if ( (zipcode.length == 5) && (countrysel == 'US') ) {
			// send to ZIP lookup, output XML data
			$.post("/js/ajax/checkzip.php",{ zip: zipcode }, function(xml){
            	// fill location fields with data returned from ZIP lookup
				var state = $("state",xml).text();
            	var city = $("city",xml).text();
            	if ((state) && (city)) {  // if city & state returned, update fields
					var country = "US";
            		// highlight updated fields for visual notification (uses Easing functions)
            		$("#city,#state")
      						.animate({opacity: 0}, 600, 'easeOutQuart', updateFields)
      						.animate({opacity: 1}, 1400, 'easeOutQuart');
             	} else {  // if nothing returned, clear fields
             		var city = "", state = "", country = "";
             	}
            	// update fields
            	function updateFields() {
            		if ($("#postalcode").val().length) {
		            	$("#city").attr("value",city);
		            	$("#state").attr("value",state);
		            	$("#country").attr("value",country);
		            }
	            }
            });
		}
	});
	
	//Autofill for the calling code for the country
	var phoneEdit = "";
	var phoneEdited = false;
	
	$('#country').change(function(){
		//TODO:add fancy fade effect like the postal code change above
		//$("#callingcode").attr("value", $('#country').val());
		var newCode = $("#country option:selected").attr("rel");

		if(phoneEdited == false && $("#phone").val() != newCode){
			$("#phone")
				.animate({opacity: 0}, 600, 'easeOutQuart', updateFields)
				.animate({opacity: 1}, 1400, 'easeOutQuart');
		}

		function updateFields() {
			$("#phone").attr("value", "+" + newCode + " ");
		}
	});
	
	$('#phone').focus(function (){
		phoneEdit = $("#phone").val();					
	});
	
	//Evaluates whether the user has correctly input a country code
	//TODO: make another hidden field for the other part of the number.
	$('#phone').blur(function (){
		if($('#phone').val() == ""){
			phoneEdited = false;
		} else if($('#phone').val() != phoneEdit || phoneEdited == true) {
			phoneEdited = true;
		} else {
			phoneEdited = false;
		}
		
		var spacePos = $('#phone').val().search(/\s+/g);
		var americaPrefix = $('#phone').val().search(/\+1\s+[0-9][0-9][0-9]\s+/g);
		
		if(americaPrefix > -1){
			$('#callingcode').attr("value", $('#phone').val().slice(0, 6));
			$('#phonenumber').attr("value", $('#phone').val().slice(7, $('#phone').val().length));
		} else if($('#phone').val().slice(0, 1) == "+" && 1 < spacePos && spacePos < 5){
			$('#callingcode').attr("value", $('#phone').val().slice(0, spacePos));
			$('#phonenumber').attr("value", $('#phone').val().slice((spacePos + 1), $('#phone').val().length));
		} else {
			$('#callingcode').attr("value", "");
			$('#phonenumber').attr("value", $('#phone').val());
		}
		
	});

	// clear state value (autofilled from ZIP) if non-US country selected
	var country = $("#country");
	country.change(function(){
		if ( ( country.val() != 'USA' ) && ( $('#state').val() != '' ) ) $('#state').val('');
	});

	// show personal email warning
	/*
	$("#emailwarning").hide();
	$("#email").blur(function(){
		var addr = $("#email").val();
		// warn if personal e-mail found
		if ( addr.match("yahoo.c") || addr.match("hotmail.c") || addr.match("gmail.c") || addr.match("live.c") ) {
			$('#emailWarning').show();
			$("#email").parent().addClass('warningBorder');
		} else {
			$('#emailWarning').hide();
			$("#email").parent().removeClass('warningBorder');
		}
	});
	*/

	// chemistry autocomplete
	/*
	$chemistry = $("#chemistry");
	$chemistry.autocomplete(chems, {
		width: 268,
		max: 4,
		highlight: false,
		matchContains: true,
		multiple: true,
		multipleSeparator: ", ",
		scroll: true,
		scrollHeight: 300,
		formatItem: function(row) {
			var chemString = row.name;
			if (row.symbol) chemString += " (" + row.symbol + ")";
			return chemString;
		},
		formatMatch: function(row, i, max) {
			return row.name + " " + row.symbol;
		},
		formatResult: function(row) {
			if (row.symbol) {
				return row.symbol;
			} else {
				return row.name;
			}
		}
	});

	// trim whitespace & trailing comma from chemistry field onBlur
	$chemistry.blur(function(){
		var chems = $.trim( $chemistry.val() );
		chems = chems.replace(/\,$/,"");  // http://www.tek-tips.com/viewthread.cfm?qid=1147368&page=3
		$chemistry.val( chems );
	});
	*/
	
	
	// geocoder function
	function newGeocode(address){
		$.geocoder = new GClientGeocoder();
		$.geocoder.getLocations(address, getGeocode);
			
		function getGeocode(response){
			
			if(response.Placemark != undefined){
						
				var newLat = response.Placemark[0].Point.coordinates[1];
				var newLong = response.Placemark[0].Point.coordinates[0];
				var newGoogleMap = 'http://maps.google.com/maps/api/staticmap?center=' + address + '&size=180x158&sensor=false\&markers=color:0xe780f|' + address + '&key=ABQIAAAAyy7owyNPdtPXtXYQNvS1lxToItV0mIf8r73zl36MaZyLuU8ObRQo3TI8bDPLCiBcZ31kfEaxLO-ciw'
				
				//Populates hidden fields with latitude, longitude, and google maps code
				$("#latitude").attr("value",newLat);
				$("#longitude").attr("value",newLong);
				$("#mapimageurl").attr("value",newGoogleMap);
				
			}
		}
	}
	
	// blur function attached to the address fields that fires geocode function
	$('#address1, #address2, #address3, #postalcode, #city, #state').blur(blurNewGeocode);

	
	// set new geocoding parameters on address field blur
	var addressParsed;
	
	function blurNewGeocode(){		
		//Listens to each address field, but only passes either the zip or the city to google. 
		var preferedLocation = ($('#postalcode').val() != "") ? $('#postalcode').val() : $('#city').val();
		addressParsed = $('#address1').val() + " " + preferedLocation + " " + $('#state').val() + " " + $('#country').val();
		addressParsed = addressParsed.replace(/\s\s+/g, " ");
		addressParsed = addressParsed.replace(/\s+/g, "+");
		newGeocode(addressParsed);
		
	}
	
	//Get browser information
	var nVer = navigator.appVersion;
	var nAgt = navigator.userAgent;
	var browserName  = navigator.appName;
	var fullVersion  = ''+parseFloat(navigator.appVersion); 
	var majorVersion = parseInt(navigator.appVersion,10);
	var nameOffset,verOffset,ix;
	
	// In MSIE, the true version is after "MSIE" in userAgent
	if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
		browserName = "Microsoft Internet Explorer";
		fullVersion = nAgt.substring(verOffset+5);
	}
	// In Opera, the true version is after "Opera" 
	else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
		browserName = "Opera";
		fullVersion = nAgt.substring(verOffset+6);
	}
	// In Chrome, the true version is after "Chrome" 
	else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
		browserName = "Chrome";
		fullVersion = nAgt.substring(verOffset+7);
	}
	// In Safari, the true version is after "Safari" 
	else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
		browserName = "Safari";
		fullVersion = nAgt.substring(verOffset+7);
	}
	// In Firefox, the true version is after "Firefox" 
	else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
		browserName = "Firefox";
		fullVersion = nAgt.substring(verOffset+8);
	}
	// In most other browsers, "name/version" is at the end of userAgent 
	else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) 
	{
		browserName = nAgt.substring(nameOffset,verOffset);
		fullVersion = nAgt.substring(verOffset+1);
		if (browserName.toLowerCase()==browserName.toUpperCase()) {
			browserName = navigator.appName;
		}
	}
	// trim the fullVersion string at semicolon/space if present
	if ((ix=fullVersion.indexOf(";"))!=-1) fullVersion=fullVersion.substring(0,ix);
	if ((ix=fullVersion.indexOf(" "))!=-1) fullVersion=fullVersion.substring(0,ix);
	
	majorVersion = parseInt(''+fullVersion,10);
	if (isNaN(majorVersion)) {
		fullVersion  = ''+parseFloat(navigator.appVersion); 
		majorVersion = parseInt(navigator.appVersion,10);
	}

	$('#browser').attr("value", browserName + ' ' + fullVersion);
	
	//Get time and date when submit button is clicked
	////$('#submit').click(getTimeAndDate);
	
//	function getTimeAndDate(){
//		alert("sdf");
//		var currentDate = new Date();
//		var UTCDate = currentDate.getUTCDate();
//		var UTCMonth = currentDate.getUTCMonth() + 1;
//		var UTCHours = currentDate.getUTCHours() - 5;
//		var UTCMinutes = currentDate.getUTCMinutes();
//		var UTCSeconds = currentDate.getUTCSeconds();
//			
//		var UTCDate = (UTCDate.toString().length == 1) ? "0" + UTCDate : UTCDate;
//		var UTCMonth = (UTCMonth.toString().length == 1) ? "0" + UTCMonth : UTCMonth;
//		var UTCHours = (UTCHours.toString().length == 1) ? "0" + UTCHours : UTCHours;
//		var UTCMinutes = (UTCMinutes.toString().length == 1) ? "0" + UTCMinutes : UTCMinutes;
//		var UTCSeconds = (UTCSeconds.toString().length == 1) ? "0" + UTCSeconds : UTCSeconds;
//		
//		var parsedDate = currentDate.getFullYear() + "-" + UTCMonth + "-" + UTCDate;
//		var parsedTime = UTCHours + ":" + UTCMinutes + ":" + UTCSeconds;
//	
//		$('#quotetime').attr("value", parsedTime);	
//		$('#quotedate').attr("value", parsedDate);
//		
//		//getUPSTradeAbilityParty();
//	}

  /****************************************
   * UPS TradeAbility Check
   * 
   * Check Denied Party Status for request-spin-coater-quote.php only
   * Only process if <body id="request-spin-coater-quote">
   *          
   ****************************************/
   			//Tradability check function
  
   
//	function tradeAbilityCheck($url){
//		// serialize form data
//		$formdata = $('form').serialize();
//		// DEBUG: show form data in Firebug
//		// *** Remove for production ***
//		console.log ($formdata);
//		$.ajax({
//			url:      "/lib/ups/tradeability/ajax_check.php",
//			data:     $formdata,
//			dataType: "html",
//			success:  function(response){
//				// set the hidden 'deniedparty' field's value to the result of the AJAX request
//				  $('#deniedparty').val(response);
//			},
//			error:    function(){
//				$('#deniedparty').val("Error processing UPS TradeAbility Request");
//			}
//		});
//	}
  
  	//Functionally superceded by the tradeabilityparty function... for now will leave hidden field on form and column in SQL database
  	//$('#country').change(getUPSTradeAbilityCountry);
  
	function getUPSTradeAbilityCountry()
	{
		// c: 2-digit ISO countrycode
		var c = $('#country').val();
		var result;
		$.ajax({
		   async: false,
		   type: "GET",
		   url: "/lib/ups/tradeability/inc_tradeability.php",
		   data: "reqtype=country&countrycode=" + c,
		   dataType: "text",
		   success: function(response){
			 	$('#deniedparty').val(response);
		   },
		   error: function(){
				$('#deniedparty').val("Error processing UPS TradeAbility Request");
		   }
		 });
		 //return result;
	}	

	// USA! USA! USA! (move it to top of Country select
	if ($('#country').length) { $('#country option[value="USA"]').insertAfter( $('#country option:first') ); }
     
});  // end Doc Ready

	function getTimeAndDate(){
		
		var currentDate = new Date();
		var UTCDate = currentDate.getUTCDate();
		var UTCMonth = currentDate.getUTCMonth() + 1;
		var UTCHours = currentDate.getUTCHours() - 5;
		var UTCMinutes = currentDate.getUTCMinutes();
		var UTCSeconds = currentDate.getUTCSeconds();
			
		var UTCDate = (UTCDate.toString().length == 1) ? "0" + UTCDate : UTCDate;
		var UTCMonth = (UTCMonth.toString().length == 1) ? "0" + UTCMonth : UTCMonth;
		var UTCHours = (UTCHours.toString().length == 1) ? "0" + UTCHours : UTCHours;
		var UTCMinutes = (UTCMinutes.toString().length == 1) ? "0" + UTCMinutes : UTCMinutes;
		var UTCSeconds = (UTCSeconds.toString().length == 1) ? "0" + UTCSeconds : UTCSeconds;
		
		var parsedDate = currentDate.getFullYear() + "-" + UTCMonth + "-" + UTCDate;
		var parsedTime = UTCHours + ":" + UTCMinutes + ":" + UTCSeconds;
	
		$('#quotetime').attr("value", parsedTime);	
		$('#quotedate').attr("value", parsedDate);
		
		$('form').submit();
		//getUPSTradeAbilityParty();
	}
	
	
	function getUPSTradeAbilityParty()
	{
		// str should be serialized string of form inputs that emulate what the UPS tradeability API is looking for
		var parsedName = $('#firstname').val() + " " + $('#lastname').val();
		parsedName = parsedName.replace(/\s\s+/g, " ");
		parsedName = parsedName.replace(/\s+/g, "+");
		parsedName = (parsedName.substring(0,1) == "+") ? parsedName.substring(1, (parsedName.length)) : parsedName;
																				   
		var str = "contact=" + parsedName + "&company=" + $("#organization").val() + "&addr1=" + $("#address1").val() + "&addr2=" + $("#address2").val() + "&addr3=" + $("#address3").val() + "&city=" + $("#city").val() + "&state=" + $("#state").val() + "&postalcode=" + $("#postalcode").val() + "&countrycode=" + $("#country").val();
		
		parsedString = str.replace(/\s\s+/g, " ");
		parsedString = parsedString.replace(/\s+/g, "+");
		parsedString = (parsedString.substring(0,1) == "+") ? parsedString.substring(1, (parsedString.length)) : parsedString;		
		
		$('#upsstring').val(parsedString);
		
		var result;
		$.ajax({
		   async: false,
		   type: "GET",
		   url: "/lib/ups/tradeability/inc_tradeability.php",
		   data: "reqtype=party&" + str,
		   dataType: "text",
		   success: function(response){
			 	$('#deniedparty').val(response);
		   },
		   error: function(){
				$('#deniedparty').val("Error processing UPS TradeAbility Request");
		   }
		 });
		
		 //form.submit();
		 $('form').submit();
	}
