var CurPlay;

var UpdateRadioPlayCallback = Prototype.emptyFunction;

// pula radyj z ktorych jest losowane domyslnie rozwiniete radio na SG
var CurRadios = [36,37,38,39,40,41];
var CurRadio = 41;
CurRadio = CurRadios[Math.floor(Math.random()*CurRadios.length)];
var FirstRun = 1;

function OpenPlayer(s) { // 468 bez shoutboksow, 675 z
  window.open('/play,'+s, "RMFplayerWindow", 'width=468,height=512,menubar=no,toolbar=no,location=no,scrollbars=no,resizable=no,status=no');
}

function DoSearch() {
  if ($F('s').strip()!='') {
    window.location = '/?p=search&'+$('searchform').serialize();
  }
}

function N2E(s) {
  return s===null ? '' : s;
}

function DoKoncertySearch() {
  var dpocz=$F('kyear')+'-'+$F('kmonth')+'-'+$F('kday');
  window.location = '/?p=koncerty&d=search&data_pocz='+dpocz+'&q='+$F('q')+'&wykonawca='+N2E($F('cwyko'))+'&opis='+N2E($F('copis'))+'&miejsce='+N2E($F('cmiej'))+'&miasto='+N2E($F('cmias'));
}

function DoUserSearch() {
  if ($F('uname').strip()!='') {
    $('userloader').show();
    new Ajax.Request('/ajax.html', {
      method: 'get',
      parameters: { what: 'user', q: $F('uname').strip() },
      onComplete: function (transport) {
        $('userloader').hide();
        var r = transport.responseJSON;
        var text = r.slice(0,20).collect(function(u) {return '<DIV><A HREF="/?p=profil&uid='+u.id+'">'+u.name+'</A></DIV>';}).join('');
        var extra = r.length>20 ? '<DIV>...</DIV>' : '';
        $('usersearchresults').update(text==''?'brak':(text+extra));
      }
     });
   }
}

function SendComment() {
  if ($F('comm').strip()!='') {
    $('kontaktformmsg').update('Proszę czekać...');
    new Ajax.Request('contact.html', {
      method: 'post',
      parameters: { text: $F('comm'), sig: $F('sig') },
      onComplete: function (transport) {
        $('commform').reset();
        $('kontaktformmsg').update('');
        $('ContactPage').hide();
      }
     });
   }
}

function PrettyName(s) {
  return escape(s.replace(/[ \/']/g,'-').replace(/[^a-zA-Z0-9\-]/g,'').toLowerCase());
}

function ChangeBigPhoto() {
  XLog('ChangeBigPhoto()');
  $('bigphotowait').show();
  //$('starlogo').hide();
  //$('bigphotoname').hide();
  new Ajax.Request('ajax.html', {
    method: 'post',
    parameters: { what: 'bigphoto' },
    onComplete: function () {
      XLog('ChangeBigPhoto() - ajax oncomplete');
      $('bigphotowait').hide();
    },
    onSuccess: function (transport) {
      XLog('ChangeBigPhoto() - ajax onsuccess');
      var r = transport.responseJSON;

      if (document.images) {
        pic = new Image(368,244);
        pic.src = r.foto;
      }

      var prettyname = PrettyName(r.name);
      var link = '<A HREF="/biografia-'+prettyname+','+r.id+'">';
      var text = link+'<IMG SRC="'+r.foto+'" WIDTH=368 HEIGHT=244 alt="'+r.name+'"></A><DIV STYLE="background-color:#182738;padding:8px;"><DIV STYLE="float:right"><A TITLE="Zmień" HREF="#" onClick="ChangeBigPhoto(); return false;"><IMG SRC="/img/yellow-arrow-big.gif"></A></DIV><SPAN ID="bigphotoname">'+link+r.name+'</A></SPAN><SPAN STYLE="display:none" ID=bigphotowait> <IMG SRC="img/load1.gif"></SPAN></DIV></DIV>';

      if (1) new Effect.Opacity('bigphoto', {
        delay:0.6, duration:1.3, from:1.0, to:0.0,
        afterFinish: function(obj){
          $('bigphoto').update(text);
          new Effect.Opacity($('bigphoto'), {
            delay:0.1, duration:1.2, from:0.0, to:1.0
          });
        }
      });
    }
  });
}

function UpdateDesc(rid) {
  XLog('UpdateDesc('+rid+')');
  if (FirstRun==1) {
    FirstRun = 0;
    XLog('UpdateDesc: FirstRun');
    //$('pvtitletext').show();
    $('pvallblock').show();
  }
  CurRadio = rid;
  //$('pvradio').update('<A HREF="/radio,'+rid+'">'+RadioNames[rid]+'</A>');
  $('pvlogo').update('<img src="img/logos112/'+RadioIDNames[rid]+'.jpg" width=112 STYLE="margin-top:7px;" height=83>');
  //$('pvopis').update(RadioTexts[rid]);
}

function GetPlayInfo(rid) {
  var ret = { status:0 };
  ret.radio = RadioNames[rid] || '';
  ret.radioidname = RadioIDNames[rid] || '';
  ret.logo = '<IMG STYLE="margin-left:8px;" SRC="/img/logos85/'+RadioIDNames[rid]+'.jpg">';
  
  CurRadio = rid;
  if (CurPlay==undefined) return ret;
  
  var c = CurPlay['radio'+rid];
  if (c==undefined) return ret;

  var name = c.name;
  var pretty = PrettyName(name);
  var plytaname = c.plyta.truncate(50);
  var rok = c.rok;
  var plink1 = plink2 = '';
  if (parseInt(rok)>=1960) rok = '<A HREF="/year,'+rok+'">'+rok+'</A>';
  if (c.duza_biografia==1) {
    name = '<A HREF="/biografia-'+pretty+','+c.id_autor+'">'+name+'</A>';
    plink1 = '<A HREF="/bio,'+c.id_autor+',ply,'+c.id_plyta+'">';
    plink2 = '</A>';
  }
  
  ret.autor = name;
  ret.tytul = c.utwor
  ret.rok = c.rok;
  ret.plyta = plytaname;

  var dir = Math.floor(c.id_plyta/1000);
  if (c.id_plyta!='') {
    var covimg = plink1+'<img class="border1" width=100 height=100 src="http://doc.rmf.pl/media/img_muzyka/plyta/'+dir+'/'+c.id_plyta+'.jpg">'+plink2;
  } else {
    var covimg = '<img class="border1" src="/img/zaslepka.jpg" width=100 height=100>';
    if (rid==57) { //muzzo
      if (c.id_utwor!='') {
    	var dir = Math.floor(c.id_utwor/1000);
   	    var covimg = '<img class="border1" width=100 height=100 src="http://doc.rmf.pl/media/img_muzyka/utwor/'+dir+'/'+c.id_utwor+'.jpg">';
      } else {
        var covimg = '<img class="border1" src="img/p/zaslepka-muzzo.jpg" width=100 height=100>';
      }
    }
  }
  ret.cover = covimg;
  ret.status = 1;
  return ret;
}

function UpdatePlay(rid) {
  XLog('UpdatePlay('+rid+')');
  if (FirstRun==1) {
    FirstRun = 0;
    XLog('UpdatePlay: FirstRun');
    //$('pvtitletext').show();
    $('pvallblock').show();
  }

  CurRadio = rid;
  if (CurPlay==undefined) { XLog('<SPAN STYLE="color:red">UpdatePlay(): returning because of CurPlay==undefined</SPAN>'); return; }
  var c = CurPlay['radio'+rid];
  if (c==undefined) { XLog('<SPAN STYLE="color:red">UpdatePlay(): returning because of c==undefined</SPAN>'); return; }

  var name = c.name;
  var pretty = PrettyName(name);
  var plytaname = c.plyta.truncate(50);
  var rok = c.rok;
  var plink1 = plink2 = '';
  if (parseInt(rok)>=1960) rok = '<A HREF="/year,'+rok+'">'+rok+'</A>';
  if (c.duza_biografia==1) {
    name = '<A HREF="/biografia-'+pretty+','+c.id_autor+'">'+name+'</A>';
    plink1 = '<A HREF="/bio,'+c.id_autor+',ply,'+c.id_plyta+'">';
    plink2 = '</A>';
  }
  //$('pvradio').update('<A HREF="/radio,'+rid+'">'+RadioNames[rid]+'</A>');
  $('pvautor').update(name);
  $('pvtytul').update(c.utwor);
  //$('pvplyta').update(plink1+plytaname+plink2);
  //$('pvrok').update(rok);

  var dir = Math.floor(c.id_plyta/1000);
  if (c.id_plyta!='') {
    var covimg = plink1+'<img class="border1" width=100 height=100 src="http://doc.rmf.pl/media/img_muzyka/plyta/'+dir+'/'+c.id_plyta+'.jpg">'+plink2;
  } else {
    var covimg = '<img class="border1" src="/img/zaslepka.jpg" width=100 height=100>';
    if (rid==57) { //muzzo
      if (c.id_utwor!='') {
    	var dir = Math.floor(c.id_utwor/1000);
   	    var covimg = '<img class="border1" width=100 height=100 src="http://doc.rmf.pl/media/img_muzyka/utwor/'+dir+'/'+c.id_utwor+'.jpg">';
      } else {
        var covimg = '<img class="border1" src="img/p/zaslepka-muzzo.jpg" width=100 height=100>';
      }
    }
  }
  //$('pvcover').update(covimg);
}

function UpdateBoth(rid) {
  UpdateDesc(rid);
  UpdatePlay(rid);
}

function UpdatePlaying() {
  XLog('UpdatePlaying()');
  //$('playingload').show();
  new Ajax.Request('/stacje/ajax_playing_main.txt', {
    method: 'get',
    parameters: { c: Math.random() },
    onComplete: function () {
      XLog('UpdatePlaying: Ajax.Request onComplete');
      //$('playingload').hide();
    },
    onSuccess: function (transport) {
      XLog('UpdatePlaying: Ajax.Request onSuccess start');

      CurPlay = eval('('+transport.responseText+')');
/*
      CurPlay.radio1.name = 'U2';
      CurPlay.radio1.id_autor = 275;
      CurPlay.radio1.utwor = '';
      CurPlay.radio1.id_plyta = '';
      CurPlay.radio1.plyta = '';
      CurPlay.radio1.rok = '';
*/
      if (CurPlay==undefined) {
        XLog('<SPAN STYLE="color:red">UpdatePlaying: Ajax.Request onSuccess - CurPlay==undefined</SPAN>');
        // hmm?
        UpdatePlay(CurRadio);
        return;
      }

      //XLog('UpdatePlaying: Ajax.Request onSuccess part 1');
      //XLog('CurPlay = '+Object.toJSON(CurPlay));

      for (var n in CurPlay) {
        if (n.substr(0,5)!='radio') continue;
        XLog('UpdatePlaying parsing CurPlay: '+n+' start');
        var ss = a1 = a2 = '';
        var pretty = PrettyName(CurPlay[n].name);
        if (CurPlay[n].duza_biografia==1) {
          a1 = '<A idr="'+n.substr(5,3)+'" HREF="/biografia-'+pretty+','+CurPlay[n].id_autor+'">';
          a2 = '</A>';
        }
        ss += a1 + CurPlay[n].name + a2;
        if ($(n+'autor')) {$(n+'autor').update(ss);} 
      }

      XLog('UpdatePlaying: Ajax.Request onSuccess part 2');

      //UpdatePlay(CurRadio);
    }
  });
}

function UpdatePlayingCat() {
  XLog('UpdatePlayingCat()');
  //$('playingload').show();
  new Ajax.Request('/stacje/ajax_playing_main.txt', {
    method: 'get',
    parameters: { c: Math.random() },
    onComplete: function () {
      XLog('UpdatePlayingCat: Ajax.Request onComplete');
      //$('playingload').hide();
    },
    onSuccess: function (transport) {
      XLog('UpdatePlayingCat: Ajax.Request onSuccess start');

      CurPlay = eval('('+transport.responseText+')');
      if (CurPlay==undefined) return;

      for (var n in CurPlay) {
        var ss = a1 = a2 = '';
        var cpn = CurPlay[n];
        if (cpn.duza_biografia==1) {
          a1 = '<A HREF="/bio,'+cpn.id_autor+'">';
          a2 = '</A>';
        }
        ss += a1 + '<b>' + cpn.name + '</b>' + a2 + (cpn.name!='' && cpn.utwor!='' ? ': ' : '')+'<span class="radiolist-tytul">'+cpn.utwor.truncate(44-cpn.name.length)+'</span>';
        if ($(n+'autor')!=null) {
          $(n+'autor').update(ss=='' ? '' : '<!--teraz: -->'+ss);
          var dir = Math.floor(cpn.id_plyta/1000);
          if (cpn.id_plyta=='') {
            var covimg = '<img class="border1" src="/img/zaslepka.jpg" width=100 height=100>';
            if (n=='radio57') { //muzzo
              if (cpn.id_utwor!='') {
    	        var dir = Math.floor(cpn.id_utwor/1000);
   	            var covimg = '<img class="border1" width=100 height=100 src="http://doc.rmf.pl/media/img_muzyka/utwor/'+dir+'/'+cpn.id_utwor+'.jpg">';
              } else {
                var covimg = '<img class="border1" src="img/p/zaslepka-muzzo.jpg" width=100 height=100>';
              }
            }
          } else {
            var covimg = a1+'<img class="border1" width=100 height=100 src="http://doc.rmf.pl/media/img_muzyka/plyta/'+dir+'/'+cpn.id_plyta+'.jpg">'+a2;
          }
          $(n+'cover').update(covimg);
          var pozniej = cpn.next.slice(0,7).collect(function(n) { return (n.duza_biografia==1) ? ('<A HREF="/bio,'+n.id_autor+'">'+n.name.strip()+'</A>') : n.name.strip(); }).uniq().join(', ');
          $(n+'next').update(pozniej=='' ? '' : '<!--później: -->'+pozniej+'');
        }
      }
    }
  });
}

function UpdateRadioPlay() {
  var rid = CurRadio;
  XLog('UpdateRadioPlay('+rid+')');
  $('playingload').show();
  new Ajax.Request('/stacje/stacje_gramy_'+rid+'.txt', {
    method: 'get',
    onComplete: function () {
      XLog('UpdateRadioPlay: Ajax.Request onComplete');
      $('playingload').hide();
    },
    onSuccess: function (transport) {
      XLog('UpdateRadioPlay: Ajax.Request onSuccess start');
      var xThisPlay = eval('('+transport.responseText+')');
      if (xThisPlay==undefined) {
        XLog('<SPAN STYLE="color:red">UpdateRadioPlay: Ajax.Request onSuccess - xThisPlay==undefined</SPAN>');
      } else {
        var ThisPlay = xThisPlay.teraz;
        XLog('UpdateRadioPlay: Ajax.Request onSuccess - ThisPlay OK');

	var name = ThisPlay.wyk;
	var plytaname = ThisPlay.ply.truncate(70);
	var rok = ThisPlay.rok;

    if (!Object.isUndefined(UpdateRadioPlayCallback) && Object.isFunction(UpdateRadioPlayCallback)) UpdateRadioPlayCallback(ThisPlay);
    
	var plink1 = plink2 = '';
	if (parseInt(rok)>=1960) rok = '<A HREF="/year,'+rok+'">'+rok+'</A>';
	if (ThisPlay.d_b==1) {
	  name = '<A HREF="/bio,'+ThisPlay.id_wyk+'">'+name+'</A>';
	  plink1 = '<A HREF="/bio,'+ThisPlay.id_wyk+',ply,'+ThisPlay.idp+'">';
	  plink2 = '</A>';
	}
	$('pvautor').update(name);
	$('pvtytul').update(ThisPlay.tyt);
	$('pvplyta').update(plink1+plytaname+plink2);
	$('pvrok').update(rok);

    if (ThisPlay.idp!='') {
	  var dir = Math.floor(ThisPlay.idp/1000);
	  var covimg = plink1+'<img class="border1" width=100 height=100 src="http://doc.rmf.pl/media/img_muzyka/plyta/'+dir+'/'+ThisPlay.idp+'.jpg">'+plink2;
    } else {
      if (rid==57) { //muzzo
        if (ThisPlay.idu!='') {
    	  var dir = Math.floor(ThisPlay.idu/1000);
   	      var covimg = '<img class="border1" width=100 height=100 src="http://doc.rmf.pl/media/img_muzyka/utwor/'+dir+'/'+ThisPlay.idu+'.jpg">';
        } else {
          var covimg = '<img class="border1" src="img/p/zaslepka-muzzo.jpg" width=100 height=100>';
        }
      } else {
         var covimg = '<img class="border1" src="img/zaslepka.jpg" width=100 height=100>';
      }
    }
	$('pvcover').update(covimg);
      }
    }
  });

}



function UpdateRadioPlayAjax() {  // OLD + OBSOLETE version
  var rid = CurRadio;
  XLog('UpdateRadioPlayAjax('+rid+')');
  $('playingload').show();
  new Ajax.Request('ajax.html', {
    method: 'post',
    parameters: { what: 'playing', id: rid, c: Math.random() },
    onComplete: function () {
      XLog('UpdateRadioPlay: Ajax.Request onComplete');
      $('playingload').hide();
    },
    onSuccess: function (transport) {
      XLog('UpdateRadioPlay: Ajax.Request onSuccess start');
      var xThisPlay = transport.responseJSON;
      if (xThisPlay==undefined) {
        XLog('<SPAN STYLE="color:red">UpdateRadioPlay: Ajax.Request onSuccess - xThisPlay==undefined</SPAN>');
      } else {
        var ThisPlay = xThisPlay['radio'+rid];
        XLog('UpdateRadioPlay: Ajax.Request onSuccess - ThisPlay OK');

	var name = ThisPlay.name;
	var plytaname = ThisPlay.plyta.truncate(70);
	var rok = ThisPlay.rok;

    if (!Object.isUndefined(UpdateRadioPlayCallback) && Object.isFunction(UpdateRadioPlayCallback)) UpdateRadioPlayCallback(ThisPlay);
    
	var plink1 = plink2 = '';
	if (parseInt(rok)>=1960) rok = '<A HREF="/year,'+rok+'">'+rok+'</A>';
	if (ThisPlay.duza_biografia==1) {
	  name = '<A HREF="/bio,'+ThisPlay.id_autor+'">'+name+'</A>';
	  plink1 = '<A HREF="/bio,'+ThisPlay.id_autor+',ply,'+ThisPlay.id_plyta+'">';
	  plink2 = '</A>';
	}
	$('pvautor').update(name);
	$('pvtytul').update(ThisPlay.utwor);
	$('pvplyta').update(plink1+plytaname+plink2);
	$('pvrok').update(rok);

    if (ThisPlay.id_plyta!='') {
	  var dir = Math.floor(ThisPlay.id_plyta/1000);
	  var covimg = plink1+'<img class="border1" width=100 height=100 src="http://doc.rmf.pl/media/img_muzyka/plyta/'+dir+'/'+ThisPlay.id_plyta+'.jpg">'+plink2;
    } else {
      if (rid==57) { //muzzo
        if (ThisPlay.id_utwor!='') {
    	  var dir = Math.floor(ThisPlay.id_utwor/1000);
   	      var covimg = '<img class="border1" width=100 height=100 src="http://doc.rmf.pl/media/img_muzyka/utwor/'+dir+'/'+ThisPlay.id_utwor+'.jpg">';
        } else {
          var covimg = '<img class="border1" src="img/p/zaslepka-muzzo.jpg" width=100 height=100>';
        }
      } else {
         var covimg = '<img class="border1" src="img/zaslepka.jpg" width=100 height=100>';
      }
    }
	$('pvcover').update(covimg);
      }
    }
  });

}


function LoadRecord(divid,recid) {
  $(divid).toggle();
}

function ShowAllRecords(id) {
  $(id).select('.muzykabioplytautwory').invoke('show');
}

function HideAllRecords(id) {
  $(id).select('.muzykabioplytautwory').invoke('hide');
}

function ShowAllSongRecords(id) {
  $(id).select('.muzykabioutworyplyty').invoke('show');
}

function HideAllSongRecords(id) {
  $(id).select('.muzykabioutworyplyty').invoke('hide');
}

function ShowContact() {
  $('ContactPage').show();
}


function Pad2(n) {
  return n<10 ? '0'+n : n;
}

function XLog(s) {
  if (DoLog) {
    cdt = new Date();
    ln = Pad2(cdt.getHours()) + ':' + Pad2(cdt.getMinutes()) + ':' + Pad2(cdt.getSeconds()) + ' ' + s + '<BR>';
    if (window.console) console.log(ln);
    $('logger').insert({top:ln});
  }
}

function Mobi(eid,prefix,flashid,idmono,idpoli,idmp3) {
  XLog('Mobi('+eid+','+prefix+','+flashid+','+idmono+','+idpoli+','+idmp3+')');
  $('mobi').hide();
  var url = 'http://www.mobila.pl/odsluchaj.php?redirect=1&src=';
  var txt = '<DIV STYLE="float:right; margin:0px;"><A HREF="#" onClick="$(\'mobi\').hide();mp3Stop(\''+flashid+'\',\'mobiplay1\',\''+url+'\');mp3Stop(\''+flashid+'\',\'mobiplay2\',\''+url+'\');return false;">X</A></DIV>';
  if (idpoli>0) {
    txt += '<DIV CLASS=mobiblock>'+getPlayer('dplayer','mobiplay1',url+idpoli)+' Jeśli chcesz pobrać dzwonek <B>POLI</B>,<br>wyślij SMS o treści <B>AA'+prefix+'.0'+idpoli+'</B><br>na numer <B>7365</B><br>(koszt 3 zł netto / 3,66 zł brutto)</DIV>';
  }
  if (idmp3>0) {
    txt += '<DIV CLASS=mobiblock>'+getPlayer('dplayer','mobiplay2',url+idmp3)+' Jeśli chcesz pobrać dzwonek <B>MP3</B>,<br>wyślij SMS o treści <B>AA'+prefix+'.0'+idmp3+'</B><br>na numer <B>7570</B><br>(koszt 5 zł netto / 6,10 zł brutto)</DIV>';
  }
  txt += '<DIV CLASS=mobiblock>Usługa dostępna w sieciach:<br>Orange, Plus, Era, Play, Heyah, Sami swoi</DIV><DIV CLASS=mobiblock><A HREF="http://www.regulaminy.pl/regulamin/regulamin-uslugi-pobieranie-obiektow-dla-telefonow-komorkowych/r,5/" TARGET="_blank">regulamin <IMG ALT="" SRC="/img/yellow-arrow.gif"></A> | <A HREF="mailto:sms@mobila.pl">reklamacje <IMG ALT="" SRC="/img/yellow-arrow.gif"></A></DIV>';
  var offs = $(eid).cumulativeOffset();
  XLog('cumulative offset: '+offs.toJSON());
  $('mobi').setStyle({'width':'248px','height':'178px','left':(Math.max(8,offs.left-270))+'px','top':(offs.top+5)+'px'}).update(txt).show();
}

function ShowLogos() {
  var ajdisy = RadioIDs.compact().sortBy(function(s) { return Math.random(); });
  //XLog(RadioIDs.inspect());
  XLog('ShowLogos() called'); 
  var txt = '';
  $('logaxcontainer').show();
  for (var i=1; i<=3; i++) {
    //XLog(ajdisy[i]);
    txt += '<A TITLE="'+RadioNames[ajdisy[i]]+'" HREF="/radio,'+ajdisy[i]+'"><IMG WIDTH=112 HEIGHT=83 SRC="/img/logos112/'+RadioIDNames[ajdisy[i]]+'.jpg"></A> ';
  }
  $('logax').update(txt);
  XLog('ShowLogos() finished '); 
}

function GenAjax(blockid, typ,typid,offset,limit) {
  //return "To jest dynamicznie wygenerowana strona: "+' | '+typ+' | '+typid+' | '+offset+' | '+limit+'<BR>'+Math.random();
  XLog('GenAjax('+typ+','+typid+','+offset+','+limit+')');
  new Ajax.Request('ajaxgen.html?c='+Math.random(), {
    method: 'post',
    parameters: $H({ what: typ, offset: offset, limit: limit }).merge(typid),
    onComplete: function () {
      XLog('GenAjax: Ajax.Request onComplete');
      if (typ=='radiorecords') MarkFavouriteRecords();
    },
    onSuccess: function (transport) {
      XLog('GenAjax: Ajax.Request onSuccess');
      XLog('Responsetext: '+transport.responseText);
      $(blockid).update(transport.responseText);
      if (typ=='concerts' && Config.Logged==1) ShowFavKoncerty();
    }
  });
}

function LoadNextPlay(id) {
  XLog('LoadNextPlay('+id+')');
  $('nextplayshow').update('<IMG SRC="/img/load1.gif">');
  new Ajax.Request('ajax.html', {
    method: 'get',
    parameters: { what: 'nextplay', id: id, c: Math.random() },
    onComplete: function () {
      $('nextplayshow').update('');
    },
    onFailure: function () {
      $('nextplayshow').update(':(');
    },
    onSuccess: function (transport) {
      var res = transport.responseJSON;
      Object.keys(res).each(function(s){ 
        rrr = '<SPAN CLASS="nextplay-time">'+res[s].start_time.truncate(5,'')+'</SPAN> <SPAN CLASS="nextplay-tytul">'+res[s].tytul+'</SPAN>';
        $(s).update(rrr).show();
      });
    }
  });
}

// *************** ulubione plyty

function MarkFavouriteRecords() {
  $$('.FavRecord').each(function(s) {
    var rid = s.readAttribute('RECORDID');
    s.update(getRecordFavoriteHTML(rid));
  });
}

// *************** cookies

function isFavorite(id) {
  var mm = Config.MM_Favorites;
  if (mm==null) return false;
  return mm.split(',').include(id);
}
function addFavorite(id) {
  if (isFavorite(id)) return;
  Config.MM_Favorites = Config.MM_Favorites+','+id;
  new Ajax.Request('/useraction.html', {   
    method: 'get',
    parameters: { 'a':'addartist', 'id':id }
  }); 
}
function setFavorites(ids) {
  Config.MM_Favorites = ids;
  new Ajax.Request('/useraction.html', {   
    method: 'get',
    parameters: { 'a':'setartists', 'ids':ids }
  }); 
}
function delFavorite(id) {
  var mm = Config.MM_Favorites;
  if (mm==null) return false;
  mm = mm.split(',').without(id).join(',');
  Config.MM_Favorites = mm;
  new Ajax.Request('/useraction.html', {   
    method: 'get',
    parameters: { 'a':'delartist', 'id':id }
  }); 
}
function getFavoriteHTML(id) {
  return isFavorite(id) ? '<A HREF="#" onClick="delFavorite('+id+');$(\'isfav\').update(getFavoriteHTML('+id+')).show();return false;" TITLE="Usuń z ulubionych"><IMG onMouseOver="this.src=\'/img/btn_remove7.gif\'" onMouseOut="this.src=\'/img/btn_remove5.gif\'" STYLE="border:0px;" SRC="/img/btn_remove5.gif"></A>':'<A HREF="#" onClick="addFavorite('+id+');$(\'isfav\').update(getFavoriteHTML('+id+')).show();return false;" TITLE="Dodaj do ulubionych"><IMG STYLE="border:0px;" SRC="/img/btn_add7.gif"></A>';
}

function isConcertFavorite(id) {
  var mm = Config.MM_ConcertFavorites;
  if (mm==null) return false;
  return mm.split(',').include(id);
}
function addConcertFavorite(id) {
  if (isConcertFavorite(id)) return;
  Config.MM_ConcertFavorites += ','+id;
  new Ajax.Request('/useraction.html', {   
    method: 'get',
    parameters: { 'a':'addconcert', 'id':id }
  }); 
}
function delConcertFavorite(id) {
  var mm = Config.MM_ConcertFavorites;
  if (mm==null) return false;
  mm = mm.split(',').without(id).join(',');
  Config.MM_ConcertFavorites = mm;
  new Ajax.Request('/useraction.html', {   
    method: 'get',
    parameters: { 'a':'delconcert', 'id':id }
  }); 
}
function getConcertFavoriteHTML(id) {
  return isConcertFavorite(id) ? '<A HREF="#" onClick="delConcertFavorite('+id+');$(\'koncert'+id+'\').update(getConcertFavoriteHTML('+id+')).show();return false;" TITLE="Usuń z ulubionych"><IMG onMouseOver="this.src=\'/img/btn_remove7.gif\'" onMouseOut="this.src=\'/img/btn_remove5.gif\'" STYLE="border:0px;" SRC="/img/btn_remove5.gif"></A>':'<A HREF="#" onClick="addConcertFavorite('+id+');$(\'koncert'+id+'\').update(getConcertFavoriteHTML('+id+')).show();return false;" TITLE="Dodaj do ulubionych"><IMG STYLE="border:0px;" SRC="/img/btn_add7.gif"></A>';
}



    function isRecordFavorite(id) {
      var mm = Config.MM_RecordFavorites;
      if (mm==null) return false;
      return mm.split(',').include(id);
    }
    function addRecordFavorite(id) {
      if (isRecordFavorite(id)) return;
      Config.MM_RecordFavorites += ','+id;
      new Ajax.Request('/useraction.html', {   
        method: 'get',
        parameters: { 'a':'addrecord', 'id':id }
      }); 
    }
    function delRecordFavorite(id) {
      var mm = Config.MM_RecordFavorites;
      if (mm==null) return false;
      mm = mm.split(',').without(id).join(',');
      Config.MM_RecordFavorites = mm;
      new Ajax.Request('/useraction.html', {   
        method: 'get',
        parameters: { 'a':'delrecord', 'id':id }
      }); 
    }
    
    function getRecordFavoriteHTML(id) {
      return isRecordFavorite(id) ? '<A HREF="#" onClick="delRecordFavorite('+id+');$(\'record'+id+'\').update(getRecordFavoriteHTML('+id+')).show();return false;" TITLE="Usuń z ulubionych"><IMG onMouseOver="this.src=\'/img/btn_remove7.gif\'" onMouseOut="this.src=\'/img/btn_remove5.gif\'" STYLE="border:0px;" SRC="/img/btn_remove5.gif"></A>':'<A HREF="#" onClick="addRecordFavorite('+id+');$(\'record'+id+'\').update(getRecordFavoriteHTML('+id+')).show();return false;" TITLE="Dodaj do ulubionych"><IMG STYLE="border:0px;" SRC="/img/btn_add7.gif"></A>';
    }



function isStationFavorite(id) {
  var mm = Config.MM_StationFavorites;
  if (mm==null) return false;
  return mm.split(',').include(id);
}
function addStationFavorite(id) {
  if (isStationFavorite(id)) return;
  Config.MM_StationFavorites = Config.MM_StationFavorites+','+id;
  new Ajax.Request('/useraction.html', {   
    method: 'get',
    parameters: { 'a':'addradio', 'id':id }
  }); 
}
function delStationFavorite(id) {
  var mm = Config.MM_StationFavorites;
  if (mm==null) return false;
  mm = mm.split(',').without(id).join(',');
  Config.MM_StationFavorites = mm;
  new Ajax.Request('/useraction.html', {   
    method: 'get',
    parameters: { 'a':'delradio', 'id':id }
  }); 
}
function getStationFavoriteHTML(id) {
  return isStationFavorite(id) ? '<A HREF="#" onClick="delStationFavorite('+id+');$(\'radio'+id+'fav\').update(getStationFavoriteHTMLforList('+id+')).show();return false;" TITLE="Usuń stację z ulubionych"><IMG onMouseOver="this.src=\'/img/btn_remove7.gif\'" onMouseOut="this.src=\'/img/btn_remove5.gif\'" ALIGN=top CLASS="playbut" STYLE="border:0px;" ALT="" SRC="/img/btn_remove5.gif"></A>':'<A HREF="#" onClick="addStationFavorite('+id+');$(\'radio'+id+'fav\').update(getStationFavoriteHTMLforList('+id+')).show();return false;" TITLE="Dodaj stację do ulubionych"><IMG ALIGN=top CLASS="playbut" STYLE="border:0px;" ALT="" SRC="/img/btn_add7.gif"></A>';
}
function getStationFavoriteHTMLforList(id) {
  return isStationFavorite(id) ? '<A HREF="#" onClick="delStationFavorite('+id+');$(\'radio'+id+'fav\').update(getStationFavoriteHTMLforList('+id+')).show();RefreshRadioList();return false;" TITLE="Usuń stację z ulubionych"><IMG onMouseOver="this.src=\'/img/btn_remove7.gif\'" onMouseOut="this.src=\'/img/btn_remove5.gif\'" ALIGN=top CLASS="playbut" STYLE="border:0px;" ALT="" SRC="/img/btn_remove5.gif"></A>':'<A HREF="#" onClick="addStationFavorite('+id+');$(\'radio'+id+'fav\').update(getStationFavoriteHTMLforList('+id+')).show();RefreshRadioList();return false;" TITLE="Dodaj stację do ulubionych"><IMG ALIGN=top CLASS="playbut" STYLE="border:0px;" ALT="" SRC="/img/btn_add7.gif"></A>';
}
function getStationLineHTML(id,cls) {
  return '<DIV onMouseOut="HidePlayBox('+id+')" onMouseOver="ShowPlayBox('+id+')" CLASS="'+cls+'" ID="radio'+id+'line"><DIV CLASS="right"><DIV STYLE="width:158px" CLASS="listautor" ID="radio'+id+'autor">*</DIV></DIV><DIV CLASS=nowrap><A TITLE="Posłuchaj" HREF="#'+id+'" onClick="OpenPlayer('+id+')"><IMG ALT="" ALIGN=top CLASS="playbut" SRC="/img/arrowp.gif" ALT=""></A><SPAN ID="radio'+id+'fav" STYLE="display:none"></SPAN>&nbsp;<A HREF="/radio,'+id+','+RadioIDNames[id]+'"><SPAN CLASS=radionormal>'+RadioNames[id]+(NewRadios.include(parseInt(id))?' <SPAN STYLE="color:#F00;font-weight:normal;">new!</SPAN>':'')+'</SPAN></A></DIV><DIV CLASS="clear"></DIV></DIV>';
}

function SetStationFavorite(id) {
  $('radio'+id+'fav').update(getStationFavoriteHTML(id)).show();
}
function SetStationFavoriteForList(id) {
  $('radio'+id+'fav').update(getStationFavoriteHTMLforList(id)).show();
}

function UpdateStationFavorites() {
  XLog('UpdateStationFavorites()');
  RadioIDs.compact().each(function (id) { if (id!==null) SetStationFavoriteForList(id); } );
}

function BuildRadioList() {
  XLog('BuildRadioList()');
  $('staticradiolist').update().hide();
  var parts = RadioIDs.compact().partition(function(id) { return isStationFavorite(id); });
  var p1 = parts[0].compact().map(function (id,i) { var cls = i%2 ? 'odd':'even'; return getStationLineHTML(id,cls); } ).join(' ');
  var p2 = parts[1].compact().map(function (id,i) { var cls = i%2 ? 'odd':'even'; return getStationLineHTML(id,cls); } ).join(' ');
  if (Config.Logged==0) {
    $('radiolist').update(p1+p2);
  } else {
    if (p1=='') {
      $('radiolist').update('<DIV CLASS="radiolistdivider"><IMG SRC="/img/longarrow.gif">&nbsp;wybierz ulubione stacje</DIV>'+p2);
    } else if (p2=='') {
      $('radiolist').update(p1);
    } else {
      $('radiolist').update('<DIV CLASS="radiolistdivider">ulubione stacje</DIV>'+p1+'<DIV CLASS="radiolistdivider">pozostałe stacje</DIV>'+p2);
    }
  }
}

function RefreshRadioList() {
  BuildRadioList();
  if (Config.Logged==1) UpdateStationFavorites();
  UpdatePlaying();
}

function UserConfigSet(keyvals,msgid) {
  var ii = $(msgid).innerHTML;
  $(msgid).update('czekaj');
  for (i=0;i<keyvals.length;i++) {
    new Ajax.Request('/useraction.html', {   
      method: 'get',
      parameters: { 'a':'setconfig', 'key':keyvals[i][0], 'val':keyvals[i][1] },
      onComplete: function() {
        $(msgid).update('OK');
        window.setTimeout(function() { $(msgid).update(ii); }, 5000);
      }
    }); 
  }
}

function $RR(aform,aname) {
  var valx = $(aform).getInputs('radio',aname).find(function(radio) { return radio.checked; });
  return valx==null ? '' : valx.value;
}

function RadioLogosShow(a,title) {
  $('radiologostitle').update(title);
  if (a.length==0) {
    // show all
    $$('.radiologo').invoke('show'); 
  } else {
    // show some
    RadioIDs.compact().each( function (id) { 
      if (a.include(id)) {
        $('radiologo'+id).show();
      } else {
        $('radiologo'+id).hide();
      }
    } );
  }
}

function ShowFavKoncerty() {
  XLog('ShowFavKoncerty()');
  $$('.koncertfav').each( function(s) { 
    var koncertid = parseInt(s.id.substr(7,999));
    var koncertst = getConcertFavoriteHTML(koncertid);
    s.update(koncertst).show();
  });
}

function ShowRanking(blockid,blockcontentsid,blocktitleid,id) {
  $(blockid).show()
  $(blocktitleid).update('wakacyjny ranking stacji <A HREF="/radio,'+id+'">'+RadioNames[id]+'</A>');
  $(blockid).show();
  GenAjax(blockcontentsid, 'topradia',$H({'id':id}),0,5);
}

function ShowProfileComments(uid,allowdel) {
  $('ProfileComments').update('');
  $('ProfileCommentsWait').show();
  new Ajax.Request('/ajaxgen.html', {   
    method: 'get',
    parameters: { 'what':'profilecomments', 'uid':uid, 'allowdel':allowdel, 'chaos':Math.round(Math.random()*9999999) },
    onSuccess: function(transport) {
      $('ProfileComments').update(transport.responseText);
      $('ProfileCommentsWait').hide();
    },
    onFailure: function() {
      $('ProfileComments').update('Wystąpił problem z załadowaniem komentarzy - spróbuj odświeżyć stronę');
      $('ProfileCommentsWait').hide();
    }
  });
}

function SendProfileComment() {
  var uid_for = $F('PCUserID');
  var tytul = $F('PCTytul');
  var tresc = $F('PCTresc');
  if (tytul.strip()=='' && tresc.strip()=='') {
    alert('Wypełnij pola formularza!');
  } else {
    var podpis = Config.UserName;
    $('ProfileCommentForm').reset();
    $('ProfileCommentForm').hide();
    $('ProfileCommentsWait').show();
    $('ProfileComments').update('');
    new Ajax.Request('/useraction.html', {   
      method: 'get',
      parameters: { 'a':'usercomment', 'tytul':tytul, 'tresc':tresc, 'podpis':podpis, 'uid':uid_for },
      onComplete: function() {
        $('ProfileCommentsWait').hide();
        $('ProfileComments').update('OK');
        ShowProfileComments(uid_for,Config.UserID==uid_for?1:0);
      }
    });
  }
}

function DeleteProfileComment(komid) {
  new Ajax.Request('/useraction.html', {   
    method: 'get',
    parameters: { 'a':'deleteusercomment', 'komid':komid },
    onComplete: function(transport) {
      ShowProfileComments(Config.UserID,1);
    }
  });
}

function ShowProfilePhotoComments(pid,allowdel) {
  $('ProfileComments').update('');
  $('ProfileCommentsWait').show();
  new Ajax.Request('/ajaxgen.html', {   
    method: 'get',
    parameters: { 'what':'profilephotocomments', 'pid':pid, 'allowdel':allowdel },
    onSuccess: function(transport) {
      $('ProfileComments').update(transport.responseText);
      $('ProfileCommentsWait').hide();
    },
    onFailure: function() {
      $('ProfileComments').update('Wystąpił problem z załadowaniem komentarzy - spróbuj odświeżyć stronę');
      $('ProfileCommentsWait').hide();
    }
  });
}

function SendProfilePhotoComment() {
  var pid = $F('PCPid');
  var uid_for = $F('PCUserID');
  var tytul = $F('PCTytul');
  var tresc = $F('PCTresc');
  if (tytul.strip()=='' && tresc.strip()=='') {
    alert('Wypełnij pola formularza!');
  } else {
    var podpis = Config.UserName;
    $('ProfileCommentForm').reset();
    $('ProfileCommentForm').hide();
    $('ProfileCommentsWait').show();
    $('ProfileComments').update('');
    new Ajax.Request('/useraction.html', {   
      method: 'get',
      parameters: { 'a':'userphotocomment', 'tytul':tytul, 'tresc':tresc, 'podpis':podpis, 'pid':pid, 'uid':uid_for },
      onComplete: function() {
        $('ProfileCommentsWait').hide();
        $('ProfileComments').update('OK');
        ShowProfilePhotoComments(pid,Config.UserID==uid_for?1:0);
      }
    });
  }
}

function DeleteProfilePhotoComment(pid,komid) {
  new Ajax.Request('/useraction.html', {   
    method: 'get',
    parameters: { 'a':'deleteuserphotocomment', 'komid':komid },
    onComplete: function(transport) {
      ShowProfilePhotoComments(pid,1);
    }
  });
}

//--Komentarze----------

function CommentsAlbum(albumid) {
  $('albumcom' + albumid).show();
  GetCommentsAlbum(albumid);
  return false;
}

function GetCommentsAlbum(albumid){
  $('listcom' + albumid).update('pobieranie komentarzy ... ');
  new Ajax.Request('/ajaxgen.html', {   
    method: 'get',
    parameters: { 'what':'generalcomments', 'type': 'plyta', 'pid': albumid, 'ignoreid': '', 'allowdel': 0, 'chaos':Math.round(Math.random()*9999999) },
    onSuccess: function(transport) {
      $('listcom' + albumid).update(transport.responseText);

    },
    onFailure: function() {
      $('listcom' + albumid).update('Wystąpił problem z załadowaniem komentarzy - spróbuj odświeżyć stronę');
    }
  });  
  
}

function ShowGeneralComments(type, pid, allowdel, ignoreid) {
  $('GeneralComments').update('');
  if($('GeneralCommentsWait')) $('GeneralCommentsWait').show();
  new Ajax.Request('/ajaxgen.html', {   
    method: 'get',
    parameters: { 'what':'generalcomments', 'type': type, 'pid': pid, 'ignoreid': ignoreid, 'allowdel': 0, 'chaos':Math.round(Math.random()*9999999) },
    onSuccess: function(transport) {
      $('GeneralComments').update(transport.responseText);
      $('GeneralCommentsWait').hide();
    },
    onFailure: function() {
      $('GeneralComments').update('Wystąpił problem z załadowaniem komentarzy - spróbuj odświeżyć stronę');
      $('GeneralCommentsWait').hide();
    }
  });
}

function ShowGeneralCommentsPagination(type, pid, allowdel, ignoreid, page, limit) {
  $('GeneralComments').update('');
  if($('GeneralCommentsWait')) $('GeneralCommentsWait').show();
  new Ajax.Request('/ajaxgen.html', {   
    method: 'get',
    parameters: { 'what':'generalcomments', 'type': type, 'pid': pid, 'ignoreid': ignoreid, 'allowdel': 0,'page': page, 'limit': limit, 'chaos':Math.round(Math.random()*9999999) },
    onSuccess: function(transport) {
      $('GeneralComments').update(transport.responseText);
      $('GeneralCommentsWait').hide();
    },
    onFailure: function() {
      $('GeneralComments').update('Wystąpił problem z załadowaniem komentarzy - spróbuj odświeżyć stronę');
      $('GeneralCommentsWait').hide();
    }
  });
}

function SendAlbumComment(albumid) {
  var albumid = albumid;
  var tytul = $F('PCTytul' + albumid);
  var tresc = $F('PCTresc' + albumid);
  var pid = $F('PCID' + albumid);
  var type = $F('PCType' + albumid);
  if (tytul.strip()=='' && tresc.strip()=='') {
    alert('Wypełnij pola formularza!');
  } else {
    var podpis = Config.UserName;
    //$('GeneralCommentForm').reset();
    //$('GeneralCommentForm').hide();
    //$('GeneralCommentsWait').show();
    //$('GeneralComments').update('');
    new Ajax.Request('/useraction.html', {   
      method: 'post',
      parameters: { 'a':'generalcomment', 'tytul':tytul, 'tresc':tresc, 'podpis':podpis, 'type': type, 'pid':pid },
      onComplete: function() {
        //$('GeneralCommentsWait').hide();

        $('frmcom' + albumid).update('<span class="cs">Komentarz został dodany.</span>');


        GetCommentsAlbum(albumid);
      }
    });
  }
}


function SendGeneralComment() {
  var tytul = $F('PCTytul');
  var tresc = $F('PCTresc');
  var pid = $F('PCID');
  var type = $F('PCType');
  if (tytul.strip()=='' && tresc.strip()=='') {
    alert('Wypełnij pola formularza!');
  } else {
    var podpis = Config.UserName;
    $('GeneralCommentForm').reset();
    $('GeneralCommentForm').hide();
    $('GeneralCommentsWait').show();
    $('GeneralComments').update('');
    new Ajax.Request('/useraction.html', {   
      method: 'post',
      parameters: { 'a':'generalcomment', 'tytul':tytul, 'tresc':tresc, 'podpis':podpis, 'type': type, 'pid':pid },
      onComplete: function() {
        $('GeneralCommentsWait').hide();
        $('GeneralComments').update('OK');
        
        if (type == 'news' && pid == 5142) {
          ShowGeneralCommentsPagination(type, pid, 0, 0, 1, 6);
        }
        else {
          ShowGeneralComments(type, pid, 0);
        }
      }
    });
  }
}

function SendSubPageComment() {
  var tytul = $F('PCTytul');
  var tresc = $F('PCTresc');
  var pid = $F('PCID');
  var type = $F('PCType');
  if (tytul.strip()=='' && tresc.strip()=='') {
    alert('Wypełnij pola formularza!');
  } else {
    var podpis = Config.UserName;
    $('GeneralCommentForm').reset();
    $('GeneralCommentForm').hide();
    $('GeneralCommentsWait').show();
    $('GeneralCommentsWait').update('Proszę czekać.');
    new Ajax.Request('/useraction.html', {   
      method: 'post',
      parameters: { 'a':'generalcomment', 'tytul':tytul, 'tresc':tresc, 'podpis':podpis, 'type': type, 'pid':pid },
      onComplete: function() {
        $('GeneralCommentsWait').update('Komentarz został dodany');
				document.location.reload();
      }
    });
  }
}


//----------------------
function showFailure(originalRequest) {
  $('placeholder').update('');
}

function showResponse(originalRequest) {
  $('placeholder').update(originalRequest.responseText);
}

function DoSendEmail(uname,buddyemail) {
  var url = 'sendemail.php?uname='+uname +'&buddyemail='+buddyemail +'&chaos='+Math.random();
  $('placeholder').update('<div style="height:16px;width:16px;"><IMG ALIGN=absmiddle SRC="/img/load3.gif"></div>');
  var myAjax = new Ajax.Request(
			url, 
			{
				method: 'get',
				onSuccess: showResponse,
				onFailure: showFailure
			});
  return false;
}
//----------------------


function ShowDecade(y) {
  $('decades').update($R(y,Math.min(2009,y+9)).collect(function(x){ return '<A HREF="year,'+x+'">'+x+'</A>' }).join(' '));
}

function OpenWallpaper(elemid) {        
  var w=window.open('http://www.miastophone.pl/1/element/'+elemid,'Content','width=567,height=500,left=320,top=100,manubar=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,resizable=yes');
  w.focus();
}    

function SortStationFavorites() {
  var parts = RadioIDs.compact().partition(function(id) { return isStationFavorite(id); });
  var p1 = parts[0].compact().map(function (id,i) { var cls = i%2 ? 'odd':'even'; return getRadioItem(id,cls); } ).join(' ');
  var p2 = parts[1].compact().map(function (id,i) { var cls = i%2 ? 'odd':'even'; return getRadioItem(id,cls); } ).join(' ');
  

  $('staticradiolist22').update('<div class="stripe stripe-radia"><DIV CLASS="radiolistdivider">ulubione stacje</DIV>'+p1+'<DIV CLASS="radiolistdivider">pozostałe stacje</DIV>'+p2+'</div>');

  var xs = $$('.statline');
  //console.log(Object.toJSON(xs));
  xs.each( function(el) { 
    el.observe('mousemove',mOver);
    el.observe('mouseout',mOut);
  });
}

function getRadioItem(id, cls) {
  return '<div class="'+cls+'"><DIV idr="'+id+'" ID="radio'+id+'line" CLASS="statline"><DIV idr="'+id+'" CLASS=right ID="radio'+id+'autor"></DIV><A idr="'+id+'" TITLE="Posłuchaj" HREF="#'+id+'" onClick="OpenPlayer('+id+')"><IMG idr="'+id+'" ALT="Posłuchaj" ALIGN=top CLASS="playbut" SRC="/img/arrowp.gif"></A>&nbsp;<SPAN idr="'+id+'" ID="radio'+id+'fav" STYLE="display:none"></SPAN>&nbsp;<A idr="'+id+'" CLASS=radionormal HREF="/radio,'+id+','+RadioIDNames[id]+'">'+RadioNames[id]+(NewRadios.include(parseInt(id))?' <SPAN STYLE="color:#F00;font-weight:normal;">new!</SPAN>':'')+'</A></DIV></div>';
}