var AudioObject = {
	prevAudio: 0,
	debug_mode: 0,
	curAudio: 0,
	curWallAudio: null,
	curPressed: false,
	flashVer: 0,
	preventInit: false,
	fileInfo: new Array(),
	offlineHosts:[],
	images: {
		playmode: {
			play: "http://vkontakte.ru/images/play.gif",
			pause: "http://vkontakte.ru/images/pause.gif"
		},
		editmode: {
			play: "http://vkontakte.ru/images/play.png",
			pause: "http://vkontakte.ru/images/pause.png"
		},
		icon: "http://vkontakte.ru/images/favicon.ico",
		pauseicon: "http://vkontakte.ru/images/pauseicon.ico",
		playicon: "http://vkontakte.ru/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) ? "http://vkontakte.ru/swf/AudioPlayer_wall.swf?0.9.9" : "http://vkontakte.ru/swf/AudioPlayer_mini.swf?0.9.9";
			var name = (wall) ? "/swf/AudioPlayer_wall.swf?0.9.9" : "/swf/AudioPlayer_mini.swf?0.9.9";
			var so = new SWFObject(name, id, width, "14", "7", "#FFFFFF");
			if (isWindowFocused && navigator.userAgent.indexOf("Firefox/3") == -1) {
					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 = audio_you_need_flash + (window.showBox ? "<br/><br/>" : "\n\n") + audio_do_you_want_flash;
			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(){
    var a = {};
    if(arguments.length==1){
      a = arguments[0];
    }else{
      var p = "id,host,user,file,dur,wall".split(',');
      for(var i in p){
        if(i<arguments.length)a[p[i]] = arguments[i];
      }
    }
		if(!window.Ajax || !this.offlineHosts[a.host]){
			return this.doOperate(a.id, a.host, a.user, a.file, a.dur, a.wall, a.url);
		}else{
			var ajax = new Ajax();
			var _t = this;
			ajax.onDone = function(resp, text){
				if(!text || text=="ok"){
					_t.offlineHosts[host] = false;
					return _t.doOperate(a.id, a.host, a.user, a.file, a.dur, a.wall, a.url);
				}else{
					var suff = _t.getSuff(a.wall);
					ge("player"+suff+a.id).innerHTML = text;
					ge("player"+suff+a.id).style.display = "";
					ge("player"+suff+a.id).style.paddingTop = "-5px";
					ge("line"+suff+a.id).style.display = "none";
				}
			}
			ajax.post("/audio.php", {
				act: 'checkhost',
				host:a.host
			});
		}
		return false;
	},

	doOperate: function(id, host, user, file, dur, wall, url){
		log("operate");
		if (!this.fileInfo[id]) {
      if(url){
        this.fileInfo[id] = {
          "dbid": id,
          "url": url,
          "duration": dur
        };
      }else{
        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{

			setStyles(ge('line' + suff + id),{
			  borderTop: "0px",
			  background: "no-repeat url('http://vkontakte.ru/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{
			setStyles(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;
		//setStyles(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";
				//setStyles(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;
						if(window.pagination){
							var next_offset = pagination.currentOffset + 100;
							pagination.getPageContent(next_offset, 1, function(){
								if(next_offset != pagination.realOffset) 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 : (state == "paused" ? this.images.pauseicon : 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(){
  var a = arguments;
  if(a.length == 3){
    AudioObject.operate({id:a[0], url:a[1], dur:a[2], wall:true});
  }else{
	  AudioObject.operate({id:a[0], host:a[1], user:a[2], file:a[3], dur:a[4], wall:true});
  }
}

function operate(id, host, user, file, dur){
  var a = arguments;
  if(a.length == 3){
    AudioObject.operate({id:a[0], url:a[1], dur:a[2], wall:false});
  }else{
	  AudioObject.operate({id:a[0], host:a[1], user:a[2], file:a[3], dur:a[4], wall:false});
  }
  dispatchIntro(5, {id: id});
}


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

function log(message)
{
	if(!window.debug_mode)return;
  debugLog(message);
}


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='http://vkontakte.ru/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];
    }
  setStyles(el, styles);
  return el;
}

function setStyles(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;

var posting = false;
function postAudioOnWall(hash, where_to, audio_id) {
  if (posting) {
    return;
  }
  posting = true;
  var callback = function(obj, text) {
    posting = false;
    if (text.substr(0, 1) == 'r') {
      window.location = text.substr(1);
    }
  }
  var params = {act: 'sent', a: 1, wall_hash: hash, to_id: where_to, message: '[[' + audio_id + ']]'};
  var stop = function(obj, text) {
    posting = false;
  }
  var options = {onSuccess: callback, onFail: stop, onCaptchaShow: stop, onCaptchaHide: stop};
  Ajax.postWithCaptcha('wall.php', params, options);
}

function addAudio(el, params){
	var aid = params.aid;
	if(!aid)return;
	ge('actionError'+aid).style.display = 'none';
	ge('actionMessage'+aid).style.display = 'none';
  Ajax.postWithCaptcha('audio.php', params, {onSuccess:function(res, text){
		var container = el.parentNode;
		el.parentNode.innerHTML = text;
		dispatchIntro(6, {el: ge('actions'+aid)});
	}, onFail:function(res, text) {
		if(text){
			ge('actionError'+aid).style.display = 'block';
			ge('actionError'+aid).innerHTML = text;
		}
	}});
}
