// general utilities
function buildSelect(menu, items) {
  menu.length = items.length;

  for (i = 0; i < items.length; i++) {
    menu.options[i].value = items[i][0];
    menu.options[i].text = items[i][1];
  }
}

function findByKey(list, key) {
  for (var i = 0; i < list.length; i++) {
    if (list[i][0] == key) {
      return list[i];
    }
  }
  return false;
}

function addPortableEventHandler(object, eventName, handlerFun) {
  if (object.addEventListener != null) {
	object.addEventListener(eventName, handlerFun, false);
  } else if (object.attachEvent != null) {
	object.attachEvent("on" + eventName, handlerFun);
  }
}

// dealing with MS 'special' characters
var msCharSubs = [
  [0x82, ','],
  [0x83, '<em>f</em>'],
  [0x84, ',,'],
  [0x85, '...'],
  [0x88, '^'],
  [0x8b, '<'],
  [0x8c, 'Oe'],
  [0x91, "'"],
  [0x92, "'"],
  [0x93, '"'],
  [0x94, '"'],
  [0x95, '*'],
  [0x96, '-'],
  [0x97, '--'],
  [0x98, '<sup>~</sup>'],
  [0x99, '<sup>TM</sup>'],
  [0x9b, '>'],
  [0x9c, 'oe'],

  [8208, '-'],
  [8209, '-'],
  [8211, '--'],
  [8212, '--'],
  [8213, '--'],
  [8214, '||'],
  [8215, '<u>_</u>'],
  [8216, "'"],
  [8217, "'"],
  [8218, ','],
  [8219, "'"],
  [8220, '"'],
  [8221, '"'],
  [8222, ",,"],
  [8223, '"'],
  [8226, '&#183;'],
  [8227, '&#183;'],
  [8228, '&#183;'],
  [8229, '..'],
  [8230, '...'],
  [8231, '&#183;'],

  [163, '&pound;']
];

function unSmarten(field) {
  var str = field.value;
  var newstr = "";

  for (i = 0; i < str.length; i++) {
    var sub = findByKey(msCharSubs, str.charCodeAt(i));

    if (sub) {
      newstr = newstr.concat(sub[1]);
    } else {
      newstr = newstr.concat(str.charAt(i));
    }
  }

  field.value = newstr;

  return true;
}

// Build a date menu with appropriate days
// note that months indexes are one-based for compatability with .NET
var shortMonths = [4, 6, 9, 11];
var reallyShortMonth = 2;

function populateDays(menu, month, year) {
  var nDays = 31;

  if (month == reallyShortMonth) {
    if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
      nDays = 29;
    else
      nDays = 28;
  }

  for (var i = 0; i < shortMonths.length; i++) {
    if (month == shortMonths[i]) {
      nDays = 30;
    }
  }

  //alert("days: " + nDays + ", month: " + month + ", year: " + year);

  var items = [];

  for (var i = 1; i <= nDays; i++) {
    items.push([i, i]);
  }

  buildSelect(menu, items);
}

function setText(elem, txt) {
    if (document.all)
        elem.innerText = txt;
    else
        elem.textContent = txt;
}


