function debug(str) {
    try {
        console.log("[debug] "+str);
    } catch (e) {

    }
}

function printPlayTime(t, full) {

    var hours = Math.floor(t / 3600);
    var minutes = Math.floor(t / 60);
    var seconds = Math.floor(t) % 60;

    if (hours > 0 || full) {
        return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
    } else if (minutes > 0) {
        return (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
    } else {
        return "00:" + (seconds < 10 ? "0" + seconds : seconds);
    }

};

function jsError(msg) {
    alert(msg);
}

function pingBack(backchannel) {

    if (window.playerclient.pingCallback) {
        window.playerclient.pingCallback();
    }
    
}

function initialized(id,w,h) {
    // alert("initialized "+id+","+w+","+h);
    window.setTimeout(function() {
        try {
            window.playerclient.initCallback(w,h);
        } catch (e) {
            alert(e);
        }
    },50);
}

function flash(name) {
	return window.document[name];
}

var PlayerClient = function(opts) {

    if (!opts) {
        opts = {};        
    }

    this.opts = {
        cityplayRoot: opts.cityplayRoot||""
    }

    this.onInitCallback = opts.onInitCallback;

    this.init();

    this.evListeners = [];


}

PlayerClient.prototype = {

    init : function(){

        this.clientid = "_client"+(new Date().getTime());

        var clientplayerdiv = $("<div/>");
        clientplayerdiv.attr("id", this.clientid);
        clientplayerdiv.css("width", "1px");
        clientplayerdiv.css("height", "1px");
        clientplayerdiv.css("background", "black");
        clientplayerdiv.appendTo($("#playerclient"));

        var swf = swfobject.embedSWF(this.opts.cityplayRoot+"cityplay.swf", this.clientid, "50", "50", "9.0.124", "swfobject/expressInstall.swf", {}, {
            wmode: "transparent", "allowScriptAccess":"always", name: this.clientid
        }, {});

    },

    swf : function() {
        return this.swf_;
    },

    callJs : function(funcname, args) {

    },

    ping : function(cb) {
        this.pingCallback = cb;
        this.swf().pingPlayer("_popup");
    },

    playerExists : function() {
        return this.swf().pingPlayer("_popup");
    },

    player : function(cb) {

        var self = this;

        if (!self.playerExists_) {
            self.openPlayer(cb);
        } else {

            if (cb) {
                cb(this.swf());
            }

        }

    },

    initCallback : function(stagewidth, stageheight) {

        this.stagew = stagewidth;

        this.stageh = stageheight;

        this.swf_ = window.document[this.clientid];

        this.swf_.initPlayer(this.clientid);

        this.swf_ = window.document[this.clientid];

        var self = this;

            this.ping(function() {
                self.bindClientToPlayer();
                self.playerExists_ = true;
                if (this.onInitCallback) {
                    this.onInitCallback(this);
                }
            })

        window.setInterval(function() {
            self.playerExists_ = false;
            self.ping(function() {
                self.playerExists_ = true;
            })
        }, 3000);


    },

    currentlyPlaying : function(trackjson) {
        var track = JSON.parse(trackjson);
        $("#player-links .controller [handle='control']").attr("class", track.stat);
        $("#player .album").html(track.opts.album);
        $("#player .song").html(track.title);
        $("#player .artist").html(track.opts.artist);
        $("#player .download-button").attr("href", track.url);
    },

    onplay : function(id, trackjson) {

        var track = JSON.parse(trackjson);

        this.curtrack = track;

        $("#player-links .controller [handle='control']").attr("class", track.stat);
        $("#player .album").html(track.opts.album);
        $("#player .song").html(track.title);
        $("#player .artist").html(track.opts.artist);
        $("#player .download-button").attr("href", track.url);

        for (var k in this.evListeners) {
            this.evListeners[k].onplay(track);
        }

    },

    onpause : function(id, trackjson) {
        var track = JSON.parse(trackjson);
        $("#player-links .controller [handle='control']").attr("class", "paused");
        $("#player .download-button").attr("href", track.url);
        for (var k in this.evListeners) {
            this.evListeners[k].onpause(track);
        }
    },

    onstop : function(id, trackjson) {
        var track = JSON.parse(trackjson);
        $("#player-links .controller [handle='control']").attr("class", "stopped");
        for (var k in this.evListeners) {
            this.evListeners[k].onstop(track);
        }
     },

    whilePlaying : function(pos, duration) {

        $("#player .pos").html(Player.printPlayTime(pos));

        $("#player .progress b").css("width", (100*pos/duration)+"%");

        $("#player .duration").html(Player.printPlayTime(duration));

    },

    focus : function() {

        // this.player(function(swf) {
        if (this.playerExists_) {
            this.swf().callRemoteJs("_popup", "window.focus");
            this.swf().callRemoteJs("_popup", "window.alert", "Here's your boombox!");
        } else {
            this.openPlayer();
        }
        // });

    },
    
    bindClientToPlayer : function() {
        this.swf().callRemoteJs("_popup", "window.player.bindClient", this.clientid);
    },
    
    openPlayer : function(cb) {
        try {
            this.onInitCallback = cb;
            var screenx = (this.stagew-600)/2;
            var screeny = (this.stageh-235)/2;
            this.popwin = window.open("player.jsp", "popup", "width=456,height=256,scollbars=0,status=0,navigation=0,screenX="+screenx+",screenY="+screeny);
            // this.popwin.focus();
        } catch (e) {
            alert("error opening player "+e);
        }
    },

    remotePlayerInitialized : function(win, player) {
        var self = this;
        window.setTimeout(function() {
            win.player.bindClient(self.clientid);
            if (self.onInitCallback) {
                self.onInitCallback(self.swf());
            }
        }, 50);
    },

    addTrack : function(idsong, mp3, title, opts) {
        this.swf().callRemoteJs3("_popup", "window.player.addTrack", idsong, mp3, title);
    },

    playTrack : function(idsong) {
        this.player(function(swf) {
            swf.callRemoteJs1("_popup", "window.player.playTrack", idsong);
        });
    },

    playTrackAt : function(pos) {
        this.player(function(swf) {
            swf.callRemoteJs1("_popup", "window.player.playTrackAt", pos);
        });
    },

    play : function() {
        this.player(function(swf) {
            try {
                if (this.curtrack) {
                    swf.callRemoteJs1("_popup", "window.player.playTrack", this.curtrack.id);
                } else {
                    swf.callRemoteJs("_popup", "window.player.play");
                }
            } catch (e) {
                alert(e);
            }
        });
    },

    stop : function() {
        this.player(function(swf) {
            swf.callRemoteJs("_popup", "window.player.stop");
        });
    },

    pause : function() {
        this.player(function(swf) {
            try {
                swf.callRemoteJs0("_popup", "window.player.pause");
            } catch (e) {
                alert(e);
            }
        });
    },

    rewind : function() {
        this.player(function(swf) {
            swf.callRemoteJs0("_popup", "window.player.prevTrack");
        });
    },

    nextTrack : function() {
        this.player(function(swf) {
            swf.callRemoteJs0("_popup", "window.player.nextTrack");
        });
    },

    prevTrack : function() {
        this.player(function(swf) {
            swf.callRemoteJs("_popup", "window.player.prevTrack");
        });
    },

    initElements_ : function() {

    },

    prepareElem_ : function(a$) {

        try {

            var self = this;

            var num = new Date().getTime();

            var trackid = "track-" + num;

            a$.wrap('<span id="' + trackid + '" class="mp3-track"/>');

            var track$ = $("#" + trackid);

            a$.attr("action", "sound-play");

            a$.attr("track", "#" + trackid);

            var song = a$.attr("song");

            track$.attr("song", song);

            a$.click(function() {
                self.play(song);
                return false;
            });


            if (!a$.attr("no-icon")) {

                var play$ = $("<a>");
                play$.attr("href", a$.attr("href"));
                play$.attr("track", "#" + trackid);
                play$.addClass("mp3-play-");
                play$.attr("action", "sound-play");
                play$.html('<img src="img/common/Play_weiss.png"/>');

                track$.append(play$);

                play$.click(function() {
                    self.play(song);
                    return false;
                });

                var pause$ = $("<a>");
                pause$.attr("class", "mp3-pause-");
                pause$.attr("track", "#" + trackid);
                pause$.attr("action", "sound-pause");
                pause$.html('<img src="img/common/Pause_off.png"/>');

                track$.append(pause$);
                pause$.click(function() {
                    self.pause(song);
                    return false;
                });

            }

        } catch (e) {
            alert(e);
        }

    },

    registerEventListener : function(listener) {
        this.evListeners.push(listener);
    }

}
