/*
    If anything's done in a fishy way it's to make it work in gecko AND ie
*/

var staticurl = "http://62.216.251.201";


var hilightcolor = '#CCFFFF';//336699';//'#9999FF'; //'#FFCCCC'; // used for mouseovers on bar and buttons.
var unhilightcolour = '#e6e6e6';
var defaultprovidedtext = '\u00a0'; // unicode reference for &nbsp; ;-)
var disabledColor= '#999';  // aka lightgray

// mode menu colors on and off
var modemenuoff= '#006';
var modemenuon= '#fff';

var mydocument = document;

var second_timer; // global handle to it so we can clear it if needed 
var hammer_timer; // refresh every few seconds until that stream is a flowin' (then kill timer ;)
var onetimer; // oneoffs
var third_timer; // oneoffs


var SYNC_ADJUST = -10;   // const added to timer from start of track
                        // 10 seconds is about right, given ave pre-buffer times

//id's of controls to disable during wait mode.
var controls = new Array(11);
controls[0] = 'skip';
controls[1] = 'love';
controls[2] = 'hate';
controls[3] = 'change-button';
controls[4] = 'stoprec';
controls[5] = 'bar1';
controls[6] = 'bar2';
controls[7] = 'bar3';
controls[8] = 'bar4';
controls[9] = 'bar5';
controls[10] = 'bar6'; // home icon

var waiting = false; // if we are "waiting" then buttons are disabled

var prog=0;
var dur=0;
var isRecording=true;
var isPreviewing=false;
var isOndemanding=false;

var isLoggedIn = false;

var currenttrack=0;

var radiomode   = 1;

var _PROFILE    = 3;
var _FAN        = 2;
var _RANDOM     = 1;

/*  (lower case means shrunk, absent means hidden)
    N   -   Song now playing box
    F   -   Provided by <user>
    T   -   Taste provided by <user>
*/
var modestring = new Array(4);
modestring[1]="N";
modestring[2]="NFA";
modestring[3]="NFT";


var vis_provided=true;
var vis_taste=true;
var vis_fan=true;

function isPreview(x){
    if(x) {
        isPreviewing=true;
        dur=30;
    }else{
        isPreviewing=false;
    }
}

function isOndemand(x){
    if(x){
        onDemanding = true;
    }else{
        onDemanding = false;
    }
}

function getPreview(){
    return isPreviewing;
}
function getCurrentTrack(){
    return currenttrack;
}
function barover(obj,txt){
    if (waiting) return false;
    hilight(obj);
    setprovidedmessage(txt);
}
function barout(obj){
    unhilight(obj)
    setprovidedmessage(defaultprovidedtext);
}
function setprovidedmessage(txt){
    if (waiting) return false;
    var s = mydocument.getElementById('changetext');
    var msg = mydocument.createTextNode(txt);
    s.replaceChild(msg,s.childNodes[0]);
}

function tooltiptext(obj,txt) {
    if (txt == '') {
        txt = defaultprovidedtext;
    }
    var s = mydocument.getElementById(obj);
    var msg = mydocument.createTextNode(txt);
    s.replaceChild(msg,s.childNodes[0]);
}

function hilight(obj){
    if (waiting) return false;
    if(mydocument.getElementById(obj)) mydocument.getElementById(obj).style.backgroundColor=hilightcolor;
}
function unhilight(obj){
    if (waiting) return false;
    if(mydocument.getElementById(obj)) mydocument.getElementById(obj).style.backgroundColor=unhilightcolour;
}
// replaces buttons with a "wait" div for long delays between tracks and shit
function setLimbo(i){
    return false;
    if(i==true){
        document.getElementById('limboplayer').style.display='block';
        document.getElementById('player').style.display='none';
       //e alert('setLimbo(true)');
    }else{
        document.getElementById('limboplayer').style.display='none';
        document.getElementById('player').style.display='block';
    }
}
function startWaiting(){
    if(waiting) return false;
    waiting=true; 
    if (gotPopup()) {
        popup.startWaiting();
    }
    for(var i=0; i<controls.length; i++){
        if (i<=4) {
            if(mydocument.getElementById(controls[i])){
                if (i==4) {
                    if (isRecording) imgst = "stoprec";
                    else imgst = "startrec";
                }
                else imgst = controls[i];
                mydocument.getElementById(controls[i]).src = staticurl+"/images/player/"+imgst+"2.gif";
            }
        }
        else {
            if(mydocument.getElementById(controls[i])){ // does this object have style(, baby)?
                mydocument.getElementById(controls[i]).style.backgroundColor=disabledColor;
            }
        }
    }
    return true;
}
function stopWaiting(){
    clearInterval(hammer_timer);
    if(!waiting) return false;
    waiting=false; 
    if (gotPopup()) {
        popup.stopWaiting();
    }
    for(var i=0; i<controls.length; i++){
        if (i<=4) {
            if(mydocument.getElementById(controls[i])){
                if (i==4) {
                    if (isRecording) imgst = "stoprec";
                    else imgst = "startrec";
                }
                else imgst = controls[i];
                mydocument.getElementById(controls[i]).src = staticurl+"/images/player/"+imgst+".gif";
            }
        }
        else {
            if(mydocument.getElementById(controls[i])) { //.style){ doesn't work if object doesn't exist, felix
                mydocument.getElementById(controls[i]).style.backgroundColor=unhilightcolour;
            }
        }
    }
    return true;
}
function actionFrame(url){
    mydocument.getElementById('ActionFrame').src=url;
}
function miscFrame(url){
    //alert('miscFrame : '+url);
    mydocument.getElementById('MiscFrame').src=url;
}
function changeEntropy(e){
    setprovidedmessage('');
    if(waiting) return false;
//    hammer_timer = setInterval('updatePlayer()',12000);
    actionFrame("/iframes/playeraction.php?a=entropy&e="+e);
    startWaiting();
}
function getRand(){
    return Math.round((Math.random()*9999999)+1);
}
function clickSkip(max){
    if(waiting) return false;
//    hammer_timer = setInterval('updatePlayer()',12000);
    actionFrame("/iframes/playeraction.php?a=skip&rand="+getRand());
    startWaiting();
}
function clickLove(max){
    if(waiting) return false;
//    hammer_timer = setInterval('updatePlayer()',12000);
    actionFrame("/iframes/playeraction.php?a=love&rand="+getRand());
    startWaiting();
}
function clickHate(max){
    if(waiting) return false;
//    hammer_timer = setInterval('updatePlayer()',12000);
    actionFrame("/iframes/playeraction.php?a=hate&rand="+getRand());
    startWaiting();
}
function clickStart(){
    unshrinkplayer();
    hammer_timer = setInterval('updatePlayer()',10000); 
    //miscFrame("/iframes/playlist.m3u");
    window.location = "/iframes/playlist.m3u";
    startWaiting();
}
function clickChange(){
    if(waiting) return false;
    actionFrame("/iframes/playeraction.php?a=changeprovider");
    startWaiting();
}
        
function clickStop(){
    actionFrame("/iframes/playeraction.php?a=stop");
    shrinkplayer();
    clearPlayer();
    if (gotPopup())
        popup.clickStop(false);
}
function clickRec(){
    if(isRecording){
        actionFrame("/iframes/playeraction.php?a=stoprec");
    }else{
        actionFrame("/iframes/playeraction.php?a=startrec");
    }
    startWaiting();
}

function setRec(x){
    /*isRecording=x;
    if(x){
        var nodeImg = mydocument.createElement("img");
        nodeImg.setAttribute("src", staticurl+"/images/player/stoprec.gif" );
        nodeImg.setAttribute("border", '0');
        nodeImg.setAttribute("id", 'stoprec');
    }
    else {
        var nodeImg = mydocument.createElement("img");
        nodeImg.setAttribute("src", staticurl+"/images/player/startrec.gif" );
        nodeImg.setAttribute("border", '0');
        nodeImg.setAttribute("id", 'stoprec');
    }
    oldnode = mydocument.getElementById('stoprec-parent');
    if (oldnode.firstChild) {
        oldnode.removeChild(oldnode.firstChild);
    }
    oldnode.appendChild(nodeImg);
    //oldnode.replaceChild(nodeA,oldnode.firstChild);*/
}

function removePreviewTrack(id){
  //  alert('removing track: '+id+' NB: function doesnt do anything');
    removeNodeById('previewplaylist-track-'+id);
    actionFrame('/iframes/playlistActions.php?a=delete&track='+id);
}


function previewTrack(trk){
    var trk = new String(trk);
    if(trk.length<1){
        alert('No track selected. Try again.');
        return;
    }else{
        actionFrame("/iframes/playeraction.php?a=previewtrack&track="+trk);
        //startWaiting();
    }
}
function ondemandTrack(trk){
    var trk = new String(trk);
    if(trk.length<1){
        alert('Invalid track identifier specified');
        return;
    }else{
        actionFrame("/iframes/playeraction.php?a=ondemandtrack&track="+trk);
        //startWaiting();
    }
}
function ondemandAlbum(alb){
    if(alb<=0){
        alert('Invalid album identifier specified');
        return;
    }else{
        actionFrame("/iframes/playeraction.php?a=ondemandalbum&album="+alb);
        //startWaiting();
    }
}
function previewAlbum(alb){
    if(alb<=0){
        alert('Invalid album identifier specified');
        return;
    }else{
        actionFrame("/iframes/playeraction.php?a=previewalbum&album="+alb);
        //startWaiting();
    }
}
function test(){
//alert('this is a test');
}
//----------    UPDATING PLAYING INFO FIELDS   -------------

function _updatePlayingNode(node,name,url,bold){
	var nodeObj = mydocument.getElementById(node);
	var nodeA = mydocument.createElement("a");
	nodeA.setAttribute("href", url );
    //nodeA.setAttribute("class", 'top-playing-text'); // keep the css class too or the formatting fucks up
    nodeA.setAttribute("style", 'font-family: Arial, Helvetica, sans-serif;  font-size: 8pt;'+bold);
	var textContent = mydocument.createTextNode(name);
	nodeA.appendChild(textContent);
    if (nodeObj.childNodes[1]) {
    	nodeObj.replaceChild(nodeA,nodeObj.childNodes[1]);
    } else {
    	nodeObj.appendChild(nodeA);
    }
}
function updatePlayer(max){
    clearTimeout(onetimer);
    top.AutoFrame.location.href='/iframes/songfinished.php?currenttrack='+currenttrack;
}
function clearPlayer(){
//    updateArtist('Waiting for stream...',0);
//    updateAlbum('Waiting for stream...',0);
//    updateTrack('Waiting for stream...',0);
//    alert('clear player (TODO)');
    clearTimeout(onetimer);
    clearTimeout(second_timer);
    clearTimeout(third_timer);
    clearInterval(hammer_timer);
}
function setPlayerTimeout(ms){
    ms=ms*1000;
        //alert('updaing in ' + ms);
    third_timer = setTimeout("updatePlayer()",ms);
}
function updateArtist(name,id){
    _updatePlayingNode('playing-artist',name,"/artist.php?id="+id,'font-weight:bold;');
}

function updateAlbum(name,id){
    _updatePlayingNode('playing-album',name,"/album.php?id="+id);
}

function updateTrack(name,id){
    if(currenttrack != id) clearInterval(hammer_timer);// stop hammering
    currenttrack=id;
    _updatePlayingNode('playing-track',name,"/track.php?id="+id);
}

function updateCover(url, id,name){
    mydocument.getElementById('cover-art').src=url;
    mydocument.getElementById('cover-art').title=name;
    mydocument.getElementById('album-link').href="/album.php?id="+id;
}
function _updateUserNode(name,url,node){
    var nodeObj = mydocument.getElementById(node);
    var nodeA = mydocument.createElement("a");
    nodeA.setAttribute("href", url );
    nodeA.setAttribute("class", 'top-username'); // keep the css class too or the formatting fucks up
    nodeA.setAttribute("style", "font-family: Arial, Helvetica, sans-serif;  font-size: 8pt; color: #000;  text-decoration: none;");
    var textContent = mydocument.createTextNode(name);
    nodeA.appendChild(textContent);
    if (nodeObj && nodeObj.childNodes[1]){
        nodeObj.replaceChild(nodeA,nodeObj.childNodes[1]);
    } else if(nodeObj){
        nodeObj.appendChild(nodeA);
    }
}
function updateTasteProvider(name,url){
    _updateUserNode(name,url,'taste-provider');
}
function clickVisit(){
    window.location='http://www.last.fm/user/' + mydocument.getElementById("tasteusername").value;
}

function updateSongProvider(name,url){
    _updatePlayingNode('provided-profile',name,url);
}


function _updateTime(max){

    var nodeObj = mydocument.getElementById('track-progress');
    var nodeA = mydocument.createElement("span");
        nodeA.setAttribute("style","color:#666;font-size: 8pt; font-family: Arial, Helvetica, sans-serif;");
    var special="";
    if(isPreviewing) special="Preview: ";
    if(!waiting && prog<=dur){
        if(prog<1) prog=0;
        nodeA.appendChild(mydocument.createTextNode(special+mmss(prog) + "/" + mmss(dur)));
    }else{
        nodeA.appendChild(mydocument.createTextNode(special+"Loading..."));
    }
    //fucking fuck arse bastards IE is sooooooooo shit! 
    if(nodeObj.firstChild ){
        nodeObj.replaceChild(nodeA,nodeObj.firstChild); //children[0]);
    } 
    else {
        nodeObj.appendChild(nodeA);
    }
    
}
function perSecond(max){
    maxi=max;
    prog=prog+1;
    if(prog<=dur){
        if(max<1) max=0;
        _updateTime(max);
    }
    if(prog>=dur) startWaiting();
    // depending on response time of server, one of these will work
    if( ( isPreviewing || isOndemanding ) && prog==dur+5){
        updatePlayer(maxi);
    }else if(prog==(dur+6)) {
        updatePlayer(maxi);
    }else if(prog==(dur+10)) {
        updatePlayer(maxi);
    }else if(prog==(dur+20)) {
        updatePlayer(maxi);
    }else if(prog==(dur+15)) {
        updatePlayer(maxi);
    }else if(prog==(dur+30)) {
        updatePlayer(maxi);
    }else if(prog==(dur+60)) {
        updatePlayer(maxi);
    }else {
        //noop
    }
    clearTimeout(second_timer); // this is handy, because it cancels timer if we call it twice by accident :)
    second_timer = setTimeout("perSecond(maxi)",1000);
}
function startCountdown(_prog,_dur,max){
    prog=_prog+SYNC_ADJUST; 
    dur=_dur;
    if(isPreviewing){
        //updateSongProvider('','#');
        dur=30;//TODO: variableize this
    }
    //alert('startCountdown('+prog+','+dur+');');
    perSecond(max);
}
function mmss(secs){
    var str="";
    var m = Math.floor(secs/60);
    if(m<10){
        str="0"+m+":";
    }else{
        str=m+":";
    }
    var s = Math.floor(secs-(m*60));
    if(s<10){
        str=str+"0"+s;
    }else{
        str=str+s;
    }
    return str;
}
function hideMe(obj){
    var x = obj.getChildNodes(); //mydocument.getElementById(obj).getChildNodes();
    for(var i=0; i<x.length; i++){
        if(x[i].getChildNodes().length >0) hideMe(x[i]);
        x.style.visibility='hidden';
    }
}

function shrinkplayer(){
    mydocument.getElementById('player').style.display='none'; 
    mydocument.getElementById('startmusic').style.display='block'; 
}
function unshrinkplayer(){
    mydocument.getElementById('player').style.display='block'; 
    mydocument.getElementById('startmusic').style.display='none'; 
    if(isPreviewing){
        //changePlayerState('N');
        setPlayerTimeout(5000);
    }else{
        setPlayerTimeout(12000);    
    }
}
function changeRadioMode(i){
    actionFrame("/iframes/playeraction.php?a=radiomode&mode="+i+"&playerstate="+modestring[i]);
    unshrinkplayer();
    //startWaiting();
}

function startPersonalRadio(id) {
    top.ActionFrame.location.href = "/iframes/playeraction.php?a=personalradio&user=" + id;
}

function startOnMode(mode,id){
    if (mode == 3) {
        top.ActionFrame.location.href = "/iframes/playeraction.php?a=listenas&user=" + id;
    }
    else {
        changeRadioMode(mode);
        //alert('setting hammer');
        hammer_timer = setInterval('updatePlayer()',10000); 
        //if(mode==1 || mode==3)
           //miscFrame('/iframes/playlist.m3u');
          // window.location = '/iframes/playlist.m3u';
    }
}

function startMode(){
    unshrinkplayer();
    var mode=0;
    if(mydocument.getElementById('mode1').checked) mode=1;
//    if(mydocument.getElementById('mode2').checked) mode=2;
    if(mydocument.getElementById('mode3').checked) mode=3;
    if(mode==0) alert('invalid player mode. this is a bug, tell rj');
    changeRadioMode(mode);
    setPlayerTimeout(15000);
    if(mode==1 || mode==3) 
        //miscFrame('/iframes/playlist.m3u');
        window.location = '/iframes/playlist.m3u';
}

var popup = null;

function openPlayer(loc) {
        tune_OpenPlayer();
//        popup = window.open("/player/","popupplayer","toolbar=no, location=no, directories=no, status=no,menubar=no, scrollbars=no, resizable=yes, width=520, height=800");
  //      popup.focus();
    //    window.name = "lastfm";
}

function _openPlayer(loc) {
    if(!gotPopup()) {
        var cmd = '';
        if (loc == "home") var cmd = "?home=1";
        popup = window.open("/popup.php"+cmd,"popup","toolbar=no, location=no, directories=no, status=no,menubar=no, scrollbars=no, resizable=no, width=580, height=520"); // was height 560 wid 520
        popup.focus();
        //popup.startWaiting();
        window.name = "lastfm";
    }
    else {
        popup.focus();
        window.name = "lastfm";
    }
}

function getPlayer(mode) {
        if (mode) { 
            // mini
            var popmode = mode;
            var dim = ", width=185, height=160"
        }
        else {
            // maxi
            var popmode = '';
            var dim = ", width=580, height=520"
        }
        //popup = window.open("","popup");
        var agt=navigator.userAgent.toLowerCase();
        // stupid IE does not reset window.opener properly so you have to close 
        // the poor popup bastard and re-open it. not nice but works. ALWAYS!
        if (agt.indexOf("msie") != -1) {
            popup.close();
        }
        popup = window.open("/popup"+popmode+".php","popup","toolbar=no, location=no, directories=no, status=no,menubar=no, scrollbars=no, resizable=no"+dim);
        window.name = "lastfm";
        popup.opener = window.self;
        popup.setPopup();
}

function gotPopup() {
     return false;
     //TODO this broke, due to cookie action
    if (popup && !popup.closed) {
        //alert('popup found!');
        return true;
    }
    else { 
        //alert('no popup found, yeah right asshole!');
        return false;
    }
}

// open adding popup
function add(id,type,node,mem){
    if (node != '')
        if (mem != '') 
            window.open("/popups/add.php?id=" + id + "&type=" + type + "&node=" + node + "&mem=" + mem, "addpopup", "height=150, width=350, scrollbars=auto,toolbar=no, location=no, directories=no, status=no,menubar=no");
        else 
            window.open("/popups/add.php?id=" + id + "&type=" + type + "&node=" + node, "addpopup", "height=150, width=350, scrollbars=auto,toolbar=no, location=no, directories=no, status=no,menubar=no");
    else 
        window.open("/popups/add.php?id=" + id + "&type=" + type, "addpopup", "height=150, width=350, scrollbars=auto,toolbar=no, location=no, directories=no, status=no,menubar=no");
}

function userlink(name){
    window.open("/popups/userlink.php?user=" + name , "ulinkpopup", "height=400, width=550, scrollbars=auto");
}
//alert(document.cookie);
