$(document).ready( function(){
    /** Onload of src in iFrame, do some stuff */
    $("#content-frame").load(function () {
        try {
            document.getElementById("content-frame").contentWindow.init();
            Frontend.refreshUI();
        } catch (e){
        //            alert(e.message);
        //            alert('this page does not have an init function!');
        }

    });

});

function jstrace(msg){
    alert(msg);
}

function getParameterByName( name ){

    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var attr = document.getElementById("content-frame").attributes;

    var results = regex.exec( attr.getNamedItem("src").value );
    if( results == null )

        return "";

    else

        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

/**
 * Backend
 */
var Backend = {
    init: function(){
        /** Called from the SWF, after being succesfully connected to the audio server */
        config.init = true;
        Frontend.refreshUI();
    },
    serverSwf: function() {
        if (navigator.appName.indexOf("Microsoft") != -1) {
            return window['audioserver'];
        } else {
            return document['audioserver'];
        }
    },
    playPause: function(){
        console.log('Backend > play song');
        Backend.serverSwf().playPause();
    },
    playSpecific: function(){
        var playlistItem =  $(this).closest('li');
        console.log('Backend > play song id: ' + playlistItem.attr('id').split('_')[1] );
        Backend.serverSwf().playSongWithId(playlistItem.attr('id').split('_')[1] ); // parent = <li>
    },
    skipForward: function(){
        console.log('Backend > skip forward');
        Backend.serverSwf().nextSong();
    },
    skipBackward: function(){
        console.log('Backend > skip backward');
        Backend.serverSwf().prevSong();
    },
    seekTo: function(val){
        var state = Backend.getState();
        if( state.songIsPlaying === true || state.songIsPaused === true ){
            console.log('Backend > seeking to '+val+'% through the song');
            Backend.serverSwf().jumpToPos(val);
        }
    },
    setVolume: function(val){
        console.log('Backend > set volume '+val+'%');
        Backend.serverSwf().setVolume(val);
    },
    addWork: function(url, playImmediately){
        if( playImmediately != undefined && playImmediately == true ){
            console.log("Backend > Add work and play immediately");
            Backend.serverSwf().addWork(url, true);
        } else {
            console.log("Backend > Add work");
            Backend.serverSwf().addWork(url, false);
        }
    },
    addAndPlay: function(url){
        console.log("Backend > Add work and play");
        Backend.serverSwf().addWork(url, true);
    },
    deleteFromPlaylist: function(){
        var playlistItem =  $(this).closest('li');
        var playlistItemId = playlistItem.attr('id').split('_')[1];

        if( playlistItemId == Backend.getState().currentSongId ) {
            Frontend.resetScrubber();
            Frontend.refreshUI();
        }

        Backend.serverSwf().removeSongWithId(playlistItemId);

        playlistItem.remove();
    },
    reorder: function(newlist){
        var idList = [];
        for(var i=0; i < newlist.length; i++ ){
            idList.push(newlist[i].split('_')[1]);
        }
        Backend.serverSwf().reorderPlaylist(idList);
        Frontend.refreshUI();
    },
    getState: function(){
        /**
         * Returns an object that contains a myriad of fun stuff about the state of the player.
         * It's all pretty self-descriptive:
           - songQueue [array]
           - songIsPlaying [bool]
           - songIsPaused [bool]
           - currentSong [obj]
           - currentSongId [number]
           - hasNextSong [bool]
           - hasPrevSong [bool]
          */
        var state = Backend.serverSwf().getAppState();
        content = $('#content-frame').contents();
        return state;
    }
};



/**
 * Modify the contents of the FrontEnd iFrame.
 */
var Frontend = {
    updateNowPlaying : function(state){
        document.getElementById('content-frame').contentWindow.updateNowPlaying(state);
    },
    updateList: function(state){


        if( config.init == true ){
            var newlist = state.songQueue;


            if( newlist.length >= 0 ){
                var playlist = content.find('#playlist').empty();

                /**
                 * FYI: IE6 & 7 do not seem to be able to use dynamically generated elements (through $.tmpl, for instance) created in this Window and insert them in the iFrame Window. I don't know why. The work around: pass the data into a function in
                 the client js file. The content is created inside the iFrame, instead of outside of it. SIGH.

                 This also applies to Frontend.updateNowPlaying.
                 */

                //$.tmpl( "playListItem", newlist ).appendTo( playlist ); //<-- doesn't work from here in IE <7... what a pity
                document.getElementById('content-frame').contentWindow.updateList(state.songQueue);


                playlist.find('.playnow').click( Backend.playSpecific );
                playlist.find('.delete').click( Backend.deleteFromPlaylist );

                if( state.currentSongId > 0 ){
                    playlist.find('li').removeClass('active');
                    playlist.find('#songid_'+state.currentSongId).addClass('active');

                }

            }else{

            }

        }

    },
    resetScrubber: function(){
        document.getElementById("content-frame").contentWindow.resetScrubber();
    },
    refreshUI: function(){
        if( config.init === true ){
            var state = Backend.getState(); // fetch state
            Frontend.updateList(state);
            Frontend.updateNowPlaying(state);

            // visually enable/disable next button
            if( state.hasNextSong == true && state.songQueue.length > 0 ){
                content.find("#btn-skip-next").removeClass('disabled');
            } else {
                content.find("#btn-skip-next").addClass('disabled');
            }

            // visually enable/disable prev btn
            if( state.hasPrevSong == true && state.songQueue.length > 0 ){
                content.find("#btn-skip-prev").removeClass('disabled');
            } else {
                content.find("#btn-skip-prev").addClass('disabled');
            }

            // visually disable play btn
            if( state.songQueue.length > 0 && state.songQueue.length > 0 ){

            //content.find("#btn-play-pause").removeClass("disabled");

            } else {
                //content.find("#btn-play-pause").addClass("disabled");
                Frontend.resetScrubber();
            }

            // determine if play or pause icon should be shown
            if( state.songIsPlaying === true ){

                content.find("#btn-play-pause").removeClass("btnstate-pause").addClass("btnstate-play");

            } else {
                content.find("#btn-play-pause").removeClass("btnstate-play").addClass("btnstate-pause");
            }

        }
    },
    updateProgressBar: function(data){
        try{
            var played = data.percentPlayed;
            if(played>100){
                played=100;
            }
            content.find('#bar-progress').width( played + '%');

            var buffered = data.percentPlayed + data.percentBuffered;
            if(buffered>100){
                buffered = 100;
            }
            
            content.find('#bar-buffered').width( buffered + '%');
            content.find('#scrubber').slider("value", data.percentPlayed);
            content.find('#song-current-position').text(data.position);
            document.getElementById("content-frame").contentWindow.updatePlayhead(data.percentPlayed);
        } catch(e){
            console.log(e);
        }
    },
    changeURI: function(href){
	var bits  =location.hash.replace("#!","").split("#");

	var hash = '';
	if(bits.length>1){
		hash = "#"+bits[1];
		document.getElementById("content-frame").contentWindow.location.hash = hash;
	}
        location.hash = "!/"+href.replace("http://"+location.host+config.baseURL,'')+hash;
    },
    changeTitle: function(title){
        document.title = title;
    },
    setIgnoreHistoryChange: function(){
        config.ignoreHistoryChange = true;
    },
    updateVolumeBar: function(data){
        try{
            document.getElementById("content-frame").contentWindow.updateVolumeControl(data);
        } catch(e){
            console.log(e);
        }
    }
}

