// (c) 2006-2008, MForum.ru

function madr(a,d) {
  return a+String.fromCharCode(64)+d.replace(/#/g,'\056');
}

function mto(a,d) {
  var m = madr(a,d);
  document.write(String.fromCharCode(60,97,32,104)+'ref=\"mai'+String.fromCharCode(108,116,111,58)+m+'\">'+m+'\074/a\076');
}

function qtCheck() {
  try {
    var qtVars=document.getElementsByName("qtmov");
    var qtVer, i;
    if (qtVars && qtVars.length>0) {
      for (i=0; i<qtVars.length; i++) {
        try { qtVer=qtVars[i].GetQuickTimeVersion(); } catch (e) {}
        if (qtVer) break;
      }
      if (parseInt(qtVer)<7 && confirm("Для просмотра видеофайлов рекомендуем установить QuickTime версии 7 или выше\nПрограмму можно скачать бесплатно: http://www.apple.com/quicktime/download/"))
        window.open("http://www.apple.com/quicktime/download/");
    }
    //else window.status='no quicktime movies on page';
  } catch (e) {}
}
setTimeout("qtCheck()", 1000);

function escapeHTML(s) {
  if (!s) return '';
  return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/'/g,'&#39;').replace(/"/g,'&quot;');
}

var win1251table="ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–— ™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕї";
var win1251cache=new Array();
function getWin1251Code(c) {
  if (win1251cache[c]) return win1251cache[c];
  if (c>0 && c<=127) {
    win1251cache[c]=c;
    return c;
  }
  else if (c>=0x410 && c<=0x44f) { // А-Яа-я
    win1251cache[c]=c-0x350;
    return c-0x350; // (0x410-0xc0)=0x350
  }
  else {
    var idx=win1251table.indexOf(String.fromCharCode(c));
    if (idx>=0) {
      win1251cache[c]=0x80+idx;
      return 0x80+idx;
    }
  }
  return 0;
}

function getUnicodeFromWin1251(c) {
  if (c>0 && c<=127) return c;
  if (c>=0xc0) return c+0x350;
  return win1251table.charCodeAt(c-0x80);
}

function checkWin1251(s) {
  if (!s) return '';
  var res='';
  for (var i=0; i<s.length; i++) {
    var c=getWin1251Code(s.charCodeAt(i));
    if (c>=32 && c<=255 || c==9 || c==10 /*|| c==13*/) {
      res+=s.charAt(i);
    }
  }
  return trim(res);
}

function trim(s) {
  return s.replace(/^\s+/, '').replace(/\s+$/, '');
}

function decodeURIComponentWin1251(s) {
  if (!s) return '';
  var us='';
  for (var i=0; i<s.length; i++) {
    var c=s.charAt(i);
    if (c=='%') {
      if ('u'==s.charAt(i+1)) {
        us+=String.fromCharCode(parseInt(s.substring(i+2, i+6), 16));
        i+=5;
      }
      else {
        us+=String.fromCharCode(getUnicodeFromWin1251(parseInt(s.substring(i+1, i+3), 16)));
        i+=2;
      }
    }
    else if (c=='+') us+=' ';
    else us+=c;
  }
  return us;
}

function encodeURIComponentWin1251(s) {
  if (!s) return '';
  var us='';
  for (var i=0; i<s.length; i++) {
    var c=getWin1251Code(s.charCodeAt(i));
    if (c>=32 && c<=255 || c==9 || c==10) {
      if (c==32) us+='+';
      else if (c<=127) us+=encodeURIComponent(s.charAt(i));
      else us+='%'+zeroPad(c.toString(16), 2);
    }
  }
  return us;
}


function setCookie(name, value, expire, domain, path) {
  if ( expire == null ) {
    expire = new Date();
    expire.setTime(expire.getTime()+2*365*24*3600*1000); // +2 years
  }
  document.cookie=name+"="+encodeURIComponentWin1251(value)
   +((expire==null) ? "" : ("; expires="+expire.toGMTString()))
   +((domain==null) ? "" : ("; domain="+encodeURIComponent(domain)))
   +((path==null) ? "" : ("; path="+encodeURIComponent(path)));
  return document.cookie;
}

function getCookie(name) {
  var cookies=document.cookie.split(/\s*;\s*/);
  for (var i=0;i<cookies.length;i++) {
    var pair=cookies[i].split("=");
    if (name==pair[0]) return decodeURIComponentWin1251(pair[1]);
  }
  return null;
}

function getParam(name) {
  var query = window.location.search + "";
  if (!query) return null;
  var qp=query.split(/\s*[\?&]\s*/);
  for (var i=0; i<qp.length;i++) {
    var pair=qp[i].split("=");
    if (name==pair[0]) return decodeURIComponentWin1251(pair[1]);
  }
  return null;
}

function activateActiveX() {
  try {
    if (navigator.appVersion.indexOf("MSIE")>=0) {
      var theObjects = document.getElementsByTagName("object");
      for (var i=0; i<theObjects.length; i++) {

        var attrc=theObjects[i].attributes;
        var ohtml='<object';
        for(var n=0; n<attrc.length; n++) {
          var a=attrc[n];
          if (a.nodeValue) ohtml+=' '+a.nodeName+'="'+a.nodeValue+'"';
        }
        ohtml+='>';

        var prmc=theObjects[i].childNodes;
        var ihtml='';
        var movieUrl=null;
        var escript=false;
        for(var n=0; n<prmc.length; n++) {
          var p=prmc[n];
          if (p.nodeName=='PARAM') {
            ihtml+='<param name="'+p.getAttribute('name')+'" value="'+p.getAttribute('value')+'">';
            if (p.getAttribute('name')=='movie') movieUrl=p.getAttribute('value');
            if (p.getAttribute('name')=='__escript') escript=true;
          }
          //else return;
        }
        if (movieUrl!=null && !escript) {
          var m=movieUrl.match(/^https?:\/\/(www\.)?(.+?)\//);
          var domain=location.hostname.match(/^(www\.)?(.+)$/);
          if (!m || m[2]==domain[2])
            theObjects[i].outerHTML=ohtml+ihtml+'</object>';
          //else
          //  status='mu='+movieUrl+' m[2]='+m[2]+' d[2]='+domain[2];
        }
      }
    }
  } catch (e) {}
}

// external docs

function showHiddenText(destElm, url) {
  if (typeof(destElm)=="string") destElm=document.getElementById(destElm);
  return loadDoc(url, doShowHiddenText, destElm);
}

function doShowHiddenText(destElm, htmlCode) {
  destElm.innerHTML=htmlCode;
}


// following code based on http://developer.apple.com/internet/webcontent/xmlhttpreq.html


function loadDoc(url, func, arg) {
  var xmlReq = false;
  // branch for native XMLHttpRequest object
  if(window.XMLHttpRequest) {
    try {
      xmlReq = new XMLHttpRequest();
    } catch(e) {
      xmlReq = false;
    }
  // branch for IE/Windows ActiveX version
  } else if(window.ActiveXObject) {
    try {
      xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        xmlReq = false;
      }
    }
  }
  if(xmlReq) {
    xmlReq.onreadystatechange = function() {
        // only if xmlReq shows "loaded"
        if (xmlReq.readyState == 4) {
          // only if "OK"
          if (xmlReq.status == 200) {
            // ...processing statements go here...
            func(arg, xmlReq.responseText, xmlReq.responseXML);
          } else if (xmlReq.status == 401) {
            window.location="/auth_required.htm";
          } else {
            alert("Загрузить информацию не удалось:\n" +
                 xmlReq.statusText);
          }
        }
      };
    xmlReq.open("GET", url, true);
    xmlReq.send("");
    return false;
  }
  return true;
}

// request img counter

var reqImg=new Array();
function requestImg(u) {
  var i=new Image();
  i.src=u;
  return reqImg.push(i);
}

function videoFLV(flvPath, width, height, preview) {
  if (!preview) preview='/video/flash/mfvideobg.jpg';
  flash('8', '/video/flash/flvplayer.swf', width, height+20, {'allowfullscreen':'true','FlashVars':'file='+flvPath+'&image='+preview+'&width='+width+'&height='+(height+20)+'&showicons=false&overstretch=true&showdownload=false&volume=100&type=flv'}, '<span style="background-color:yellow;padding:4px;">Для воспроизведения видео требуется Adobe Flash Player 8+</span>');
}

function videoMP4(mp4Path, width, height, preview) {
  if (!preview) preview='/i/videoframe.jpg';
  flash('10', '/i/jwplayer43.swf', width, height+20, {'allowfullscreen':'true','FlashVars':'file='+mp4Path+'&image='+preview+'&width='+width+'&height='+(height+20)+'&showicons=false&overstretch=true&showdownload=false&volume=100&type=video'}, '<span style="background-color:yellow;padding:4px;">Для воспроизведения видео требуется Adobe Flash Player 10+</span>');
}

function audioMP3(mp3Path, width, height) {
  if (!width) width=320;
  if (!height) height=20;
  flash('8', '/i/player_mp3_maxi.swf', width, height, {'FlashVars':'mp3='+mp3Path+'&width='+width+'&height='+height+'&volume=150&showvolume=1&bgcolor1=aaaaaa&bgcolor2=444444&slidercolor1=ffffff&slidercolor2=eeeeee&sliderovercolor=dddddd&buttonovercolor=dddddd'}, '<span style="background-color:yellow;padding:4px;">Для воспроизведения аудио требуется установить Adobe Flash Player 8+</span>');
}

var defaultFlashParams={'allowScriptAccess':'sameDomain','menu':'false','quality':'high','__escript':'true'};

function flash7(swf, width, height, parms, noflashHtml) {flash('7', swf, width, height, parms, noflashHtml);}
function flash8(swf, width, height, parms, noflashHtml) {flash('8', swf, width, height, parms, noflashHtml);}

function buildFlashHtml(version, swf, width, height, parms, noflashHtml, id) {
  var fpva=getFlashPlayerVersion2();
  var fpv=fpva[0];
  var fpvr=parseInt(version);
  if (noflashHtml && fpv<fpvr) {
    return noflashHtml;
  }
  else {
    if (!id) id='flash'+Math.round(Math.random()*1000000);
    var o='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+version+',0,0,0"'
      +(width?' width="'+width+'"':'')+(height?' height="'+height+'"':'')
      +' align="middle" id="'+id+'">'
      +'<param name="movie" value="'+swf+'" />';
    var e='<embed name="'+id+'" src="'+swf+'"'
      +(width?' width="'+width+'"':'')+(height?' height="'+height+'"':'')
      +' align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"';
    if (parms) {
      for(var p in parms) {
        o+='<param name="'+p+'" value="'+parms[p]+'" />';
        e+=' '+p+'="'+parms[p]+'"';
      }
    }
    for(var p in defaultFlashParams) {
      if (!parms || !parms[p]) {
        o+='<param name="'+p+'" value="'+defaultFlashParams[p]+'" />';
        e+=' '+p+'="'+defaultFlashParams[p]+'"';
      }
    }
    e+='></embed>';
    o+=e+'</object>';
    return o;
  }
}

function flash(version, swf, width, height, parms, noflashHtml, id) {
  document.write(buildFlashHtml(version, swf, width, height, parms, noflashHtml, id));
}

function makeVideo(elm) {
  var width=elm.getAttribute('width',2), height=parseInt(elm.getAttribute('height',2),10), src=elm.parentNode.getAttribute('href',2), preview=elm.getAttribute('src',2);
  //alert('w='+width+' h='+height+' src='+src);
  elm.parentNode.innerHTML=buildFlashHtml(8, '/i/jwplayer43.swf', width, height+20, {'allowfullscreen':'true','FlashVars':'file='+src+'&image='+preview+'&width='+width+'&height='+(height+20)+'&showicons=false&overstretch=true&showdownload=false&volume=100&type=video'}, '<span style="background-color:yellow;padding:4px;">Для воспроизведения видео требуется установить Adobe Flash Player 8+</span>');
}

function makeAudio(elm) {
  var width=elm.getAttribute('width',2), height=parseInt(elm.getAttribute('height',2),10), src=elm.parentNode.getAttribute('href',2), preview=elm.getAttribute('src',2);
  //alert('w='+width+' h='+height+' src='+src);
  elm.parentNode.innerHTML=buildFlashHtml(8, '/i/player_mp3_maxi.swf', width, height, {'FlashVars':'mp3='+src+'&width='+width+'&height='+height+'&volume=150&showvolume=1&bgcolor1=aaaaaa&bgcolor2=444444&slidercolor1=ffffff&slidercolor2=eeeeee&sliderovercolor=dddddd&buttonovercolor=dddddd'}, '<span style="background-color:yellow;padding:4px;">Для воспроизведения аудио требуется установить Adobe Flash Player 8+</span>');
}

function makeFlash(elm, ver) {
  var width=elm.getAttribute('width',2), height=parseInt(elm.getAttribute('height',2),10), src=elm.parentNode.getAttribute('href',2);
  if (!ver) ver=8;
  elm.parentNode.innerHTML=buildFlashHtml(ver, src, width, height, null, '<span style="background-color:yellow;padding:4px;">Для отображения флэш-ролика требуется установить Adobe Flash Player '+ver+'+</span>');
}

function getFlashPlayerVersion2() {
  // code (C) http://code.google.com/p/swfobject/
  var playerVersion = [0,0,0];
  var d = null;
  if (typeof navigator.plugins != "undefined" && typeof navigator.plugins["Shockwave Flash"] == "object") {
    d = navigator.plugins["Shockwave Flash"].description;
    if (d) {
      d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
      playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
      playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
      playerVersion[2] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
    }
  }
  else if (typeof window.ActiveXObject != "undefined") {
    var a = null;
    var fp6Crash = false;
    try {
      a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
    }
    catch(e) {
      try { 
        a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
        playerVersion = [6,0,21];
        a.AllowScriptAccess = "always";  // Introduced in fp6.0.47
      }
      catch(e) {
        if (playerVersion[0] == 6) {
          fp6Crash = true;
        }
      }
      if (!fp6Crash) {
        try {
          a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
        }
        catch(e) {}
      }
    }
    if (!fp6Crash && typeof a == "object") { // When ActiveX is disbled in IE, then "typeof a" returns "object", however it is "null" in reality, so something like "typeof a.GetVariable" will crash the script
      try {
        d = a.GetVariable("$version");  // Will crash fp6.0.21/23/29
        if (d) {
          d = d.split(" ")[1].split(",");
          playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
        }
      }
      catch(e) {}
    }
  }
  return playerVersion;
}

function writeCurrentLogin() {
  var t4cookie=getCookie("t4user"), t4usertitle=getCookie("t4usertitle");
  if (t4cookie && t4usertitle) {
    document.write("Здравствуйте, <a href='/t4/Registration' title='Настройки пользователя'>"+escapeHTML(t4usertitle)+"</a>!");
  }
  else {
    document.write("&nbsp;");
  }
}

function writeCurrentLoginEnter() {
  var t4cookie=getCookie("t4user"), t4username=getCookie("t4username");
  if (t4cookie && t4username) {
    document.write("<a href='/t4/Login?t4logout=yes'>Выход</a>");
  }
  else {
    document.write("<a href='/t4/Login'>Вход</a>");
  }
}
