//
//  (ñ) SiteLeader, 2005-2008 | http://www.siteleader.ru
//
var unicode = {
  'win1251' : {
    'from_unicode' : { 
      0x0410:0xc0,0x0411:0xc1,0x0412:0xc2,0x0413:0xc3,0x0414:0xc4,0x0415:0xc5,0x0416:0xc6,0x0417:0xc7,0x0418:0xc8,0x0419:0xc9,0x041A:0xca,
      0x041B:0xcb,0x041C:0xcc,0x041D:0xcd,0x041E:0xce,0x041F:0xcf,0x0420:0xd0,0x0421:0xd1,0x0422:0xd2,0x0423:0xd3,0x0424:0xd4,0x0425:0xd5,
      0x0426:0xd6,0x0427:0xd7,0x0428:0xd8,0x0429:0xd9,0x042A:0xda,0x042B:0xdb,0x042C:0xdc,0x042D:0xdd,0x042E:0xde,0x042F:0xdf,0x0430:0xe0,
      0x0431:0xe1,0x0432:0xe2,0x0433:0xe3,0x0434:0xe4,0x0435:0xe5,0x0436:0xe6,0x0437:0xe7,0x0438:0xe8,0x0439:0xe9,0x043A:0xea,0x043B:0xeb,
      0x043C:0xec,0x043D:0xed,0x043E:0xee,0x043F:0xef,0x0440:0xf0,0x0441:0xf1,0x0442:0xf2,0x0443:0xf3,0x0444:0xf4,0x0445:0xf5,0x0446:0xf6,
      0x0447:0xf7,0x0448:0xf8,0x0449:0xf9,0x044A:0xfa,0x044B:0xfb,0x044C:0xfc,0x044D:0xfd,0x044E:0xfe,0x044F:0xff,0x0451:0xb8,0x0401:0xa8,
      0x2013:0x96
    },
    'to_unicode' : {
      0x80:0x0402,0xc0:0x0410,0xc1:0x0411,0xc2:0x0412,0xc3:0x0413,0xc4:0x0414,0xc5:0x0415,0xc6:0x0416,0xc7:0x0417,0xc8:0x0418,0xc9:0x0419,
      0xca:0x041A,0xcb:0x041B,0xcc:0x041C,0xcd:0x041D,0xce:0x041E,0xcf:0x041F,0xd0:0x0420,0xd1:0x0421,0xd2:0x0422,0xd3:0x0423,0xd4:0x0424,
      0xd5:0x0425,0xd6:0x0426,0xd7:0x0427,0xd8:0x0428,0xd9:0x0429,0xda:0x042A,0xdb:0x042B,0xdc:0x042C,0xdd:0x042D,0xde:0x042E,0xdf:0x042F,
      0xe0:0x0430,0xe1:0x0431,0xe2:0x0432,0xe3:0x0433,0xe4:0x0434,0xe5:0x0435,0xe6:0x0436,0xe7:0x0437,0xe8:0x0438,0xe9:0x0439,0xea:0x043A,
      0xeb:0x043B,0xec:0x043C,0xed:0x043D,0xee:0x043E,0xef:0x043F,0xf0:0x0440,0xf1:0x0441,0xf2:0x0442,0xf3:0x0443,0xf4:0x0444,0xf5:0x0445,
      0xf6:0x0446,0xf7:0x0447,0xf8:0x0448,0xf9:0x0449,0xfa:0x044A,0xfb:0x044B,0xfc:0x044C,0xfd:0x044D,0xfe:0x044E,0xff:0x044F,0xb8:0x0451,
      0xa8:0x0401,0x96:0x2013 }
  }
}

function utf8_to_win1251(str)
{
  var out = '';
  var t = unicode['win1251']['from_unicode'];
  if (!t) return null;
  var c = null, i = 0;
  
  while (i < str.length)
  {
    c = str.charCodeAt(i);
    // Latin??
    if ((c & 0x80) == 0) out += String.fromCharCode(c);
    // 110xxxxx (2 chars)
    else if ((c & 0xe0) == 0xc0) {
      c = ((c & 0x3f) << 6) | ((str.charCodeAt(++i)) & 0x3f);
      out += t[c] ? String.fromCharCode(t[c]) : String.fromCharCode(c); 
    }
    // 1110xxxx (3 chars)
    else if ((c & 0xf0 ) == 0xe0) {
      c = ((c & 0x0f) << 12 ) | (((str.charCodeAt(++i)) & 0x3f ) << 6) | ((str.charCodeAt(++i)) & 0x3f);
      out += t[c] ? String.fromCharCode(t[c]) : String.fromCharCode(c);
    }
    else out += '*';
    //i++;
  }
  return out;
}
 