jQuery(function($) {
   $(document).ready(function() {
	  //alert('classification lookup in plugins start');

	  $.get(myAjax.ajaxurl, { action: "populateLocations", _ajax_nonce: myAjax.nonce }, function(data) {  
		$('select[name="country"]').append(data);
      });
	  
	  $.get(myAjax.ajaxurl, { action: "populatePackageTypes", _ajax_nonce: myAjax.nonce }, function(data) { 
		$('select[name="packagetype"]').append(data);
      });
	  
	  $('#lookup').click(function() {		  
		 var country = $('select[name="country"]').val();
		 var packagetype = $('select[name="packagetype"]').val();
		 
		// validate fields are not empty
		var countEmpty = 0;

		$('#msg').hide();
		$('select').removeAttr('style');

		$('select').each(function() {
			if (isEmpty($(this).val())) {
				if (!$(this).prop('disabled')) {

					++countEmpty;
					$(this).css({ 'border': '1px solid red' });
				}
			} 			
		});	
		
		if (countEmpty > 0) {
			$('#msg').html('* All fields are required.').show();
			
		} else {
			$.post(myAjax.ajaxurl, { action: "classificationLookup", _ajax_nonce: myAjax.nonce, country: country, packagetype: packagetype }, function(data) { 			
				$('input[name="itemclassification"]').val(data);
				
				if (data.startsWith('Anomalies')) {
					$('#msg').html('* Anomalies in the Country. Please call customer service for more details.').show();
				} else {
					$('#msg').hide();
				}
			});
		}
		 
	  });
	  
		function isEmpty(val) {
			var trimmed = val.trim();
			if (trimmed || trimmed.length > 0) {
			  return false;
			} 
			return true;
		}

   });	
});
