// ==UserScript==
// @name           gmail-aim-convert
// @namespace      gmail
// @include        http://mail.google.com/mail/
// ==/UserScript==
//


win2utf = { 224: 1072, 225: 1073, 226: 1074, 227: 1075, 228: 1076, 229: 1077,
            184: 1105, 230: 1078, 231: 1079, 232: 1080, 233: 1081, 234: 1082,
            235: 1083, 236: 1084, 237: 1085, 238: 1086, 239: 1087, 240: 1088,
            241: 1089, 242: 1090, 243: 1091, 244: 1092, 245: 1093, 246: 1094,
            247: 1095, 248: 1096, 249: 1097, 250: 1098, 251: 1099, 252: 1100,
            253: 1101, 254: 1102, 255: 1103, 192: 1040, 193: 1041, 194: 1042,
            195: 1043, 196: 1044, 197: 1045, 168: 1025, 198: 1046, 199: 1047,
            200: 1048, 201: 1049, 202: 1050, 203: 1051, 204: 1052, 205: 1053,
            206: 1054, 207: 1055, 208: 1056, 209: 1057, 210: 1058, 211: 1059,
            212: 1060, 213: 1061, 214: 1062, 215: 1063, 216: 1064, 217: 1065,
            218: 1066, 219: 1067, 220: 1068, 221: 1069, 222: 1070, 223: 1071 };

function fix_encoding(node) {
  if (node.innerHTML) {
    var recoded = node.innerHTML.replace(/([\x80-\xff])/g,
      function(dummy, c) {
        var cc = c.charCodeAt(0);
        return win2utf[cc] ? String.fromCharCode(win2utf[cc]) : c;
      });
    if (node.innerHTML != recoded) {
      node.innerHTML = recoded;
    }
  };
  for (var i = 0; i < node.childNodes.length; i++) {
    fix_encoding(node.childNodes[i]);
  }
}

function fix_chat_windows() {
  var spans = document.getElementsByTagName('span');

  for (var i = 0; i < spans.length; i++) {
    var span = spans[i];
    if (span.innerHTML == 'Pop-out') {
      GM_log('found chat window, fixing');
      fix_encoding(span.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode);
    }
  }
}

if (document.getElementById('topbody')) {

  GM_log('hello');

  my_interval = setInterval(fix_chat_windows, 10000);

}

