function ajax_req() {

  var XMLHttpRequestObject = false;
  /*
  if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
  }*/

  if (window.XMLHttpRequest) { // Mozilla, Safari,...
      XMLHttpRequestObject = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
      try {
        XMLHttpRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
          XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
      }
    }
  return XMLHttpRequestObject;

}

var last = new Array();
var post  = new Array();
var now = new Array();
var bez_zvuku = false;


function check(mode,get,pink)
{
var request = ajax_req();

  if( typeof(get) == 'undefined' ){
    get = false;
  }

  if( typeof(pink) == 'undefined' ){
    pink = false;
  }

  if (request) {
    if (get) {
      request.open("GET", './ajax.php?mode=' + mode, true);
    } else {
      request.open("GET", './ajax.php?mode=' + mode + '&typ=ajax', true);
    }

    request.onreadystatechange = function()
    {
     if (request.readyState == 4 && request.status == 200) {
      if (get) {
        document.getElementById(mode).innerHTML = request.responseText;
        if (pink) {
          soundManager.play('cvak');
        }
        if (mode == 'minichat') {
          dolu('minichat');
        }
      } else {
        now[mode] =  request.responseText;
        //kvuli pink!
        now[mode] = now[mode].split(',');
        //                                      tady to je spesl refreshování pro lastposty a nic jinyho
        if ( (last[mode] != now[mode][0]) || ((post[mode] != now[mode][1]) && (mode == 'lastposts')) )  {
          //pink!
          var cvak=false;
          if (!bez_zvuku)  {
            if (post[mode] < parseInt(now[mode][1])) {
              if ( (post[mode]!=undefined) && (post[mode]!=null) )
                //soundManager.play('cvak');
                cvak=true;
                //alert('pink!');
            }
          }
          check(mode,true,cvak);
          last[mode] = now[mode][0];
          post[mode] = parseInt(now[mode][1]);
          //
        }
      }
      request = null;
     }
    }
    request.send(null);
   }
}


function delchat(id)
{
var request = ajax_req();

  if (request) {
    request.open("GET", './vlozit.php?mode=delchat&id='+id, true);


    request.onreadystatechange = function()
    {
     if (request.readyState == 4 && request.status == 200) {
       if (request.responseText)
         alert(request.responseText);
       else
         check('minichat');
      request = null;
     }
    }
    request.send(null);
   }
}


function dolu(el) {
  document.getElementById(el).scrollTop=document.getElementById(el).scrollHeight;
}
var clast=0;

function send() {
  if(document.f.t.value.length==0)
   return;
  //document.getElementById('save').style.display='inline';
  if (!document.f.t.value.match('^/'))
  document.getElementById('minichat').innerHTML += '<div><img src="./images/spinner.gif" style="vertical-align:middle;margin-right:2px;" alt="Odesílám" /><b>'+username+':</b> '+document.f.t.value.replace(/</g,"&lt;")+'</div>';
  dolu('minichat');

  document.f.t.disabled=true;
  document.f.p.disabled=true;

    var http = ajax_req();

  var url = "ajax.php?mode=minichat";
  var params = "text="+encodeURIComponent(document.f.t.value);
  http.open("POST", url, true);
  document.f.t.value='';

  //Send the proper header information along with the request
  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded;");
  http.setRequestHeader("Content-length", params.length);
  http.setRequestHeader("Connection", "close");

  http.onreadystatechange = function() {//Call a function when the state changes.
  	if(http.readyState == 4 && http.status == 200) {
  		//load(1);
      document.f.t.disabled=false;
      document.f.p.disabled=false;
      //document.getElementById('save').style.display='none';
      //load(1);
      check('minichat');
  		document.f.t.focus();
  		clearTimeout(t);
      t = setTimeout("check('minichat',true)",31000);
  	}
  	document.f.t.focus();
  }
  http.send(params);
}

var t;

function vote(n) {
  var bar = document.getElementById('vote_bar');
  var r1 = document.getElementById('vote_r1');
  var r2 = document.getElementById('vote_r2');
  clearTimeout(t);
  bar.style.width=((n-1)*25+2)+'px';
  if (n >= 5) {
    r1.style.display='none';
    r2.style.display='none';
    }
  else {
    r1.style.display='inline';
    r1.style.width=(99 - ((n-1)*25))+'px';
    r2.style.display='inline';
    }
  }

function vote_res() {
  t = setTimeout("vote_up()",1000);
  }

function vote_up() {
  var bar = document.getElementById('vote_bar');
  var r1 = document.getElementById('vote_r1');
  if (parseInt(bar.style.width) < 95) {
    bar.style.width = (parseInt(bar.style.width) + 5)+'px';
    r1.style.width = (parseInt(r1.style.width) - 5)+'px';
    t = setTimeout("vote_up()",20);
  } else {
    vote('5');
  }
}

function spoiler(id,tl) {
  if (document.getElementById('spoiler' + id).style.display == 'inline') {
  //skryti
    document.getElementById('spoiler' + id).style.display='none';
    tl.value="zobrazit »";
  } else {
  //zobrazeni
    document.getElementById('spoiler' + id).style.display='inline';
    tl.value="« skrýt";

      var spoil = new fx.Opacity('spoiler' + id, {
                                      duration: 450
                                    });
	    spoil.hide();
	    spoil.toggle();
  }
}


function sdilet_clanek(t) {
  window.open(t.href,'social','width=600, height=400, left='+((screen.width-600) / 2)+', top='+((screen.height-600) / 2)+',status=no,toolbar=no,resizable=no,location=no');
  return false;
}

function smazat() {
  return confirm('Opravdu to chceš smazat?');
}

function odhlaseni() {
  return confirm('Opravdu se chceš odhlásit?\nZtratíš tím všechny nepřečtené příspěvky.');
}

function req_clanky(div,uri) {

  var request = ajax_req();

  if (request) {
    document.getElementById(div).innerHTML = '<img style="position:absolute;width:16px;height:16px;border:1px solid #999;padding:1px;background:white;" src="/images/spinner.gif" alt="" />'+document.getElementById(div).innerHTML;
    //document.location.hash = uri.substring(2,uri.length-7);
    request.open("GET", uri, true);

    request.onreadystatechange = function()
    {
     if (request.readyState == 4 && request.status == 200) {

      document.getElementById(div).innerHTML = request.responseText;

      request = null;
     }
    }
    request.send(null);
  }
  return false;
}


//
//chlast a trava:
//

//Promenne:
var chlast='';  //prispevky, ktere pily
var huleni='';  //-''- hulily
//Pohyb pri opilosti:
var s=3;  //do strany skok o (px)
var m=42; //rozsah pohybu (px)
var v=1;  //nahoru/dolu skok o (px)
var n=20; //rozsah pohybu (px)

function getElementsByClassName(classname)  {
    node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

function blikat(p) {
  var barvy = new Array('black','#ff0000','#00ff00','#0000ff');
  for ( var i in huleni )
  {
      if (i=='iterate')  //co to je? Najednou to zacalo delat, musim casem vyresit, pac tohle je pekne blby!
        break;
      huleni[i].style.color=barvy[p];

  }
  if (p<(barvy.length-1))
    p=p+1;
  else
    p=0;
  setTimeout("blikat("+p+")",150);
}

function houpat(p,d,p1,d1) {
  var s=3; //do strany
  var m=42;//max
  var v=1;  //nahoru dolu
  var n=20; //max
  for ( var i in chlast )
  {
      if (i=='iterate')  //co to je? Najednou to zacalo delat, musim casem vyresit, pac tohle je pekne blby!
        break;
      chlast[i].style.paddingLeft=p+"px";
      chlast[i].style.paddingRight=(m-p)+"px";
      /*chlast[i].style.paddingTop=p1+"px";
      chlast[i].style.paddingBottom=(n-p1)+"px";*/  //zaokrouhlovani kvuli krajnim pozicim, delanym na 0.5px
      chlast[i].style.paddingTop=Math.floor(p1)+"px";
      chlast[i].style.paddingBottom=(n-Math.floor(p1))+"px";
  }

  //zpomaleni u okraje -
  if (p>(m-4) || p<4) {
    s=1;
  }
  else if (p>(m-10) || p<10) {
    s=2;
  }
  //

  if (p<m && p>0) {
    if (d==0)
      p=p+s;
    else
      p=p-s;
  } else {
    if (d==0) {
      d=1;
      p=p-s;
    }
    else {
      d=0;
      p=p+s;
    }
  }

  //zpomaleni u okraje |
  if (p1>(n-3) || p1<3) {
    v=0.5;
  }
  //

  if (p1<n && p1>0) {
    if (d1==0)
      p1=p1+v;
    else
      p1=p1-v;
  } else {
    if (d1==0) {
      d1=1;
      p1=p1-v;
    }
    else {
      d1=0;
      p1=p1+v;
    }
  }

  setTimeout("houpat("+p+","+d+","+p1+","+d1+")",80);
}


function box(id) {
  var i=0;
  while (document.getElementById('b'+i)) {
    if (i == id) {
      document.getElementById('b'+i).style.display='block';
      document.getElementById('bb'+i).style.textDecoration='underline';
      document.getElementById('bb'+i).style.color='white';
    }
    else {
      document.getElementById('b'+i).style.display='none';
      document.getElementById('bb'+i).style.textDecoration='none';
      document.getElementById('bb'+i).style.color='#fdd';
    }
    i++;
  }
  return false;
}


var isIE = navigator.appName.toLowerCase().indexOf('internet explorer')+1;
var isMac = navigator.appVersion.toLowerCase().indexOf('mac')+1;

function SoundManager(container) {
  // DHTML-controlled sound via Flash
  var self = this;
  this.movies = []; // movie references
  this.container = container;
  this.unsupported = 0; // assumed to be supported
  this.defaultName = 'default'; // default movie

  this.FlashObject = function(url) {
    var me = this;
    this.o = null;
    this.loaded = false;
    this.isLoaded = function() {
      if (me.loaded) return true;
      if (!me.o) return false;
      me.loaded = ((typeof(me.o.readyState)!='undefined' && me.o.readyState == 4) || (typeof(me.o.PercentLoaded)!='undefined' && me.o.PercentLoaded() == 100));
      return me.loaded;
    }
    this.mC = document.createElement('div');
    this.mC.className = 'movieContainer';
    with (this.mC.style) {
      // "hide" flash movie
      position = 'absolute';
      left = '-256px';
      width = '64px';
      height = '64px';
    }
    var html = ['<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"><param name="movie" value="'+url+'"><param name="quality" value="high"></object>','<embed src="'+url+'" width="1" height="1" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>'];
    if (navigator.appName.toLowerCase().indexOf('microsoft')+1) {
      this.mC.innerHTML = html[0];
      this.o = this.mC.getElementsByTagName('object')[0];
    } else {
      this.mC.innerHTML = html[1];
      this.o = this.mC.getElementsByTagName('embed')[0];
    }
    document.getElementsByTagName('div')[0].appendChild(this.mC);
  }

  this.addMovie = function(movieName,url) {
    self.movies[movieName] = new self.FlashObject(url);
  }

  this.checkMovie = function(movieName) {
    movieName = movieName||self.defaultName;
    if (!self.movies[movieName]) {
      self.errorHandler('checkMovie','Exception: Could not find movie',arguments);
      return false;
    } else {
      return (self.movies[movieName].isLoaded())?self.movies[movieName]:false;
    }
  }


  this.play = function(soundID,loopCount,noDebug,movieName) {
    if (self.unsupported) return false;
    movie = self.checkMovie(movieName);
    if (!movie) return false;
    if (typeof(movie.o.TCallLabel)!='undefined') {
      try {
        self.setVariable(soundID,'loopCount',loopCount||1,movie);
        movie.o.TCallLabel('/'+soundID,'start');
        if (!noDebug) writeDebug('soundManager.play('+self.getArgs(arguments)+')');
      } catch(e) {

      }
    }
  }

  this.setVariable = function(soundID,property,value,oMovie) {
    // set Flash variables within a specific movie clip
    if (!oMovie) return false;
    try {
      oMovie.o.SetVariable('/'+soundID+':'+property,value);
      // writeDebug('soundManager.setVariable('+self.getArgs(arguments)+')');
    } catch(e) {
      // d'oh

    }
  }


  // constructor - create flash objects

  if (isIE && isMac) {
    this.unsupported = 1;
  }

  if (!this.unsupported) {
    this.addMovie(this.defaultName,'soundcontroller.swf');
    // this.addMovie('rc','rubber-chicken-audio.swf');
  }

}


var soundManager = null;

function soundManagerInit() {
  soundManager = new SoundManager();
}

/*function im(t,id) {
  var i = document.getElementById(t+'-'+id);

  if (i.style.display=='none' || i.style.display=='')
    i.style.display='inline';
  else
    i.style.display='none';

  return false;
}*/

function imframe() {

    var objBody = document.getElementsByTagName("body").item(0);
    var objOverlay;
    this.show = function(im,uin) {

      clearTimeout(t);
      imageEffect.clearTimer();
      if (this.check())
        this.kill();
  		objOverlay = document.createElement("span");
  		objOverlay.setAttribute('id','msg');
  		objOverlay.style.top=(mouseY()-10)+'px';
  		objOverlay.style.left=(mouseX()-55)+'px';
  		objOverlay.className='jabfrm';

  		//objOverlay.onmouseout = function() {clearTimeout(t);t=setTimeout("im.fadeout(3000)",2000);}
  		//objOverlay.onmouseover = function() {clearTimeout(t);imageEffect.clearTimer();imageEffect.now=1;imageEffect.increase();}

  		objOverlay.innerHTML = im+':<input type="text" readonly="readonly" size="'+(uin.length+1)+'" onclick="select();focus();" value="'+uin+'" /> <a href="#" onclick="im.fadeout(450,true);return false;">X</a>';

  		objBody.appendChild(objOverlay);

      imageEffect = new fx.Opacity(objOverlay, {
                                      duration: 450,
                                      onComplete: function() {
                                        objOverlay.onmouseout = function() {
                                          clearTimeout(t);
                                          t=setTimeout("im.fadeout(3000)",2000);
                                        }
                                        objOverlay.onmouseover = function() {
                                          clearTimeout(t);
                                          imageEffect.clearTimer();
                                          imageEffect.now=1;
                                          imageEffect.increase();
                                        }
                                      }
                                    });
	    imageEffect.hide();
	    imageEffect.toggle();

	    t=setTimeout("im.fadeout(5000)",3000);
	    return false;
    }

    this.check = function() {
      if (document.getElementById("msg"))
        return true;
      return false;
    }

    this.fadeout = function(dur,force) {
      if (this.check()) {
        clearTimeout(t);
        imageEffect.clearTimer();
        if (force) {
          objOverlay.onmouseout=null;
          objOverlay.onmouseover=null;
        }
        objOverlay = document.getElementById("msg");
        imageEffect = new fx.Opacity(objOverlay, { duration: dur, onComplete: function() { im.kill(); } });
		    imageEffect.toggle();
      }
    }

    this.kill = function() {
      objOverlay = document.getElementById("msg");
      objBody.removeChild(objOverlay);
    }
  }

var evt;
  //from javascript.about.com, ale mrte upraveno
  function mouseX() {
    var e;
    e = e || window.event;
    e = e || evt;
    //e = evt;
    if (e) {
      if (e.pageX)
        return e.pageX;
      if (e.clientX)
       return e.clientX + (document.documentElement.scrollLeft ?
       document.documentElement.scrollLeft :
       document.body.scrollLeft);
    }
    return 0;
  }
  function mouseY() {
    var e;
    e = e || window.event;
    e = e || evt;
    //e = evt;
    if (e) {
      if (e.pageY)
        return e.pageY;
      if (e.clientY)
       return e.clientY + (document.documentElement.scrollTop ?
       document.documentElement.scrollTop :
       document.body.scrollTop);
    }
    return 0;
  }

function init() {
  im = new imframe();
  initLightbox();
  document.onmousedown = getXY;
}

function getXY(e) {
  evt =(window.Event) ? e : event;
}

//window.onload = init;

function text_counter(pole,vypis,delka,barvy) {
  //var max = 450;
  var sign = document.getElementById(pole);
  var sigc = document.getElementById(vypis);
  var style='font-weight:bold;';
  if (barvy) {
    var hex;
    if (sign.value.length>(delka))
      hex='f00';
    else if (sign.value.length>(delka-10))
        hex = ((14-(delka-sign.value.length)).toString(16)) + ((delka-sign.value.length).toString(16)) + '0';
    else
      hex='0a0';
    
    style+='color:#'+hex+';';
  }
  
  sigc.innerHTML='Napsal jsi <span style="'+style+'">'+sign.value.length+'</span> znaků z '+delka;
}

function showminichat() {
  document.write(
    '<div style="overflow:auto;height:135px;" id="minichat">'+
      '<div style="text-align:center;margin:55px auto 0 auto; padding:5px;border: 1px solid #999; width:60%;"><img src="./images/spinner.gif" style="vertical-align:middle;" alt="Nahrávám" /> Otevírám kecálka&hellip;</div>'+
    '</div>'+
    '<form action="#" onsubmit="send();return false;" name="f">'+
      '<input type="text" name="t" size="22" />'+
      '<input type="submit" name="p" value="Poslat" /><img src="./images/spinner.gif" id="save" style="vertical-align:middle;margin-left:2px;display:none;width:16px;height:16px" alt="Nahrávám" />'+
    '</form>'+
    '<a title="Otevřít chat - Hlavní místnost" href="#" onclick="window.open(\'./mistnost.php?id=1\', \'order\', \'width=800, height=600, resizable=no, left=\' + (screen.width/2-400) + \', top=\' + (screen.height/2-300));return false;">Otevřít plnohodnotný chat</a>'
    );
    setInterval("check('minichat')",15000);  //každých 15s kontrolovat chat
    check('minichat');                       //zkontrolovat po otevření: aby se chat zobrazil
}

function soupat(id) {
    reHeight = new fx.Height(id, { duration: 350 });
		reHeight.toggle();
		return false;
 }
 
function mod_vote(v,p) {
  var request = ajax_req();
  
  if((v!=1 && v!=2) || !p) {
    alert('Chybné volání');
    return false;
  }

  if (request) {
    request.open("GET", '/ajax.php?mode=post_rank&p='+p+'&v='+v, true);


    request.onreadystatechange = function()
    {
     if (request.readyState == 4 && request.status == 200) {
       if (request.responseText)
         alert(request.responseText);
       else {
         var text;
         if (v==1)
          text='Kravina';
         else if (v==2)
          text='Dobrý příspěvek';
         $('mod_vote-'+p).innerHTML='<b>'+text+'</b>';         
      }
      request = null;
     }
    }
    request.send(null);
   }
  return false;
}