var AudioObject = {
        prevAudio: 0,
        debug_mode: 0,
        curAudio: 0,
        curWallAudio: null,
        curPressed: false,
        flashVer: 0,
        preventInit: false,
        fileInfo: new Array(),
        offlineHosts:[],
        images: {
                playmode: {
                        play: "images/play.png",
                        pause: "images/pause.png"
                },
                editmode: {
                        play: "images/play.gif",
                        pause: "images/pause.png"
                },
                icon: "images/favicon.ico",
                pauseicon: "images/pauseicon.ico",
                playicon: "images/playicon.ico"
        },

        getSuff: function(wall){
                return (wall) ? "Wall" : "";
        },

        setIcon: function(icon){
                var links = document.getElementsByTagName("link");
                for (i in links) {
                        var ico = links[i];
                        if (ico && ico.parentNode && (ico.rel == "shortcut icon")) {
                                var parent = ico.parentNode;
                                ico.setAttribute("href", icon);
                                if (isOpera()) {
                                        parent.innerHTML = parent.innerHTML;
                                }
                                else {
                                        parent.removeChild(ico);
                                        parent.appendChild(ico);
                                }
                        }
                }
        },

        getPlayer: function(current, wall){
    var created = false;
                if (!this.curVolume)
                        this.curVolume = parseInt(readCookie("audio_vol"));
                if (isNaN(this.curVolume)) {
                        this.curVolume = 80;
                        createCookie("audio_vol", this.curVolume);
                }
                var suff = this.getSuff(wall);

                var id = (wall) ? "playerWall" : "player";
    if(!ge(id)){
                        //if (wall)
                                //this.curWallAudio = null;

                        var width = (wall) ? "278" : "342";
                        var name = (wall) ? "swf/AudioPlayer_wall.swf?3" : "swf/AudioPlayer_mini.swf?3";
                        var so = new SWFObject(name, id, width, "14", "7", "#FFFFFF");
                        if (isWindowFocused)
                                so.addParam("wmode", "transparent");
                        so.addParam("swliveconnect", "true");
                        so.addParam("allowScriptAccess", "always");
                        so.addVariable("debug", window.debug_mode);
                        so.addVariable("volume", this.curVolume);
                        for(var i in this.fileInfo[current]){
        so.addVariable(i, this.fileInfo[current][i]);
                        }
                        this.flashVer = so.installedVer.major;
                        window.isValidFlash =((this.flashVer > 7) || (this.flashVer == 7 && !isOpera()));
                        so.write("player" + suff + current);//container.id);
                        created = true;
                }else{}
                var player = document["player" + suff] || window['player' + suff];
                return {player:player,created:created};
        },

        checkPlayer: function(id, wall){
    var res = this.getPlayer(id, wall);
                if (!window.isValidFlash) {
                        var message = "Для того, чтобы воспользоваться аудиосервисом, Вам необходимо установить Flash-проигрыватель." + (window.showBox ? "<br/><br/>" : "\n\n") + "Хотите перейти на страницу установки проигрывателя?";
                        var goFlash = function(){
                                if (window.hideBox)
                                        hideBox();
                                document.location = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&promoid=BIOW";
                        };
                        if (window.showBox) {
                                ge("boxMessage").innerHTML = message;
                                showBox(goFlash);
                        }
                        else {
                                if (confirm(message)) {
                                        goFlash();
                                }
                        }
                        return false;
                }
                return res;
        },

        operate: function(id, host, user, file, dur, wall){
                if(!window.Ajax || !this.offlineHosts[host]){
                        return this.doOperate(id, host, user, file, dur, wall);
                }else{
                        var ajax = new Ajax();
                        var _t = this;
                        ajax.onDone = function(resp, text){
                                if(!text || text=="ok"){
                                        _t.offlineHosts[host] = false;
                                        return _t.doOperate(id, host, user, file, dur, wall);
                                }else{
                                        var suff = _t.getSuff(wall);
                                        ge("player"+suff+id).innerHTML = text;
                                        ge("player"+suff+id).style.display = "";
                                        ge("player"+suff+id).style.paddingTop = "-5px";
                                        ge("line"+suff+id).style.display = "none";
                                }
                        }
                        ajax.post("/audio.php", {
                                act: 'checkhost',
                                host:host
                        });
                }
                return false;
        },

        doOperate: function(id, host, user, file, dur, wall){
                log("operate");
                if (!this.fileInfo[id]) {
                        this.fileInfo[id] = {
                                "dbid": id,
                                "host": host,
                                "user": user,
                                "id": file,
                                "duration": dur
                        };
                }

                var res = this.checkPlayer(id, wall);
                if (!res)        return;

                var prevWall = (this.curWallAudio != null);
                var prevAudio = (this.curAudio || this.curWallAudio);
                if (prevAudio == id && prevWall == wall) {
                        if (!wall) {
                                this.curPressed = true;
                        }
                        this.setVariable("buttonPressed", "true", wall);
                        return;
                }
                if (!wall) {
                        this.curPressed = false;
                }

                if (wall) {
                        this.curWallAudio = id;
                        this.curAudio = null;
                }
                else {
                        this.curAudio = id;
                        this.curWallAudio = null;
                }

                if (prevAudio) {
                        this.hidePlayer(prevAudio, prevWall, prevWall != wall);

                        var _t = this;
                        _t.showPlayer(id, wall, res.created);
                }
                else {
                        this.showPlayer(id, wall, res.created);
                }
                return false;
        },

        setVariable: function(func, value, wall){
                log("setVariable: " +[func,value,wall] .toString());
                var player = this.getPlayer(this.curAudio || this.curWallAudio, wall).player;
                var counter = 0;
                var interval = 0;
                var cycle = function(){
                        try {
                                if (isIE() || player.SetVariable) {
                                        player.SetVariable("audioPlayer_mc." + func, value);
                                        clearInterval(interval);
                                        return true;
                                }
                        }
                        catch (e) {
                                log(e.message);
                        }

                        if (counter++ > 3) {
                                clearInterval(interval);
                        }
                        return false;
                };
                if (!cycle()) {
                        interval = setInterval(cycle, 50);
                }
        },

        showPlayer: function(id, wall, ignoreinit){
    log(["showPlayer",id,wall,ignoreinit]);
                var suff = this.getSuff(wall);
                var player = this.getPlayer(id, wall).player;
                var mode = (window.audioEditMode) ? "editmode" : "playmode";
                if (window.audioEditMode) {
                        ge("audio" + id).className = "audioEditRowPlaying";
                        ge('line' + suff + id).style.display = "none";

                }else{

                        setStyle(ge('line' + suff + id),{
                          borderTop: "0px",
                          background: "no-repeat url('images/player.gif')",
                          position: "absolute"
                        });
                }

                ge("imgbutton" + suff + id).src = this.images[mode].pause;
                this.setIcon(this.images.playicon);

                var indent = (wall) ? 236 : 300;
                //if (!ge("toddler" + suff + id)) {
                //        ge('player' + suff + id).appendChild(createElement("div", {
                //                id: "toddler" + suff + id,
                //                className: "toddler" + suff
                //        }));
                //}
                //ge("toddler" + suff + id).style.marginLeft = Math.floor(indent + this.curVolume / 100 * 35) + "px";

                ge('player' + suff + id).style.display = "";

    if(!ignoreinit){
        //this.initPlayer(id, wall);
                }
        },

        initPlayer: function(id, wall){
                var attrs = "{volume:" +        this.curVolume;
                for(var i in this.fileInfo[id])
                {
      attrs += "," + i + ":" + this.fileInfo[id][i];
                }
                attrs += "}";
                this.setVariable("setConfig", attrs, wall);

        },

        hidePlayer: function(id, wall, fixOpera){
                var suff = this.getSuff(wall);
                if(!ge('player' + suff + id))return;
                this.setVariable("setState", "stop", wall);
                ge('player' + suff + id).style.display = "none";
                ge("player" + suff + id).innerHTML = "";
                if (window.audioEditMode) {
                        ge("audio" + id).className = "audioEditRow";
                }
                else{
                        setStyle(ge('line' + suff + id),{
                                borderTop: "dashed 1px #D8DfEA",
                                background: "none"
                        })
                }
                ge('line' + suff + id).style.display = "";
                var mode = (window.audioEditMode) ? "editmode" : "playmode";
                ge("imgbutton" + suff + id).src = this.images[mode].play;
                this.setIcon(this.images.icon);

                var indent = (wall) ? 236 : 300;
                //setStyle(ge("toddler" + suff + id), {
                //        marginLeft: Math.floor(indent + this.curVolume / 100 * 35) + "px",
                //        display: ""
                //});

                return;
        },

        setTimeoutIE: function(func, n){
                if(isIE()){func();}
                else{setTimeout(func, n);}
        },

        stateChanged: function(id, wall, state, message){
                log("stateChanged: " +[id,wall,state,message] .toString());
                var _t = this;
                var suff = this.getSuff(wall);
                var mode = (window.audioEditMode) ? "editmode" : "playmode";
                switch (state) {
                        case "stopped":
                                break;
                        case "created":
//                                if (this.preventInit != id) {
//                                this.setTimeoutIE(function(){
//                                                _t.initPlayer(id, wall);
//                                                },50);
//                                }
//                                else {
//          log("PREVENT");
//                                        this.preventInit = false;
//                                }
                                break;
                        case "volume":
                                this.curVolume = parseInt(message);
                                createCookie("audio_vol", this.curVolume);
                                break;
                        case "init":
                                ge('line' + suff + id).style.display = "none";
                                //setStyle(ge("toddler" + suff + id), {
                                //        display: "none"
                                //});
        break;
                        case "finished":
                                this.setIcon(this.images.icon);
                                ge("imgbutton" + suff + id).src = this.images[mode].play;
                                this.setTimeoutIE(function(){
                                        var next = getSiblingsIds(ge("audio" + suff + id));
                                        if (next[1] && !wall && !window.audioEditMode) {
                                                ge("imgbutton" + suff + next[1]).onclick();
                                        }
                                        else {
                                                _t.hidePlayer(id, wall, true);
                                                _t.curAudio = null;
                                                _t.curWallAudio = null;
                                                var next_offset = current_offset + 50;
                                                if(getPageContent)getPageContent(next_offset, 1, function(){
                                                        if(next_offset != current_offset) return;
                                                        var next = getSiblingsIds(ge("audios").firstChild);
                                                        if(next[1])ge("imgbutton" + suff + next[1]).onclick();
                                                });
                                        }
                                }, 0);
                                break;
                        default:
                                this.setIcon((state == "playing") ? this.images.playicon : this.images.icon);
                                ge("imgbutton" + suff + id).src = (state == "playing") ? this.images[mode].pause : this.images[mode].play;
                                if (window.audioEditMode && state != "playing" && this.curPressed) {
                                        this.setTimeoutIE(function(){
                                                _t.hidePlayer(id, wall, true);
                                                _t.curAudio = null;
                                                _t.curWallAudio = null;
                                        }, 0);
                                        return;
                                }
                                break;
                }
        }
};

function isOpera(){
        return (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
}

function isIE(){
        return (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
}

function stateChanged(id, wall, state, message){
        AudioObject.stateChanged(id, wall, state, message);
}

function operateWall(id, host, user, file, dur)
{
        AudioObject.operate(id, host, user, file, dur, true);
}

function operate(id, host, user, file, dur){
        AudioObject.operate(id, host, user, file, dur, false);
}


function flashDebug(message)
{
        log("flash debug: " + message);
}

function log(message)
{
        if(!window.debug_mode)return;
        if(!ge("debug"))document.getElementsByTagName('body')[0].appendChild(createElement("div",{id:"debug"}));
        ge("debug").innerHTML += message + "<br/>";
}


var startSiblings;

function getSiblingsIds(elem){
        var prev, next, el = elem;
        while (el.previousSibling) {
                prev = el = el.previousSibling;
                if (prev.nodeType != 3)
                        break;
                prev = null;
        }
        el = elem;
        while (el.nextSibling) {
                next = el = el.nextSibling;
                if (next.nodeType != 3)
                        break;
                next = null;
        }
        return [prev ? prev.id.match(/(\d+)/)[1] : 0, next ? next.id.match(/(\d+)/)[1] : 0];
}

function createCookie(name,value,days) {
        if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
}

function player_DoFSCommand(command, args) {
         eval(args);
}
function playerWall_DoFSCommand(command, args) {
         eval(args);
}

function showLyrics(id, lid) {
  if (ge('lyrics'+id).shown != 1) {
   show(ge('lyrics'+id));
                 var ajaxLyrics = new Ajax();
                 ajaxLyrics.onDone = function(ajaxLyrics, responseText){
                         ge('lyrics'+id).innerHTML = "<div style='margin:5px 10px 15px 40px;'>"+responseText+"</div>";
    ge('lyrics'+id).shown = 1;
                 };
                 ajaxLyrics.post('/audio.php', {
                         'act': 'getLyrics',
                         'lid': lid
                 });
                 ge('lyrics'+id).innerHTML = "<div style='text-align: center; height: 50px; padding: 30px 10px 10px 10px'><img valign='middle' src='images/progress7.gif'></div>";
                } else {
   ge('lyrics'+id).innerHTML = "";
   ge('lyrics'+id).shown = 0;
   hide(ge('lyrics'+id));
                }
}

var isWindowFocused = true;

function createElement(name, attrs, styles){
  var el = document.createElement(name);
    for(attr in attrs){
      el[attr] = attrs[attr];
    }
  setStyle(el, styles);
  return el;
}

function setStyle(el, styles){
  if(el && el.style){
    for(st in styles){
      el.style[st] = styles[st];
    }
  }
}

fixOperaTimeout = 0;

if(window.addEventListener){
window.addEventListener("blur", function(){
        isWindowFocused = false;
}, false);
window.addEventListener("focus", function(){
        isWindowFocused = true;
}, false);

window.addEventListener("scroll", function(){
        if(isOpera()){
                //fix opera transparent flash - refresh page head
                clearTimeout(fixOperaTimeout);
                fixOperaTimeout = setTimeout(function(){
                        head = document.getElementsByTagName("head")[0];
                        head.innerHTML = head.innerHTML;
                }, 300);
        }
}, false);
}

window.debug_mode = false;

