/*
  Thai Tracking Fix v0.1 for Adobe Illustrator
  by Varoot Phasuthadol
  2015-11-28
*/

var count = 0;

function getTextFrames(selection) {
  var textFrames = [];
  for (var i = 0; i < selection.length; i++) {
    var obj = selection[i];

    if (obj.characters) {
      textFrames.push(obj);
      continue;
    }

    if (obj.textFrames) {
      textFrames = textFrames.concat(getTextFrames(obj.textFrames));
    }
  }

  return textFrames;
}

if (documents.length && activeDocument.textFrames.length) {
  var textFrames;

  if (selection.length) {
    textFrames = getTextFrames(selection);
  } else {
    textFrames = activeDocument.textFrames;
  }

  for (var i = 0; i < textFrames.length; i++) {
    var obj = textFrames[i];
    var characters = obj.characters;

    // Starts with 1 because we don't have to fix the first character
    for (var j = 1; j < characters.length; j++) {
      var prevChar = characters[j-1];
      var thisChar = characters[j];
      var charCode = thisChar.contents.charCodeAt(0);

      if (charCode === 0x0e31 || // ไม้หันอากาศ
        (charCode >= 0x0e34 && charCode <= 0x0e3a) || // สระบนล่าง
        (charCode >= 0x0e47 && charCode <= 0x0e4e)) { // วรรณยุกต์
        if (prevChar.characterAttributes.tracking > 0) {
          prevChar.characterAttributes.tracking = 0;
          count++;
        }
      }
    }
  }

  if (count) {
    alert(count + " tracking problems fixed.");  
  } else if (textFrames.length) {
    alert("No tracking problems found.")
  } else {
    alert("No text is selected.")
  }
} else {
  alert("Open a document with text items.");
}
