function AudioPlayer(params){
	if(params){
		this.container = params.container || null;
		this.template = params.template || null;
		this.activeFlashClass = params.activeFlashClass || null;
		this.inActiveFlashClass = params.inActiveFlashClass || null;
		this.playImgClass = params.playImgClass || null;
		this.pauseImgClass = params.pauseImgClass || null;
		this.transparent = params.transparent || null;
        this.noRepeat = params.noRepeat;
        this.noReplaceListeners = params.noReplaceListeners || null;
        this.prefix = (params.prefix || 'inviz' )+ '_';
	}else throw('Error in AudioPlayer');
	if(!this.container || !this.template) throw('Error in AudioPlayer');
	this.template = new Template(this.template);
	this.volume = 70;
	this.init();
}
AudioPlayer.prototype.init = function(){
	var objs = this.container.cleanWhitespace().childElements();
	if(!this.noReplaceListeners) {
		for(var i=0; i < objs.length; i++){
			var toggles = objs[i].select('[name="audio_toggle"]');
			for(var k=0; k < toggles.length; k++){
				toggles[k].observe('click', this.toggle.bindAsEventListener(this, objs[i], 0, this.prefix, this.container));
				toggles[k].removeAttribute('onClick');
			}
		}
	}
	this.status = 0;
	this.previousFile = null;
	this.previousContainer = null;
	this.previousPrefix = null;
	this.inAction = 0;
}

AudioPlayer.prototype.toggle = function(event, container, paused, prefix, parent_container){
    if(container && !this.inAction){
    if(prefix && prefix != this.prefix) {
		this.status = false; 
		this.toggle({}, this.previousContainer, 1);
	    this.container = parent_container;
	    this.prefix = prefix || 'inviz_';
	    this.init();
	    this.inAction = 0;
	    this.status = true; 
    }
	this.inAction = 1;	
	var file = container.readAttribute('file');
	if(this.previousFile == file && this.status){
  	    this.pause(container, file);
	    this.status = 0;
	} else {
	    if(this.previousFile == file){
		if(!paused) this.unpause(container, file);
		else {
            if($(this.prefix + file)) {
        		this.stop(container, file);
                $(this.prefix + file).style.display = 'block';
                this.previousFile = null;
                this.previousContainer = null;
                this.previousPrefix = null;
            } else {
                this.setPlayImage(container); //this.pause(container, file, 'rewind');
            }
        }
	    } else {
		if(this.previousFile && this.previousContainer){
		    this.stop(this.previousContainer, this.previousFile);
		    if ($(this.prefix+file) != null) $(this.previousPrefix+this.previousFile).style.display = 'block';
		}
                if ($(this.prefix+file) != null) $(this.prefix+file).style.display = 'none';
		this.play(container, file, paused);
		this.previousFile = file;
		this.previousContainer = container;
		this.previousPrefix = prefix || this.prefix;
	    }
	    this.status = !paused;
	}
	this.inAction = 0;
    }
}
AudioPlayer.prototype.play = function(container, file, paused){
	var flash_container = container.select('[name="audio_flash_container"]');
	if(!flash_container || !flash_container.length){
		throw('AudioPlayer: can not find flash container');
	}
	var URL = this.template.evaluate({
		URL	: container.readAttribute('url'),
		Time	: parseInt(container.readAttribute('time'))*1000,
		Vol	: this.volume,
		file : container.readAttribute('file'),
		title: encodeURIComponent(container.readAttribute('title')),
        uid	: container.readAttribute('uid')
	});
    var p1 = '';
    var p2 = '';
    var p3 = '';//for FF2 and opera < 9.5
    var p4 = '';//remove in future
    if(paused) {
        p1 = '<PARAM NAME="FlashVars" VALUE="pause=true"/><PARAM NAME="Play" VALUE="0"/>';
        p2 = 'FlashVars="pause=true"';
    }
    if(!this.activeFlashClass || this.transparent){
      //  p3 = '<param name="wmode" value="transparent"/>';
        p4 = ' wmode="transparent"';
    }
	flash_container[0].innerHTML = '<object id="ie_flashplayer_'+file+'" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="100%" height="100%" style="margin:-2px 0 0 -2px"><param name="allowScriptAccess" value="always" /><param name="swLiveConnect" value="true" /><param name="movie" value="'+URL+'" />'+p1+'<param name="wmode" value="transparent"/><embed id="flashplayer_'+file+'" src="'+URL+'" width="100%" height="100%" style="margin:-2px 0 0 -2px" allowScriptAccess="always" swLiveConnect="true" '+p2+p4+' type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>'; // Because fucking kriaking browsers can do that kind of shit(embed src), and fkriaging prototype also
//	ajax_call('perl_count_audio_listen');//stat
	var staturl = 'http://'+location.hostname+'/cgi-bin/my/ajax?ajax_call=1&func_name=perl_count_audio_listen&url=' + URL;
	if(!this.statitem) this.statitem = document.body.appendChild(new Element('img', {'src':staturl,'width':0,'height':0}));
	else this.statitem.src = staturl;
	if(this.activeFlashClass){
                flash_container[0].className = this.activeFlashClass;
	}
    if(paused) {
        this.setPlayImage(container);
    } else {
        this.setPauseImage(container);
    }
}
AudioPlayer.prototype.stop = function(container, file){
	var flash_container = container.select('[name="audio_flash_container"]');
	if(!flash_container || !flash_container.length){
		throw('AudioPlayer: can not find flash container');
	}
	flash_container[0].innerHTML = '';
	if(this.inActiveFlashClass){
                flash_container[0].className = this.inActiveFlashClass;
	}
	this.setPlayImage(container);
	this.status = 0;
}
AudioPlayer.prototype.pause = function(container, file, rewind){
	var flashplayer = this.getFlashPlayer(file);
	this.setPlayImage(container);
	flashplayer.SetVariable("_root.pause", "true");
    if(rewind) flashplayer.Rewind();
}
AudioPlayer.prototype.unpause = function(container, file){
	var flashplayer = this.getFlashPlayer(file);
	this.setPauseImage(container);
	flashplayer.SetVariable("_root.pause", "false");
}

AudioPlayer.prototype.getFlashPlayer = function(file){
	var flashplayer;
	if(Prototype.Browser.IE){
		flashplayer = $('ie_flashplayer_'+file);
	}else{
		flashplayer = $('flashplayer_'+file);
	}	
	if(!flashplayer){
		throw('AudioPlayer: can not find flashplayer');
	}
	return flashplayer;
}
AudioPlayer.prototype.onUnPause = function(){
	if(this.previousContainer){
		this.setPauseImage(this.previousContainer);
	}
	this.status = 1;
}
AudioPlayer.prototype.onEndMusic = function(){
    if(this.previousFile){
        var objs = this.container.cleanWhitespace().childElements();
		for(var i=0; i < objs.length; i++){
		    if(objs[i].readAttribute('file') == this.previousFile){
			this.status = 0;
			if(i == objs.length-1) this.toggle(null, objs[0], this.noRepeat && 'paused');
			else this.toggle(null, objs[i+1]);
			break;
		    }
		}
    } else throw('AudioPlayer: can not find previous file');
}
AudioPlayer.prototype.onSetVolume = function(v){
	this.volume = parseInt(v);
}
AudioPlayer.prototype.setPauseImage = function(container){
	if(container && this.pauseImgClass){
		var image = container.select('[name="audio_toggle"]');
		if(image && image.length) image[0].className = this.pauseImgClass;
	}
}
AudioPlayer.prototype.setPlayImage = function(container){
	if(container && this.playImgClass){
		var image = container.select('[name="audio_toggle"]');
		if(image && image.length) image[0].className = this.playImgClass;
	}
}
AudioPlayer.prototype.addAudio = function(container){
	if(container){
		var toggles = container.select('[name="audio_toggle"]');
		for(var k=0; k < toggles.length; k++){
			toggles[k].observe('click', this.toggle.bindAsEventListener(this, container));
		}
	}
}
AudioPlayer.prototype.removeAudio = function(container){
	if(container == this.previousContainer){
		this.stop(container, container.readAttribute('file'));
	}
}
function audio_showEditBlock(file){
	if(file){
		$('edit_author').value = $('author_'+file).innerHTML;
		$('edit_name').value = $('name_'+file).innerHTML;
                $('edit_text').value = $('text_' + file).readAttribute('value');
		$('edit_file').value = file;
		var edit = $('edit');
		var del = $('edit_button_'+file);
		edit.style.top = absPosition(del).y + del.offsetHeight;
		edit.style.display = 'block';
	}
}

var topTimeout = 0;

function addAudio(el) {
    if(Object.isElement(el)) {
	var el = $(el);
	el.stopObserving('click');
	el.removeAttribute('onClick');
	el.removeAttribute('href');
	var request = new Ajax.Request(el.readAttribute('request') + 'ajax?ajax_call=1&func_name=' + 
	    (el.readAttribute('delete') ? 'perl_delete_audio' : 'perl_add_audio'), {
	    method: 'post',
	    postBody: 'data=' + [el.readAttribute('fileid'), el.readAttribute('uid'), el.readAttribute('top')].toJSON(),
	    onSuccess: function(t){
		var answer = t.responseText.evalJSON(true)[2];
		var el = t.request.element;
		if(el.readAttribute('delete')) {
		    if(answer > 0) {
                        var containers = document.getElementsByTagName('DIV');
                        var file = el.readAttribute('fileid');
                        for(var i = 0;i < containers.length; i++)
                            if($(containers[i]).readAttribute('file') == file) containers[i].parentNode.removeChild(containers[i]);
                        if(window.audio_move != undefined) audio_move.init();
			showMessage('audio_deleted');
		    } else if(answer == 'cannot_delete') showMessage('cannot_delete_audio');
		} else {
		    if(!answer) {
			el.writeAttribute('href', '#');
			el.observe('click', addAudio.bindAsEventListener(el));
			showMessage('audio_error');
		    }
		    if(answer > 0) {
			el.parentNode.className = el.parentNode.className.replace(/links/, '');
			el.className = 'grey tdn';
			var updatedMsg = el.readAttribute('updated_msg');
			el.update(updatedMsg || 'добавлено');
			if(updatedMsg == ' ') {
			    newHelp({'target':el}, 55, 1, 150);
			    $('help_div_55').className = 'bgNo';
			    if(topTimeout) clearTimeout(topTimeout);
			    topTimeout = setTimeout(function(){closeHelp({'srcElement':$('help_div_55')}, 1)}, 5000);
			}
		    }
		    if(answer == 'audio_ratelimit') {
				el.parentNode.className = el.parentNode.className.replace(/links/, '');
				el.className = 'grey tdn';
				el.update('превышен лимит');
		    }		    
		    if(answer < 0) showMessage('too_many_audio', el);
		    if(answer == 'cannot_add') showMessage('cannot_add_audio', el);
                    if(answer == 'exists') {
                        newHelp({'target':el}, 56, 1, 150);
			el.update('');
                        $('help_div_56').className = 'bgNo';
                        if(topTimeout) clearTimeout(topTimeout);
                        topTimeout = setTimeout(function(){closeHelp({'srcElement':$('help_div_56')}, 1)}, 5000);
                    }
		}
	    }
	});
	request.element = el;
    }
    return false;
}
