Drupal.themes = Drupal.themes || {};

/**
 * Encode special characters in a plain-text string for display as HTML.
 */
Drupal.checkPlain = function(str) {
  str = String(str);
  var replace = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' };
  for (var character in replace) {
    str = str.replace(character, replace[character]);
  }
  return str;
}

/**
 * Translate strings to the current locale.
 */
Drupal.t = function(str, args) {
  if (typeof str == 'object') {
    if (Drupal.locale.strings[str[0]]) {
      str = Drupal.locale.strings[str[0]];
    }
    if (args && args['@count']) {
      if (Drupal.locale.pluralFormula) {
        str = str[Drupal.locale.pluralFormula(args['@count'])];
      }
      else {
        str = str[(args['@count'] == 1) ? 0 : 1];
      }
    }
    else {
      str = str[0];
    }
  }
  else if (Drupal.locale[str]) {
    str = Drupal.locale[str]
  }

  if (args) {
    // Transform arguments before inserting them
    for (var key in args) {
      switch (key.charAt(0)) {
        // Escaped only
        case '@':
          args[key] = Drupal.checkPlain(args[key]);
        break;
        // Pass-through
        case '!':
          break;
        // Escaped and placeholder
        case '%':
        default:
          args[key] = Drupal.theme('placeholder', args[key]);
          break;
      }
      str = str.replace(key, args[key]);
    }
  }
  return str;
}

/**
 * Generate the themed representation of a Drupal object.
 */
Drupal.theme = function(func) {
  for (var i = 1, args = []; i < arguments.length; i++) {
    args.push(arguments[i]);
  }

  var theme = (Drupal.settings.theme && Drupal.themes[Drupal.settings.theme] && Drupal.themes[Drupal.settings.theme][func]) ? Drupal.settings.theme : 'default';
  return Drupal.themes[theme][func].apply(Drupal, args);
}

/**
 * The default themes.
 */
Drupal.themes['default'] = {
  // Formats text for emphasized display in a placeholder inside a sentence.
  placeholder: function(str) {
    return '<em>' + Drupal.checkPlain(str) + '</em>';
  }
};

$(document).ready(function () {
  Drupal.settings = Drupal.settings || {};
  Drupal.locale = Drupal.locale || Drupal.settings.locale || {};
});
