/**
 * An NMEA 0183 Message parser/manager.
 *
 * @file     NMEAMessage.js
 * @date     2008-10-28 12:33 HST
 * @author   Paul Reuter
 * @version  1.2
 *
 * @include  Message
 */


/**
 * Construct an NMEA message object.
 *
 * @constructor
 * @param {string} message The NMEA message in string notation.
 * @return {object} new NMEAMessage(message)
 */
function NMEAMessage(message) { 
  Message.call(this,message,',');
  return this;
}; // END: constructor NMEAMessage(message)
NMEAMessage.prototype = new Message;


/**
 * Returns the application-specific identifier for this NMEA sentence.
 * The app ID is the first 2 characters of the 5 character NMEA sentence.
 *
 * @public
 * @return {string} 2-char Application code (ex: GP, AI)
 */
NMEAMessage.prototype.getApplicationID = function() {
  var appid = this.getField(0);
  if( !appid ) { 
    return false;
  }
  return appid.substr(1,2);
}; // END: function getApplicationID()


/**
 * Returns the application-specific identifier for this NMEA sentence.
 * The app ID is the first 2 characters of the 5 character NMEA sentence.
 *
 * @public
 * @return {string} 3-char Application code (ex: WPT, VDM, TXT, ALR)
 */
NMEAMessage.prototype.getMessageID = function() {
  var msgid = this.getField(0);
  if( !msgid ) { 
    return false;
  }
  return msgid.substr(3,3);
}; // END: function getMessageID()


/**
 * Tests to make sure current message conforms to NMEA structure.
 *
 * @public
 * @return {boolean} yes or no
 */
NMEAMessage.prototype.isNMEA = function() { 
  return (this.message.match(/[!$][a-z][a-z0-9]{4},[^!$*]+[*][0-9A-F]{2}/i));
}; // END: function isNMEA()


/**
 * Tests to ensure that current message has a valid checksum.
 *
 * @public
 * @return {boolean} yes or no
 */
NMEAMessage.prototype.hasValidChecksum = function() { 
  var fields = this.getFields();
  if( fields.length < 1 ) { 
    return false;
  }
  var top = fields.pop();
  fields = top.split('*');
  if( fields.length != 2 ) { 
    return false;
  }
  var computed = this.computeChecksum();
  return (computed == parseInt(fields[1],16));
}; // END: function hasValidChecksum()


/**
 * Computes the checksum of the current message.
 *
 * @public
 * @return {int} checksum
 */
NMEAMessage.prototype.computeChecksum = function() { 
  var chksm = 0;
  var match = this.message.match(/[!$]([^!$*]+)[*]/);
  if( !match ) { 
    return false;
  }
  var subset = match[1];
  for(var i=0,n=subset.length; i<n; i++) { 
    chksm ^= subset.charCodeAt(i);
  }
  return chksm;
}; // END: function computeChecksum()
