if (typeof(caspian_util) == 'undefined') {
    alert ("Error: music.js: util.js not included");
}

var dial530 = "/_images/record/dial-530.jpg";
var dial630 = "/_images/record/dial-630.jpg";
var dialOn = "/_images/record/dial-ja.jpg";
var dialOff = "/_images/record/dial-nee.jpg";

var player_name = 'music_player';
var dialSongDir = "/_images/record/dial-song";

/*********/

// remember that this script is included in two different contexts (fixed
// and detached) and each one gets its own variables.

var playlistFile = '';

var currentItem;
var playlist;

var currentAlbum = '';
var currentTrackNum = -1;

var saveImage = '';
var http;

function detached() {
    /*
    return (
        (top.name == 'detachPlayer')
        ||
        (top._detached)
    );
    */
    return (top.document.location.href.match(/radio.html/) || top._detached);
}


// this script is src'ed by two different frames. if they need to access the
// same var then store it in the player frame
// (top.currentAlbum) = ...
// local currentAlbum is ok to use for stuff which only one frame needs to
// know about, e.g. currentAlbum for rendering booklet

var bookletIndex = 0;

//var dialState = 0;

function getPlayerDetached() {
    var w;
    if (w = top.detachPlayerWindow) {
        return w.document['music_player'];
    }
    else alert ("getPlayerDetached(): top.detachPlayerWindow is null");
}
    
function getFixedPlayerContainer() {
    return getFixedPlayerFrame().document.getElementById('container');
}

function getFixedPlayerFrame() {
    if (detached()) {
        return getOpener().top.frames.player_frame;
    }
    else {
        return top.frames.player_frame;
    }
}

function getFunFrameContainer() {
    var f = getFunFrame();
    if (!f) return null;
    return f.document.getElementById('main_fun');
}

function getFunFrame() {
    var w;
    if (detached()) {
        var o = getOpener();
        if (!o) return null;
        return o.top.frames.main_frame;
    }
    else return top.frames.main_frame;
}

function getRecordFrame() {
    var w;

    if (detached()) w=top;
    else w = getFixedRecordFrame();

    return w.frames['record_frame'];
}

function getFixedRecordFrame() {
    //return top.frames.main_frame.frames['1_mid_frame'];
    return top.frames.main_frame;
}

function getRecordImage() {
    //var f = getRecordFrame();
    //if (!f) return;
    //return f.document.getElementById('record_image');
    //return $('record_image');
    return null;
}

function getFixedRecordImage() {
    return getFixedRecordFrame().document.getElementById('record_image');
}



function getDialJa() {
    return document.getElementById('dial_ja');
}

function getDialSong() {
    return document.getElementById('dial_song');
}

function sendEvent(typ,prm) {
    var t;
    if (t = thisMovie(player_name)) t.sendEvent(typ,prm);
};

// apparently is NOT called when player is first ready.
// it seems to be called with typ == 'time' somewhere before it's ready
// though ??
function getUpdate(typ,pr1,pr2,swf) {
    // 0: stop, 1: buffer, 2: play
    if(typ == 'state') { 
        if (pr1 == 0) {
            //recordStop();
            if (detached()) {
               dial(0);
            } else {
                getFixedPlayerFrame().playing = 0;
            }
        }
        else if (pr1 == 1) {
            if (detached()) {
                dial(0);
            } else {
                getFixedPlayerFrame().playing = 0;
            }
            //recordStop();
        }
        else if (pr1 == 2) {
            //recordStart();
            if (detached()) {
                dial(1);

                if (getFixedPlayerFrame().playing) {
                    // doesn't work ?? Ok, let's just make display none
                    //alert('opener playing');
                    //opener.sendEvent('playpause');
                }
                //getFixedPlayerContainer().style.visibility = 'hidden';
                getFixedPlayerContainer().style.display = 'none';
            }
            else {
                getFixedPlayerFrame().playing = 1;
            }
        }

    }

    else if (typ == 'time') {
        var elapsed = pr1;
        var remaining = pr2;

        top.currentTrackElapsed = elapsed;
    }

    // item is indexed at 0, same with add and remove

    else if (typ == 'item') {
        var index = pr1;
        //alert('got item ' + index);
        if (detached()) {
            //if (top.currentItem == index) return;
            if (currentItem == index) return;

            //top.currentItem = index;
            currentItem = index;
            //dialSong(top.playlist[top.currentItem][1]);
            //dialSong(playlist[top.currentItem][2]);
            dialSong(playlist[index][2]);
        }
    }
};

function getOpener() {
    //return getMainWindow();
    if (typeof(opener) != 'undefined') return opener;
}


function thisMovie(swf) {
/*
    if(navigator.appName.indexOf("Microsoft") != -1) {
        return window[swf];
    } else {
        return document[swf];
    }
*/
    // getElementById causes crazy bug. document[] seems to work.
    //return top.frames.player_frame.document.getElementById(swf);
    if (detached()) return top.document[swf];
    else return top.frames.player_frame.document[swf];

};

/*
all player functions:
   1. getlink, index: navigate to the link of playlistitem index.
   2. next : play the next playlistitem.
   3. playitem, index: play playlistitem index
   4. playpause: toggle the playback status.
   5. prev: play the previous playlistitem.
   6. scrub, seconds: scrub the current item to position seconds.
   7. stop: stop playing and buffering.
   8. volume, percent: set the volume to percent percent.

all updates:
   1. item, index: the currently playing playlistitem.
   2. load, percent: the percentage loaded of the current item.
   3. size, width,height: the dimensions of the current item.
   4. state, index: the current playback state. 0=stopped. 1=? 2=playing
   5. time, elapsed, remaining: the current elapsed and remaining time.
   6. volume, percent: the current volume.

function getLength(swf) { 
  var len = thisMovie(swf).getLength();
};
function addItem(swf,obj,idx) { 
  thisMovie(swf).addItem(obj,idx); 
};
function removeItem(swf,idx) { 
  thisMovie(swf).removeItem(idx); 
};
function itemData(swf,idx) { 
  var obj = thisMovie(swf).itemData(idx); 
};

*/

function loadFile(obj) {
    var t;
    if (t = thisMovie(player_name)) t.loadFile(obj);
};

// at any point we are looking at / listening to one album. store its name
// in top and load its playlist.
// UPDATE: not true any more.
function loadAlbum(album, _playlistFile) {
    top.currentAlbum = album;
    playlistFile = _playlistFile;
    loadFile({file:playlistFile});
}


// called when needle is clicked.
// NOT called when a song title is clicked.
// change name.
function playpause() {
    //if (top.currentAlbum == '') alert("error, no currentAlbum in top");

    if (detached()) {
        sendEvent('playpause');
    } else {

        if (getFixedPlayerContainer().style.display != 'block') return;

        if (top.currentTrackNum == -1) {
            //playSingleSongFromAlbum(0, 0);
            playSingleSongFromAlbum(0);
        }
        else {
            sendEvent('playpause');    
        }
    }
}

function recordStart() {
    var r = getRecordImage();
    if (!r) return;
    var w = r.width;
    log('making it spin');
    r.src = '/_images/record/record.spinning.gif';
    r.width = w;
}

function recordStop() {
    var r = getRecordImage();
    if (!r) return;
    log('making it stop');
    r.src = '/_images/record/record.stopped.gif';
}

function fixedRecordStop() {
    getFixedRecordImage().src = '/_images/record/record.stopped.gif';
}

function dialSong(dialFilename) {
    var d = getDialSong();
    if ( ! d) { 
        alert ("no dial song"); 
        return;
    }

    var da = dialSongDir + "/" + "blur-left.jpg";
    var db = dialSongDir + "/" + "blur-right.jpg";
    //var dc = dialSongDir + "/" + num + ".jpg";
    var dc = dialFilename;
    d.src = da;
    setTimeout("getDialSong().src = '" + db + "'", 200);
    setTimeout("getDialSong().src = '" + dc + "'", 400);
}

function dial(b) {
    var i = getDialJa();
    if ( ! i ) return;
    if (top.dialState == b) return;

    top.dialState = b;
    if (b) {
        i.src = dial630;
        setTimeout("getDialJa().src = dial530", 150);
        setTimeout("getDialJa().src = dialOn", 300);
    }
    else {
        i.src = dial530;
        setTimeout("getDialJa().src = dial630", 50);
        setTimeout("getDialJa().src = dialOff", 100);
    }
}
        

function cursorChange() {
    document.body.style.cursor = 'pointer';
}

var bookletImages = new Array();
bookletImages['talk'] = 
[
    "/data/images/albums/talk/booklet-01.jpg",
    "/data/images/albums/talk/booklet-0203.jpg",
    "/data/images/albums/talk/booklet-0405.jpg",
    "/data/images/albums/talk/booklet-0607.jpg",
    "/data/images/albums/talk/booklet-0809.jpg",
    "/data/images/albums/talk/booklet-1011.jpg",
    "/data/images/albums/talk/booklet-1213.jpg",
    "/data/images/albums/talk/booklet-1415.jpg",
    "/data/images/albums/talk/booklet-16.jpg"
];
    
// assumes currentAlbum and bookletIndex were already set 
function bookletNextPage() {
    bookletIndex++;
    if (bookletIndex >= bookletImages[currentAlbum].length) bookletIndex = 0;

    bookletShowPage(currentAlbum, bookletIndex);
}

function bookletPreviousPage() {
    bookletIndex --;
    if (bookletIndex < 0) bookletIndex = bookletImages[currentAlbum].length - 1;
    bookletShowPage(currentAlbum, bookletIndex);
}

function bookletShowPageNumber(page) {

    // fix when more albums
    if (page > 16) return;
    if (page == 16) bookletIndex = 8;
    else if (page > 13) bookletIndex = 7;
    else if (page > 11) bookletIndex = 6;
    else if (page > 9) bookletIndex = 5;
    else if (page > 7) bookletIndex = 4;
    else if (page > 5) bookletIndex = 3;
    else if (page > 3) bookletIndex = 2;
    else if (page > 1) bookletIndex = 1;
    else if (page == 1) bookletIndex = 0;

    currentAlbum = gup('album');
    if (!currentAlbum) alert ("error: bookletShowPage");
    bookletShowPage(currentAlbum, bookletIndex);
}

function bookletShowPage(album, index) {
    
    document.getElementById('booklet').innerHTML =
        '<img src="' + bookletImages[album][index] + '" height=100%>';
    /*
    document.getElementById('booklet_right').innerHTML =
        '<img src="' + bookletImages[album][index+1] + '" width=100%>';
    */
}

// we are now calling this function also as a quicklink from every page, so
// most of this shit will be null. not using anyway.
function detachPlayer(height, width) {
    //var currentAlbum = top.currentAlbum;
    //var currentTrackNum = top.currentTrackNum;
    //if (currentTrackNum == -1) alert ("detachPlayer(): no currentTrackNum in top");
    //var elapsed = top.currentTrackElapsed;
    //if (elapsed == -1) { 
    //    alert ("detachPlayer(): no currentTrackElapsed in top");
    //    return;
    //}

    // hide stuff in fun frame; hiding the fixed player comes when we know
    // for sure that the other one is playing. though we could change this.
    var f = getFunFrameContainer();
    if (f) f.style.display = 'none';

    var testing = $get('testing');

    // what if they reload top? it might be ok. otherwise we might need a cookie.
    top.detachPlayerWindow = window.open(
        "/" + top.W + "music/radio.html?" +
        "testing=" + testing,

        "detachPlayer",

        'status=0, resize=0, toolbar=0, scrollbars=1, menubar=0' + ',' +
        'width=' + width + ',' +
        'height=' + height 
    );
}

function bookletOpen(album, height, width, page) {
    if (!page) page = 1;
    var W;
    if (detached()) {
        W = getOpener().top.globals.W;
    } else {
        W = top.globals.W;
    }
    window.open(
        "/" + W + "music/booklet.html?album=" + album + "&page=" + page,
        "booklet", 
        'status=false, resize=true, toolbar=false, scrollbars=false,' + 
        'width=' + width + 10 + ',' +
        'height=' + height * 1.2
        );
    }

// from http://www.netlobo.com/url_query_string_javascript.html
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function playSingleSongFromAlbum(num) {

    if (!detached()) {
        //alert(getFixedPlayerContainer());
        //alert(getFixedPlayerContainer().style.display);
        //alert(getFixedPlayerContainer().style.visibility);

        getFixedPlayerContainer().style.display = 'block';

        getFixedPlayerContainer().style.visibility = 'visible';

        top.currentTrackNum = num;
        sendEvent('playitem', num);

        //getFixedPlayerContainer().style.visibility = 'visible';
        getFunFrame().document.getElementById('detachButton').disabled = false;
    }

    
}

function getPlaylistIndex(album, num) {
    return 1;
}

/*
function handler() {
    if (http.readyState == 4) {
        var text = http.responseText;
        //alert(escape(text));
        var cell = document.getElementById('one_mid_table');
        cell.innerHTML = unescape(text);
        //cell.style.width = document.getElementById("record_image").width  + "px";
        //cell.style.width = "5%";
        /*
        alert("width is " + cell.style.width);
        alert("width is " + cell.style.width);
        cell.style.background = '#000044';
      
    }
}
*/

function movePlayerUp(dy) {
    var s = top.frames['player_frame'].document.getElementById('container').style;
    var t = s.top;

    var r = /(\d+)px/;
    var a = r.exec(t);

    var oldTop = new Number(a[1]);
    var newTop = oldTop + dy;

    s.top = newTop + "px";
}

/*
function hideInstructionsPointRight() {
alert('hello');
    var a = getFunFrame().document.getElementById("right_arrow");
    alert(a);
    a.style.visibility = 'hidden';
    var b = getFunFrame().document.getElementById("right_span");
    if (b) b.style.visibility = 'hidden';
}
*/

