/**** /sharedfiles/js/audme/swfobject-n.js ****/
/* SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();
;

/**** /sharedfiles/js/audme/globalScripts.js ****/
if(!$defined(console)){
	var console = [];
	console.log=function(){};
}
log = console.log;

var globalHashModify = false;
var GlobalHost = location.hostname;

var GlobalSongsQueue = {};
GlobalSongsQueue.ids = [];
var nowGlobalId = false;
var defaultDocumentTitle = lang["default_document_title"];
var currentDocumentTitle = defaultDocumentTitle;
var miscCookie = new Hash.Cookie('misc', {
	autoSave: true,
	path: '/',
	duration: 365
});
var playerCookieVolume = new Hash.Cookie('vol', {
	autoSave: true,
	path: '/',
	duration: 365
});

var playerCookie = new Hash('player');

//Переменная-контейнер
var playlists;

var jsonRequest;

var coverImgs = [new Image, new Image, new Image, new Image, new Image, new Image, new Image];
coverImgs[0].src = "/images/songCov.png";
coverImgs[1].src = "/images/songCovD.png";
coverImgs[2].src = "/images/songCovH.png";
coverImgs[3].src = "/images/songCovP.png";
coverImgs[4].src = "/images/plCov.png";
coverImgs[5].src = "/images/songCovL.png";
coverImgs[6].src = "/images/loader-s.gif";

window.addEvent('domready', function(){
	
	jsonRequest = new Request.JSON({
		url: "/playlists-get/", 
		onComplete: function(resp){

			playerCookie.set('playlists', resp);
			playlists = playerCookie.get('playlists');
			playlists = new Hash(playlists);
			
			generatePlaylistTitles();
		}
	}).get();
	
	
	//------------------------------------------------
	//startCHT.delay(4000);
	
	initGlobalPlayer('globalPlayer');
	
	Sortables.implement({
		start : function(event, element){
			if (!this.idle) return;
			this.idle = false;
			this.element = element;
			this.opacity = element.get('opacity');
			this.list = element.getParent();
			this.clone = this.getClone(event, element);
			
			this.drag = new Drag.Move(this.clone, {
				snap: this.options.snap,
				container: this.options.constrain && this.element.getParent(),
				droppables: this.getDroppables(),
				onSnap: function(){
					event.stop();
					this.clone.setStyle('visibility', 'visible');
					this.element.set('opacity', this.options.opacity || 0);
					this.fireEvent('start', [this.element, this.clone]);
				}.bind(this),
				onEnter: this.insert.bind(this),
				onCancel: this.reset.bind(this),
				onComplete: this.end.bind(this)
			});
			
			this.clone.position(element.getPosition()).inject(document.body);
			this.drag.start(event);
		}
	});
	
	
	initSortables();
	initSongsOperations();
			
	//REQUEST
	$('searchBox').addEvent('submit', function(e){
		if (e) e.stop();

		if (globalSearchRequest) globalSearchRequest.cancel();
		window.fireEvent('ce_requestcompleted');		
		location.hash = "#"+$('searchBox').q.value.replace(/ /g, "_");
		globalHashModify = true;
		
		var page = 0;
		var response = null;
		
		var queryArray = [$('searchBox').q.value, page, 1, 0, ""];
		$('searchNavi').getElement('.page').set('html', '&nbsp;');
		$('searchNavi').getElement('.next').removeClass('show');
		$('searchNavi').getElement('.back').removeClass('show');
		
		window.fireEvent('ce_requeststarted');
		requestRecursive(queryArray);
	})
	
	if ($('searchNavi')) {
		$('searchNavi').getElement('.back').addEvent('click',function(){
			if (!$('searchNavi').getElement('.back').hasClass('disabled')) {
				globalSearchInfo[3]--;
				globalSearchInfo[1] = globalSearchInfo[5][globalSearchInfo[3]];
				$('searchNavi').getElement('.page').set('html', globalSearchInfo[3] + 1);
				window.fireEvent('ce_requeststarted');
				requestRecursive(globalSearchInfo);
			}
		});
		$('searchNavi').getElement('.next').addEvent('click',function(){
			if (!$('searchNavi').getElement('.next').hasClass('disabled')) {
				
				globalSearchInfo[1] = ($defined(globalSearchInfo[7]) && $defined(globalSearchInfo[7][globalSearchInfo[3]]))?(globalSearchInfo[7][globalSearchInfo[3]] + 1):(globalSearchInfo[1] + 1);
				globalSearchInfo[3]++;
				
				$('searchNavi').getElement('.page').set('html', globalSearchInfo[3] + 1);
				window.fireEvent('ce_requeststarted');
				requestRecursive(globalSearchInfo);
			}
		});
	}
	
	window.addEvent('ce_requestcompleted', function(){
		
		$('searchNavi').getElement('.back').removeClass('disabled');
		$('searchNavi').getElement('.next').removeClass('disabled');
		
		if (globalSearchInfo)
		if (globalSearchInfo[4] != "nonextpage" && globalSearchInfo[1] < 9 && $('playlistSearch').getElements('.playBox')) {
			$('searchNavi').getElement('.next').addClass('show');
		} else {
			$('searchNavi').getElement('.next').removeClass('show');
		}
		
		if (globalSearchInfo)
		if (globalSearchInfo[3] > 0) {
			$('searchNavi').getElement('.back').addClass('show');
		} else {
			$('searchNavi').getElement('.back').removeClass('show');
		}
		if (globalSearchInfo)
		var page = (globalSearchInfo[3] !== 0) ? globalSearchInfo[3] + 1 : "&nbsp;";
		$('searchNavi').getElement('.page').addClass('show').set('html', page);
		$$('.searchListContainer')[0].removeClass('loading').getElement('.content').removeClass('loadingcont');

		
		if (
			location.hash.substring(1).indexOf("playlist/h") === 0 
		) {
			$('searchNavi').getElement('.next').removeClass('show');
		}
	})
	
	window.addEvent('ce_requeststarted', function(){
		$$('.searchListContainer')[0].addClass('loading');
		$('searchNavi').getElement('.next').addClass('disabled');
		$('searchNavi').getElement('.back').addClass('disabled');
	})
	
	window.addEvent('ce_requestcontinues', function(){
		
		$$('.searchListContainer')[0].removeClass('loading').getElement('.content').addClass('loadingcont');
	})
	
	if (location.hash.substring(1).indexOf("direct::") === 0) {
		directPlay("http://"+GlobalHost+"/"+location.hash.substring(1).replace("direct::", ""));
	} else if (location.hash.substring(1).indexOf("direct-") === 0) {
		directPlay("http://"+GlobalStreamHost+"/"+location.hash.substring(1).replace("direct-", ""));
	} else if (location.hash.substring(1).indexOf("direct/m/") === 0) {
		directPlay("http://music.appsmail.ru/"+location.hash.substring(1).replace("direct/m/", ""), "m");
	} else if (location.hash.substring(1).indexOf("playlist/h") === 0) {
		playlistPlay(location.hash.substring(1));
	} else {
		var query = decodeURIComponent(location.hash.substring(1).replace(/_/g, " "));
		if (query) {
			$('searchBox').q.value = query;
			$('searchBox').fireEvent('submit');
		}
	}
	
	if ($$('#globalPlayerTitleBox .cov')[0]) {
	
		$$('#globalPlayerTitleBox .cov')[0].addEvent('mouseenter', function(){
			var pt = $('globalPlayerTitle');
			var w = pt.getWidth();
			var boxW = $('globalPlayerTitleBox').getWidth() - 30;
			if (w > boxW) {
				pt.set('morph', {
					duration: ((w - boxW) * 10)
				}).morph({
					'left' : - (w - boxW)
				});
			}
		})
		$$('#globalPlayerTitleBox .cov')[0].addEvent('mouseleave', function(){
			var pt = $('globalPlayerTitle');
			var w = pt.getWidth();
			var boxW = $('globalPlayerTitleBox').getWidth() - 30;
			if (w > boxW) {
				pt.set('morph', {
					duration: 800
				}).morph({
					'left' : 0
				});
			}
		})
	}
	
	$$('.infoBlockText').each(function(el,i){
		if (miscCookie.get('misc') && miscCookie.get('misc')['news'][el.id] == true) {
			el.setStyle('display', 'none');
		} else {
			el.getElement('.cl').addEvent('click', function(){
				var mcn = miscCookie.get('misc');
				if (!mcn) mcn = {};
				if (mcn['news']) {
					mcn['news'][el.id] = true;
					miscCookie.set('misc', mcn);
				} else {
					mcn['news'] = {};
					mcn['news'][el.id] = true;
					miscCookie.set('misc', mcn);					
				}
				el.setStyle('display', 'none');
			})
		}
	})
	
	
	if ($('searchBox')) $('searchBox').q.focus();
})

window.addEvent('hashchange', function(){
	location.reload();
})

var oldHash = location.hash;
(function(){
	if (location.hash !== oldHash && !globalHashModify) {
		oldHash = location.hash;
		window.fireEvent('hashchange');
	} else {
		globalHashModify = false;
		oldHash = location.hash;
	}
}).periodical(1000);


function startCHT() {
	dummyRequest = new Request({
		url: "/sharedfiles/cht.php",
		method: 'get',
		onComplete: function(resp){
			resp = null;
			dummyRequest = null;
			startCHT.delay(35000);
		}
	}).send("ch="+Math.random().toString().substring(2,8));	
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Инициализация обработчиков событий песен ////////////////////////////////
function initSongsOperations(plId) {
	
	if (plId) plEl = $(plId);
	else plEl = $(document.body);
	
	plEl.getElements('.playBox').each(function(el){
		el.getElement('.song').removeEvents('click').addEvent('click',function(){
			rmSongFromQueue($(el.id)); //убираем песню из очереди, вдруг она там есть
			play(el.id);
		})
	})
	
	plEl.getElements('.playBox .delete').each(function(el){
		el.addEvent('click', function(){
			deleteSong(el.getParent('.playBox').id);
			return false;
		})
	})

	plEl.getElements('.playBox .rename').each(function(el){
		el.addEvent('click', function(){
			renameSong(el.getParent('.playBox').id);
			return false;
		})
	})

	plEl.getElements('.playBox .playnext').each(function(el){
		el.addEvent('click', function(){
			if (el.hasClass('a')) {
				rmSongFromQueue(el.getParent('.playBox'));
			} else {
				el.addClass('a');
				GlobalSongsQueue.ids.push(el.getParent('.playBox').id);
				el.set('html', GlobalSongsQueue.ids.length);
			}
			return false;
		})
	})
	
	plEl.getElements('.playBox .getlink').each(function(el){
		el.addEvent('click', function(){
	
			var title = el.getParent('.playBox').getElement('.songTitle').get('text').replace(/,/g, " ");
			var fp = el.getParent('.playBox').getAttribute('filepath');
			if (!fp.match(/music\./)) {
				var fileAttrs = fp.match(/\/mp3\/(.*)\//);
				if (!fileAttrs) {
					fileAttrs = fp.match(/\/mp3rm\/(.*)\//);
					var RM = true;
				}
				
				var href = (RM)?
					"http://"+GlobalHost+"/#direct-mp3rm/"+fileAttrs[1]+"/"+encodeURIComponent(title)
					:
					"http://"+GlobalHost+"/#direct-mp3/"+fileAttrs[1]+"/"+encodeURIComponent(title);
				var fp_titled = fp.match(/http:.*\//)[0]+"enct:"+encodeURIComponent(title);
			} else {
				var trackHash = fp.match(/music\..*\.ru\/(.*?)\.mp3/)[1];
				var href = "http://"+GlobalHost+"/#direct/m/"+trackHash+"/"+encodeURIComponent(title);
				var fp_titled = fp+"?enct:"+encodeURIComponent(title);
			}
			showInfoWindow(
				lang["direct_link"]
				+"<br /><textarea readonly='true' onclick='this.select()' class='infoFieldTA'>"
				+href
				+"</textarea><br /><br />"
				+lang["direct_link_code"]
				+"<textarea readonly='true' onclick='this.select()' class='infoFieldTA'>"
				+'<a href="'+href+'">'+title+'</a>'
				+"</textarea><br /><br />"
				+"<table width='100%'><tr><td width='100%' valign='bottom'>"+lang["outplayer_code"]+"</td><td>"
				+'<object width="290" height="24"><param name="bgcolor" value="#777777" /><param name="movie" value="http://'+GlobalHost+'/sharedfiles/swf/out/player3.swf" /><param name="flashVars" value="soundFile='+fp_titled+'&amp;titles='+encodeURIComponent(title)+'" /><embed src="http://'+GlobalHost+'/sharedfiles/swf/out/player3.swf" type="application/x-shockwave-flash" width="290" height="24" flashVars="soundFile='+fp_titled+'&amp;titles='+encodeURIComponent(title)+'" bgcolor="#777777" /></object></td></tr></table>'
				+"<textarea readonly='true' onclick='this.select()' class='infoFieldTA'>"
				+'<object width="290" height="24"><param name="movie" value="http://'+GlobalHost+'/sharedfiles/swf/out/player3.swf" /><param name="flashVars" value="soundFile='+fp_titled+'&amp;titles='+encodeURIComponent(title)+'" /><param name="wmode" value="transparent" /><embed src="http://'+GlobalHost+'/sharedfiles/swf/out/player3.swf" type="application/x-shockwave-flash" width="290" height="24" wmode="transparent" flashVars="soundFile='+fp_titled+'&amp;titles='+encodeURIComponent(title)+'" /></object>'
				+"</textarea>"
			);
			return false;
		})
	})	
		
	plEl.getElements('.playBox').each(function(el){
		setSongDownloadLink(el);
	});
	
	plEl.getElements('.playBox .songTitle').each(function(el){
		el.setAttribute('title', el.get('text'));
	})
}

function setSongDownloadLink(songEl) {
	var el = songEl.getElement('.download');
	el.set('html', '');
	var href = songEl.getAttribute('filepath');
	var linkEl = new Element('a', {
		'href' : href.replace('/mp3/', '/mp3rm/download/').replace('/mp3rm/', '/mp3rm/download/').replace('http://out', 'http://dwl')
	});
	linkEl.inject(el);
}

/////////////////////////////// Инициализация обработчиков событий песен ////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////


function showInfoWindow(cnt, height) {
	
	if (!height) height = "";
	
	var html = 
	'<div class="r-star-login infoWindow"><div class="cn tl"></div><div class="cn tr"></div>'
	+'<div class="closer" onclick="closeInfoWindow(this)">x</div><div class="icontent" style="height:'+height+'px"><div class="contentBlock">'+cnt+'</div></div>'+
	'<div class="cn bl"></div><div class="cn br"></div></div>';
	var id = 'infoWindow_'+Math.random();
	var el = new Element('div', {
		'id' : id,
		'class' : 'infoWindow',
		'styles' : {
			'position' : 'absolute',
			'display' : 'none',
			'top':'20%',
			'width':'48%',
			'left':'26%',
			'z-index' : 100000000,
			'opacity' : 0
		},
		'html' : html
	}).set('morph', {
		'duration':250
	});
	el.inject(document.body).setStyles({
		'display': 'block'
	}).setStyles({'top': Math.round((document.body.getHeight() / 2 + document.html.scrollTop) - el.getHeight() / 2)}).morph({'opacity':1});
	
	var SWIObj = {
		"id": id,
		changeContent: function(nCnt) {
			contEl = el.getElement('.contentBlock');
			contEl.set('morph',{
				duration: 250,
				onComplete: function() {
					contEl.set('html', nCnt).set('morph',{
						onComplete: function(){}
					}).morph({'opacity':1});
				}
			}).morph({'opacity':0});
		},
		close: function(interval) {
			if (!interval) interval = 0;
			(function(){
				if (el && el.getElement('.closer')) closeInfoWindow(el.getElement('.closer'))
			}).delay(interval*1000);
		},
		element: el,
		hideCloser: function(){
			this.element.getElement('.closer').setStyles({'visibility':'hidden'})
		},
		showCloser: function(){
			this.element.getElement('.closer').setStyles({'visibility':'visible'})
		}
	}
	
	return SWIObj;
}

function closeInfoWindow(closer) {
	el = $(closer).getParent('.infoWindow');
	el.set('morph',{
		onComplete: function() {
			el.dispose();
		},
		'duration':250
	}).morph({'opacity':0});
}


function initDrag() {
	$$('.playListContainer').each(function(el){
		new Drag.Move(el,{
			handle: el.getElement('.topBlock .title')//,
			//container: $('layout')
		});
	});
}

function deleteSong(sId) {
	elem = $(sId);
	rmSongFromQueue(elem); //удаление песни из GlobalQueue
	var parentPlaylist = elem.getParent('.playListContainer');
	if (!parentPlaylist) {
		if (elem.getParent('.searchListContainer')) {
			elem.dispose();
		}
	} else {
		var pId = parentPlaylist.id;
		if (playlists[pId].songs) {
			playlists[pId].songs.each(function(el){
				if (el.id == sId) {
					playlists[pId].songs.erase(el);
					elem.dispose();
					//break;
				}
			})
			playerCookie.set('playlists', playlists);
			saveUserPrefs();
		}
	}
}

function renameSong(sId) {
	
	elem = $(sId);
	var oldArtist = elem.getElement('.artist').get('text');
	var oldTitle = elem.getElement('.title').get('text');
	
	var newArtist = prompt(lang["artist"], oldArtist);
	if (newArtist) var newTitle = prompt(lang["track_title"], oldTitle);
	
	if (newArtist && newTitle) {
	
		var parentPlaylist = elem.getParent('.playListContainer');
		if (!parentPlaylist) {
			if (elem.getParent('.searchListContainer')) {
				//elem.dispose();
			}
		} else {
			var pId = parentPlaylist.id;
			if (playlists[pId].songs) {
				playlists[pId].songs.each(function(el){
					if (el.id == sId) {
						
						el.artist = newArtist;
						el.title = newTitle;
						elem.getElement('.artist').set('html', newArtist);
						elem.getElement('.title').set('html', newTitle);
					}
				})
				playerCookie.set('playlists', playlists);
				saveUserPrefs();		
			}
		}
	}
}


function rmSongFromQueue(songEl) {
	if (GlobalSongsQueue.ids.contains(songEl.id)) {
		songEl.getElement('.playnext').removeClass('a').set('html', '');
		GlobalSongsQueue.ids.erase(songEl.id);
		GlobalSongsQueue.ids.each(function(id,i){
			if ($(id)) {
				iconEl = $(id).getElement('.playnext');
				iconEl.set('html', i + 1);
			} else {
				GlobalSongsQueue.ids.erase(id);
			}
		});
	}
}


function loadUserPrefs() {
	
}

/******* Сохранение на сервере данных о плейлистах пользователя.
	paramsObj - для передачи сообщения об удалении.
*/
function saveUserPrefs(paramsObj) {
	var requestObj = playerCookie.playlists;
	if (paramsObj && paramsObj['delete']) {
		requestObj[paramsObj['delete']] = {'deleted':true}
	}
	new Request({
		method: 'post', url: '/playlists-save/'
	}).send({
		'data' : requestObj
	});
}


/******** Генерирует кликеры плейлистов (без генерации самих плейлистов).
	Запускается при загрузке страницы. 
	Если ни одного плейлиста нет сейчас в переменной-хранилище (playlists), 
	автоматически создаётся пустой новый плейлист.
*/
function generatePlaylistTitles() {
	if (playlists) {
		$('playlistsTitles').set('html', '');		
		var extI;
		playlists.each(function(el,i){
			extI = i;
			addPlaylistTitle(el.id);
			//generatePlaylist(el.id); //чтобы включить генерацию плейлистов сразу при загрузке страницы
			//$(el.id).removeClass('display');
		});
		if (!extI) {
			createPlaylist('blank', lang["new_blank_playlist"]);
		}
	}
	initPlaylistsSortables();
	setPlaylistsTitlesScroll();
	window.addEvent('resize', setPlaylistsTitlesScroll);
}


function initPlaylistsSortables() {

	var sorted = false;
	playlistsSortables = new Sortables('#playlistsTitles', {
		snap: 4,
		revert: true,
		clone: true,
		/*constrain: true,*/
		onStart: function(el, el1) {
			
			el.addClass('dragging');
			el1.addClass('draggingClone');
			var pl = el.getParent('.playListContainer');
			if (pl) fromSortId = pl.id;			
		},
		onSort: function(el) {
			sorted = true;
		},
		onComplete: function(el) {
			el.removeClass('dragging');
			
			if (sorted) {
				var newPlaylists = {};
				$('playlistsTitles').getElements('.playlistTitle').each(function(el,i){
					var pid = el.id.replace('clicker_', '');
					newPlaylists[pid] = playlists[pid];
				})
				playlists = new Hash(newPlaylists);
				playerCookie.set('playlists', playlists);
							
				sorted = false;
				saveUserPrefs();
			}
		}
	});
}


/******** Создает/показывает/скрывает плейлист (при нажатии на кликер плейлиста).
	plId - идентификатор плейлиста.
	Плейлист создаётся при потпытке показать в его первый раз после загрузки страницы.
	Одновременно меняет (по принципу toggle) статус показа плейлиста и его кликера.
*/
var playlistZIndex = 10000;
function togglePlaylist(plId) {
	if ($(plId)) {
		$(plId).toggleClass('display');
	} else {
		generatePlaylist(plId);
		$(plId).addClass('display');
		//initSortables();
	}
	
	if ($(plId).hasClass('display')) {
		playlistZIndex++;
		$(plId).setStyle('z-index', playlistZIndex);
	}
	
	$('clicker_'+plId).toggleClass('showed');
}


/******** Генерирует плейлист (визуально).
	plId - идентификатор плейлиста.
	Для генерации песен исползует переменную-хранилище (playlists).
*/
var ieFirst = null;
function generatePlaylist(plId) {
	var plObj = playlists[plId];
	var dp = $('dummyPlaylist').clone();
	dp.set('id', plObj.id);
	dp.getElement('.titleText').set('html', plObj.title);
	dp.inject($$('.playlistsBox')[0]);
	dp.setStyles({
		'display' : 'block'
	});
	
	if (plObj.songs) {
		var plHtml = "";
		plObj.songs.each(function(el,i){
			var songHtml = '<div class="playBox" id="'+el.id+'" filepath="'+el.filepath+'"><div class="song"><i class="cov"></i><span class="songTitle"><span class="artist">'+el.artist+'</span> — <span class="title">'+el.title+'</span></span></div><div class="songHandle"><i class="playnext" title="'+lang["song_playnext"]+'"></i><i class="delete" title="'+lang["song_delete"]+'"></i><i class="download" title="'+lang["song_download"]+'"></i><i class="getlink" title="'+lang["song_link"]+'"></i><i class="rename" title="'+lang["song_rename"]+'"></i><i class="drag" title="'+lang["song_drag"]+'"></i></div></div>';
			plHtml += songHtml;
		});
		dp.getElement('.playlist').set('html', plHtml);
	}
	
	initPlaylist__($(plId));
	initDrag();
	
	//IE fix playlist appear
	if (!ieFirst && Browser.Engine.trident) {
		$(plId).style.top = 0;
	}	
}


/******** Генерирует кликер плейлиста.
	plId - идентификатор плейлиста.
	Для генерации плейлиста и песен исползует переменную-хранилище (playlists), 
	требует существования там id и title указанного плейлиста.
*/
function addPlaylistTitle(plId) {
	var el = playlists[plId];
	var np = new Element('div', {
		'class' : 'playlistTitle',
		'id' : 'clicker_'+el.id,
		'html' : '<span>'+el.title+'</span>'
	})
	
	np.addEvent('click', function(){
		togglePlaylist(el.id);
	})
	np.inject($('playlistsTitles'));
	initPlaylistsSortables();
	setPlaylistsTitlesScroll();//												!!!!!!!!!!!!!!!!!!!!
}

function setPlaylistsTitlesScroll() {
	var wholeWidth = 0;
	$$('#playlistsField .playlistTitle').each(function(el) {
		wholeWidth += el.getWidth() + 10*2;
	});
	
	var boxWidth = $('playlistsTitlesBox').getWidth();
	
	if (wholeWidth > boxWidth) {
		
		var rate = wholeWidth / boxWidth;
		var left = $('playlistsTitles').getStyle('left').toInt();
		
		if (left < 0) $('playlistsField').addClass('showL');
		else $('playlistsField').removeClass('showL');
		
		if ((left + wholeWidth) > boxWidth) $('playlistsField').addClass('showR');
		else $('playlistsField').removeClass('showR');
		
		
	} else {
		$('playlistsField').removeClass('showL');
		$('playlistsField').removeClass('showR');
	}
	
	$('pltScrollR').removeEvents();
	$('pltScrollR').addEvent('click', function(e){
		e.stop();
		$('playlistsField').addClass('showL');
		$('playlistsTitles').set('morph',{
			transition: 'pow:out',
			onComplete: setPlaylistsTitlesScroll
		}).morph({
			'left' : (left - boxWidth + 80)
		})
	})
	$('pltScrollL').removeEvents();
	$('pltScrollL').addEvent('click', function(e){
		e.stop();
		$('playlistsField').addClass('showR');
		$('playlistsTitles').set('morph',{
			transition: 'pow:out',
			onComplete: setPlaylistsTitlesScroll
		}).morph({
			'left' : (left + boxWidth - 80)
		})
	})
	
}

/******* Перезаполняет хеш songs переменной-хранилище и запускает сохранение на сервере текущих данных пользователя.
	plId - идентификатор плейлиста.	
*/
function savePlaylist(plId) {
	var songs = new Array();
	$(plId).getElements('.playBox').each(function(el,i){
		songs.push({
			'id' : el.id,
			'artist' : el.getElement('.artist').get('html'),
			'title' : el.getElement('.title').get('html'),
			'filepath' : el.getAttribute('filepath')
		});
	})
	playlists[plId].songs = songs;
	playerCookie.set('playlists', playlists);
}


/******* Удаляет плейлист plId (и визуально, и из переменной-хранилища).
	plId - идентификатор плейлиста.	
*/
function deletePlaylist(plId) {
	if (confirm(lang["playlist_delete_confirm"])) {
		$(plId).dispose();
		$('clicker_'+plId).dispose();
		playlists.erase(plId);
		playerCookie.set('playlists', playlists);

		saveUserPrefs({"delete":plId});
		
		setPlaylistsTitlesScroll();
	}
	
	return false;
}

/******* Переименовывает плейлист plId (и визуально, и в переменной-хранилища).
	plId - идентификатор плейлиста.	
*/

function renamePlaylist(plId) {
	var oldTitle = playlists[plId].title;
	var newTitle = prompt(lang["playlist_rename_prompt"], oldTitle);
	if (newTitle) {
		newTitle = newTitle.replace(' - ', ' — ');
		playlists[plId].title = newTitle;
		playerCookie.set('playlists', playlists);
		$('clicker_'+plId).getElement('span').set('html', newTitle);
		$(plId).getElement('.titleText').set('html', newTitle);
	
		saveUserPrefs();
	}
	
	return false;
}

//PLAYLISTS

/******** Генерирует плейлист по запросу пользователя, либо пустой плейлист при загрузке страницы (сначала в переменной-хранилище, потом и визуально).
	(string) mode [undefined|blank] - режим создания.
	mode == undefined - генерация плелиста по запросу пользователя.
	mode == blank - генерация пустого плейлиста с названием newTitle
	(string) newTitle - название плейлиста при "mode == blank".
	
	Генерирует и/или заполняет переменную-хранилище (playlists).
*/
function createPlaylist(mode, newTitle){
	time = new Date();
	id = 'pl'+time.getTime();
	var error = false;
	if (mode == "blank") {
		var plTitle = newTitle;
	} else {
		var plTitle = prompt(lang["playlist_new_title_prompt"], '');
	}
	if (plTitle) {
		plTitle = plTitle.replace(' - ', ' — ');
		if (!playlists) playlists = new Hash();
		else {
			playlists.each(function(el,i){
				if (el.title == plTitle) {
					alert(lang["playlist_new_title_error"]);
					error = true;
				}
			});
		}
		
		if (!error) {
			playlists[id] = {
					'id' : id,
					'title' : plTitle,
					'songs' : []
				}
			
			playerCookie.set('playlists', playlists);
			saveUserPrefs();
			
			addPlaylistTitle(id);
			generatePlaylist(id);
			$('clicker_'+id).fireEvent('click');
		}
	}
}


function scrollPlaylistToSong(cont, songId) {
	new Fx.Scroll($(cont)).toElement(songId);
}


/******** Уникализирует результаты поиска.
*/
function uniqueSearchResult() {
	/*var audioColl = $('playlistSearch').getElements('.playBox');
	var audioCompare = [];
	var audioCompareIds = [];
	var audioCompareTitles = [];
	for (var i=0,ii=audioColl.length;i<ii;i++) {
		audioCompareIds[i] = audioColl[i].id;
		audioCompareTitles[i] = audioColl[i].getElement('.songTitle').get('text');
	}
	
	
	audioCompare.reverse();
	audioCompareIds.reverse();
	audioCompareTitles.reverse();
	audioColl.reverse();
	
	var tmpAudioColl = audioCompareTitles;
	for (var i=0,ii=audioColl.length;i<ii;i++) {
		var curTitle = tmpAudioColl.shift();
		var isHere = false;
		for(var l=0, ll=tmpAudioColl.length; l < ll; l++) {
			if (curTitle.toLowerCase() == tmpAudioColl[l].toLowerCase()) {
				isHere = true;
			}
		}
		if (isHere) $(audioCompareIds[i]).dispose();
	}*/
}



/******** Запрашивает поиск у сервера, заполняет блок поиска результатами.
	(array) queryArray - массив параметров.
	(string uriEncoded) queryArray[0] - текст запроса (query).
	(int) queryArray[1] - внутренняя страница запроса (page).
	(int) queryArray[2] [0|1] - использовать серверный фильтр выдачи при поиске (filter).
	(int) queryArray[3] - внешняя страница запроса.
	(string) queryArray[4] - системное сообшение.
	(object) queryArray[5] - номера внутренних страниц прошлых запросов.
	(object) queryArray[6] - кеш предыдущих страниц.
	(object) queryArray[7] - список конечных страниц запросов.
	
	(int) step - счетчик повторения рекурсивных запросов
*/
var globalSearchRequest = null; //объект Request.HTML последнего произведенного поискового запроса на сервер
var globalSearchInfo = null; //глобальный дубль последнего queryArray
function requestRecursive(queryArray, step) {
	
	var stopRequest = false;
	
	if (!$defined(step)) {
		var step = 0;
	} else step++;
	
	queryArray[4] = "";
	
	if (step == 0) {
		//очистить поисковое пространство
		$('playlistSearch').getElement('.content').innerHTML = "";
		if (!$defined(queryArray[5])) queryArray[5] = {0:0};
		else if (!$defined(queryArray[5][queryArray[3]])) queryArray[5][queryArray[3]] = queryArray[1];
	}
	
	globalSearchInfo = queryArray;	
	
	
	var parseSearchResponce = function(q,w,e,r) {
		if (typeof(e) == "undefined") {
			$('playlistSearch').getElement('.content').innerHTML = "Не получается завершить поиск. Возможно, сервер поиска перегружен, попробуйте повторить запрос.";
			window.fireEvent('ce_requestcompleted');
			stopRequest = true;
		}
		//console.log(e);
		if (e.indexOf("Connection timed out") !== -1) {
			$('playlistSearch').getElement('.content').innerHTML = "Поиск на профилактике. Попробуйте повторить позднее.";
			globalSearchInfo[4] = "nonextpage";
			window.fireEvent('ce_requestcompleted');
			stopRequest = true;
			return null;
		}
		
		//заполнение кеша
		if (!$defined(queryArray[6])) {
			queryArray[6] = {};
		} 
		if (!$defined(queryArray[6][queryArray[1]])) {
			queryArray[6][queryArray[1]] = e;
		}
		
		globalSearchInfo[6] = queryArray[6];
		
		if (e.indexOf('{{empty_next_page}}') !== -1 || queryArray[1] > 9) {
			stopRequest = true;
			queryArray[4] = "nonextpage";
			
			if (e.indexOf("{{no_result}}") !== -1 && queryArray[1] == 0) {
				$('playlistSearch').getElement('.content').innerHTML = "Ничего не нашлось.";
				window.fireEvent('ce_requestcompleted');
				return null;
			}
			
			e = e.replace('{{empty_next_page}}', '').replace('{{no_result}}', '');
			
		}
		
		if (e.indexOf("{{no_result}}") !== -1) {
			if (queryArray[1] === 0) {
				$('playlistSearch').getElement('.content').innerHTML = "Ничего не нашлось.";
				window.fireEvent('ce_requestcompleted');
			} else {
				queryArray[1]++;
				requestRecursive(queryArray, step);
				window.fireEvent('ce_requestcontinues');						
			}
		} else if (e.indexOf('<div class="playBox"') === -1) {
			if (queryArray[1] === 0) {
				queryArray[4] = "nonextpage";
				$('playlistSearch').getElement('.content').innerHTML = e;
			}
			window.fireEvent('ce_requestcompleted');
			stopRequest = true;
		} else {
			
			$('playlistSearch').getElement('.content').innerHTML += e;				
			var wholeResultLength = $('playlistSearch').getElement('.content').getElements('.playBox').length;
			if (wholeResultLength < 50 && !stopRequest) {
				queryArray[1]++;
				requestRecursive(queryArray, step);
				window.fireEvent('ce_requestcontinues');
			} else {
			
				//запоминаем кол-во страниц в запросе
				if (!$defined(queryArray[7])) queryArray[7] = {0:queryArray[1]};
				else if (!$defined(queryArray[7][queryArray[3]])) queryArray[7][queryArray[3]] = queryArray[1];
				
				globalSearchInfo = queryArray;					
				window.fireEvent('ce_requestcompleted');
			}
		}

		initSearchPlaylist();
	}	
	
		
	if ($defined(queryArray[6]) && $defined(queryArray[6][queryArray[1]])) {
		parseSearchResponce(null,null,queryArray[6][queryArray[1]]);
		window.fireEvent('ce_requestcompleted');
	} else {
				
		globalSearchRequest = new Request.HTML({
			url:'/search/',
			onComplete: parseSearchResponce
		}).get({
			'filter': 1,
			'isall' : 0,
			'q' : queryArray[0],
			'p' : queryArray[1]
		});
	}
}



/******** Инициализирует сортировку для всех элементов-песен, находящихся в данный момент на странице.
*/
var songsSortables = null; //объект Sortables последней инициализации сортировки
function initSortables() {
	var sorted = false;
	var fromSortId = false;
	songsSortables = new Sortables('.playlist', {
		snap: 4,
		//handle: '.drag',
		//constrain: true,
		revert: true,
		clone: true,
		onStart: function(el, el1) {
			
			el.addClass('dragging');
			el1.addClass('draggingClone');
			var pl = el.getParent('.playListContainer');
			if (pl) fromSortId = pl.id;
		},
		onSort: function(el) {
			sorted = true;
		},
		onComplete: function(el) {
			el.removeClass('dragging');
			var pl = el.getParent('.playListContainer');
			if ((pl) && (sorted)) {
				savePlaylist(pl.id);
				sorted = false;
				if (fromSortId && fromSortId !== pl.id) {
					savePlaylist(fromSortId);
				} else {
					fromSortId = false;
				}
				saveUserPrefs();
			}
		}
	});	
}


/******** Производит все необходимые процедуры для активации поведения элементов 
		после визуальной генерации плейлиста.
*/
function initPlaylist__(plEl) {
	
	songsSortables.addLists($(plEl).getElements('.playlist'));
	
	
	initSortables();
	initSongsOperations(plEl);
	
	var optionsShower = plEl.getElement('.optionsShower');
	optionsShower.addEvent('mouseenter', function(){
		var box = optionsShower.getElement('.options');
		var inbox = box.getElement('.optionsBox');
		box.addClass('show').setStyles({
			'height':0
		}).set('morph',{
			duration:200,
			transition: 'expo:out'
		}).morph({
			'height':144
		});
		inbox.setStyles({
			'top':-120
		}).set('morph',{
			duration: 200,
			transition: 'expo:out'
		}).morph({
			'top':0
		});
	})
	optionsShower.addEvent('mouseleave', function(){
		var box = optionsShower.getElement('.options');
		var inbox = box.getElement('.optionsBox');
		box.set('morph',{
			duration: 200
		}).morph({
			'height':0
		});
		inbox.set('morph',{
			duration: 200
		}).morph({
			'top':-120
		});
	})
	
	//Инициализация закрывалки
	var closeObj = plEl.getElement('.playlistClose');
	if (closeObj) {
		closeObj.addEvent('click', function(e){
			e.stop();
			$('clicker_'+plEl.id).fireEvent('click');
			return false;
		});
	}
	
	//Прикрепление режимов проигрывания
	var modeObj = plEl.getElement('.mode');
	if (modeObj) {
		modeObj.title = lang["playmode_end"];
		modeObj.addEvent('click', function(){
			if (modeObj.hasClass('ply')) {
				modeObj.removeClass('ply').addClass('rep');
				modeObj.title = lang["playmode_repeat"];
			} else if (modeObj.hasClass('rep')) {
				modeObj.removeClass('rep').addClass('shf');
				modeObj.title = lang["playmode_random"];
			} else if (modeObj.hasClass('shf')) {
				modeObj.removeClass('shf').addClass('ply');
				modeObj.title = lang["playmode_end"];
			}
		})
	}
	
}

/******** Производит все необходимые процедуры для активации поведения элементов поискового плейлиста.
*/
function initSearchPlaylist() {
	plEl = $('playlistSearch');
	initSortables();
	initSongsOperations(plEl);
}


/******** Ставил плейлист с идентификатором plId в состояние проигрывания, убирает этот статус с плейлиста currentPlaylistPlayingId.
	plId - идентификатор плейлиста.	
*/
var currentPlaylistPlayingId = null; //плейлист, в проигрываемый в данный момент
function setCurrentPlaylist(plId) {
	//if (plId !== currentPlaylistPlayingId) {
		if (currentPlaylistPlayingId) {
			$(currentPlaylistPlayingId).getElement('.playback').removeClass('pause').addClass('play');
		}
		var butt = $(plId).getElement('.playback');
		butt.removeClass('play').addClass('pause');
		currentPlaylistPlayingId = plId;
	//}
}

/******* Показывает блок с ссылкой для сохранения плейлиста plId.
	plId - идентификатор плейлиста.	
*/	
function downloadPlaylist(plId) {
	$('downloadPlaylistBox').addClass('show').addClass('loading');
	var messBox = $('downloadPlaylistBox').getElement('.message');
	messBox.set('html', 'Идет подготовка к скачиванию...');
	new Request.HTML({
		url: '/playlists-download/',
		onComplete: function(t,e,resp) {
			$('downloadPlaylistBox').removeClass('loading');
			messBox.set('html', 'Ссылка для скачивания: <br /><a href="'+resp+'">'+resp+'</a><small><br /><br />ссылка будет оставаться рабочей в течение двух часов</small>');
		}
	}).send('id='+plId);	
}


function playlistGetLink(plId) {
	var userName = ($$('#auth .logged')[0])?$$('#auth .logged')[0].get('text').replace(/ /g, "_").replace(/\//g, " "):"";
	var plTitle = $(plId).getElement('.titleText').get('text').replace(/ /g, "_").replace(/\//g, " ");
	var hash = "h"+Cookie.read("ch").substring(2,8);
	var href = "http://"+GlobalHost+"/#playlist/"+hash+"/"+plId+"/"+userName+"/"+plTitle;
	showInfoWindow(
		lang["playlist_link"]+" «"+$(plId).getElement('.titleText').get('text')+"»"
		+"<br /><textarea readonly='true' onclick='this.select()' class='infoFieldTA'>"
		+href
		+"</textarea>"
	);
	return false; 
}


/******* Перемещает все результаты поиска в плейлист plId.
	plId - идентификатор плейлиста.	
*/	
function searchToPlaylist(plId) {
	var coll = $$('#playlistSearch .playBox');
	var chainColl = new Chain;
	coll.each(function(el,i){
		chainColl.chain(function(){
			el.inject($(plId).getElement('.playlist'), 'bottom');
		})
	});
	
	chainColl.chain(function(){
		savePlaylist(plId);
		saveUserPrefs();
	})
	
	var interv = (function(){
		chainColl.callChain();
		if (!chainColl.$chain.getLast()) $clear(interv);
	}).periodical(85);
	return false;
}


////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////// Плеер /////////////////////////////////////////////////

/******** Инициализирует флеш-плеер.
*/
function initGlobalPlayer(elId) {
	var volume = playerCookieVolume.get('volume');
	if (!volume) volume = 90;
	
	swfobject.embedSWF("/sharedfiles/swf/audme/player.swf?0001", elId, "500", "32", "9.0.0", "", {
		'skin':'/sharedfiles/swf/audme/stylish_my.swf?0002',
		'backcolor':'#222222',
		'volume' : volume,
		'type' : 'sound'
	},
	{
		'wmode':'transparent',
		'allowscriptaccess':'always',
		'swliveconnect':'true',
		'allowfullscreen':'false'
	},
	{
		id: 'swfObject_'+elId,
		name: 'swfObject_'+elId
	});
	
	document.title = defaultDocumentTitle;
}

var player = null;
function playerReady(thePlayer) {
	player = $('swfObject_globalPlayer');
	player.addModelListener("STATE", "playerStateListener");
	player.addModelListener("META", "playerMetaListener");
	player.addModelListener("LOADED", "playerLoadedListener");
	player.addModelListener("ERROR", "playerErrorListener");
	player.addControllerListener('VOLUME','playerVolumeListener');
	
	//play($('searchPlaylist').getElement('.playerBox').id, true);
}

function playerErrorListener(ob) {
	window.fireEvent("playback_songError", {"message":ob.message,"songId":currentGlobId});
}

function playerVolumeListener(volObj) {
	playerCookieVolume.set('volume', volObj.percentage);
}

var songMeta = {};
function playerMetaListener(ob) {
	if (ob.duration) {
		songMeta.duration = ob.duration;
		if (songMeta.bytes) $$('#globalPlayerSongBitrate .rate')[0].set('html', Math.round((songMeta.bytes / 1000 * 8)  / Math.ceil(songMeta.duration)));
	}
}
function playerLoadedListener(ob) {
	if (ob.total) {
		songMeta.bytes = ob.total;
	}
}

function resetSongMeta() {
	songMeta = {};
	$$('#globalPlayerSongBitrate .rate')[0].set('html', '');
}

var currentGlobId = null;

function play(globId, as, repeat) {
	
	resetSongMeta();
	
	if (globId != currentGlobId || repeat) {
		if ($(currentGlobId)) $(currentGlobId).removeClass('playing');
		$(globId).addClass('playing');
		$('globalPlayerTitle').set('html', $(globId).getElement('.songTitle').get('html'));
		var fp = $(globId).getAttribute('filepath');
		currentGlobId = globId;
		player.sendEvent('STOP');
		player.sendEvent('LOAD', fp);
		document.title = defaultDocumentTitle+': '+$('globalPlayerTitle').get('text');
		currentDocumentTitle = document.title;
		if (!as) {
			player.sendEvent('PLAY');
			changeFavicon('fav-play.ico');
		}
	}
	return false;
}

function playStop() {
	resetSongMeta();
	player.sendEvent('STOP');
	if ($(currentGlobId)) $(currentGlobId).removeClass('playing');
	$('globalPlayerTitle').set('html', "");
	document.title = defaultDocumentTitle;
	currentDocumentTitle = document.title;
	changeFavicon('favicon.ico');
}

function directPlay(url, type) {
	
	var perId = (function(){
		if (player) {
			$clear(perId);
			
			resetSongMeta();
			
			if (!type) {
				//название песни
				var trTitleMatch = url.match(/^(.*?\/)([^\/]*)$/);
				var realUrl = trTitleMatch[1]+translit(trTitleMatch[2]).replace(/[^a-z0-9-.()]/gi, "_")+".mp3";
				var fp = realUrl.replace("/audme.ru", "/".GlobalStreamHost);
				var trTitle = trTitleMatch[2];
			} else if (type == "m") {
				//название песни
				var trTitleMatch = url.match(/^(.*?)\/([^\/]*)$/);
				var fp = trTitleMatch[1]+".mp3";
				var trTitle = trTitleMatch[2];			
			}
			
			var trueTitleArr = decodeURIComponent(trTitle).replace(" — ", "——separator——").split("——separator——");
			var generatedId = 'player'+Math.round(Math.random()*Math.random()*1000000000000000000000000000000);
			var songHtml = '<div class="playlist"><div class="playBox" id="'+generatedId+'" filepath="'+fp+'"><div class="song"><i class="cov"></i><span class="songTitle"><span class="artist">'+trueTitleArr[0]+'</span> — <span class="title">'+trueTitleArr[1]+'</span></span></div><div class="songHandle"><i class="playnext" title="'+lang["song_playnext"]+'"></i><i class="delete" title="'+lang["song_delete"]+'"></i><i class="download" title="'+lang["song_download"]+'"></i><i class="getlink" title="'+lang["song_link"]+'"></i><i class="rename" title="'+lang["song_rename"]+'"></i><i class="drag" title="'+lang["song_drag"]+'"></i></div></div></div>';
			
			$('playlistSearch').getElement('.content').set('html', songHtml);
			initSearchPlaylist();
			$(generatedId).getElement('.song').fireEvent('click');
		}
	}).periodical(500);
	
	return false;
}

function playlistPlay(hash) {
	
	var hashParts = hash.split("/");
	var valid = hashParts[1];
	var plId = hashParts[2];
	
	location.hash = decodeURI(location.hash);
	
	document.title = defaultDocumentTitle+': '+$('searchBox').q.value;
	var queryArray = [hash, 0];
	window.fireEvent('ce_requeststarted');
	requestRecursive(queryArray);
	
	return false;
}


function playerStateListener(ob) {
	
	if (ob.newstate == "COMPLETED") {
		playNextSong();
	}
	
	if (ob.newstate == "PAUSED") {
		document.title = currentDocumentTitle;
		changeFavicon('fav-pause.ico');
	}
	
	if (ob.newstate == "PLAYING") {
		document.title = currentDocumentTitle;
		changeFavicon('fav-play.ico');
	}	
	
}

function playNextSong() {
	document.title = defaultDocumentTitle;
		
	//Проигрывание песни из очереди
	if (GlobalSongsQueue.ids.length > 0) {
		//если очередь не пуста, играем следующую песню из очереди
		newGlob = $(GlobalSongsQueue.ids[0]);
		rmSongFromQueue(newGlob);
	} else {
		//если пуста, запускаем дальнейшее проигрывание по текущему (относительно отыгравшей песни) плейлисту
	
		//Обработка режимов проигрывания
		var pl = $(currentGlobId).getParent('.playListContainer');
		scrollContainer = null;
		if (pl) {
			var modeObj = pl.getElement('.mode');
			if (modeObj.hasClass('ply')) {
				var newGlob = $(currentGlobId).getNext('.playBox');
			} else if (modeObj.hasClass('shf')) {
				var elems = pl.getElements('.playBox');
				var i = 0;
				do {
					i++;
					var newGlob = elems[Math.round(Math.random() * (elems.length - 1))];
				} while(newGlob.getAttribute('id') == currentGlobId && i < 10);
			} else if (modeObj.hasClass('rep')) {
				var newGlob = $(currentGlobId).getNext('.playBox');
				var repeatMode = true;
			}
			//scrollContainer = pl.getElement('.content');
		} else {
			var newGlob = $(currentGlobId).getNext('.playBox');
			//scrollContainer = (newGlob)?newGlob.getParent('searchListContainer'):null;
		}
	}
	
	if (newGlob) {
		var newGlobId = newGlob.getAttribute('id');
		play(newGlobId);
	} else {
		//если наткнулись на разделитель
		var nextPl;
		if (nextPl = $(currentGlobId).getParent('.playlist').getNext('.playlist')) {
			var newGlobId = nextPl.getElement('.playBox').getAttribute('id');
			if (newGlobId) play(newGlobId);
		} else if (repeatMode) {
			var newGlobId = pl.getElement('.playBox').getAttribute('id');
			if (newGlobId) play(newGlobId, null, true);
		}
	}
	
	//скроллинг до песни
	if (0 && newGlobId) {
		newGlob = $(newGlobId);
		scrollContainer = newGlob.getParent('.searchListContainer')?newGlob.getParent('.searchListContainer'):newGlob.getParent('.content');
		scrollPlaylistToSong(scrollContainer, newGlobId);
	}
}

//////////////////////////////////////////// Плеер /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////// Нужные функции/////////////////////////////////////////

var rusChars = new Array('А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П','Р','С','Т','У','Ф','Х','Ц','Ч','Ш','Щ','Ъ','Ы','Ь','Э','Ю','Я','а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','\я');
var trlChars = new Array('A','B','V','G','D','E','E','J','Z','I','Y','K','L','M','N','O','P','R','S','T','U','F','H','C','CH','SH','SCH','','Y','\'','E','YU','YA','a','b','v','g','d','e','e','j','z','i','y','k','l','m','n','o','p','r','s','t','u','f','h','c','ch','sh','sch','','y','\'','e','yu','ya');
function translit(from, isTo) {
	var to = new String();
	var len = from.length;
	var character, isRus;
	
	if (isTo) {
		var fromChars = rusChars;
		var toChars = trlChars;
	} else {
		var fromChars = trlChars;
		var toChars = rusChars;		
	}

	for(i=0; i < len; i++) {
		character = from.charAt(i, 1);
		isRus = false;
		for(j=0; j < fromChars.length; j++) {
			if(character == toChars[j]) {
				isRus = true;
				break;
			}
		}
		to += (isRus) ? fromChars[j] : character;
	}
	
	return to;
}

//////////////////////////////////////////// Нужные функции/////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////




////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////// Фавиконы //////////////////////////////////////////////
var fDocumentHead = null;

function documentHead() {
	if (fDocumentHead == null) {
		fDocumentHead = document.getElementsByTagName('head')[0];
	}
	return fDocumentHead;
}

function addFavicon(url, type) {
	var icon = document.createElement('link');
	icon.type = 'image/x-icon';
	icon.rel = "shortcut icon";
	icon.href = url;
	documentHead().appendChild(icon);

}

function removeFavicons() {
	var icons = document.getElementsByTagName('link');
	var i = 0;
	while (icons.length > 0 && i < icons.length) {
		if (icons[i].type == 'image/x-icon') {
			documentHead().removeChild(icons[i]);
		} else {
			i++;
		}
	}
}

function changeFavicon(fn) {
	var url = "/images/"+fn;
	//$$('head link[type=image/x-icon]').each(function(el){
	//	el.setAttribute('href', url);
	//});
	
	removeFavicons();
	addFavicon(url);
}

changeFavicon('favicon.ico');
favsPreload = [new Image, new Image, new Image];
favsPreload[0].src = '/images/favicon.ico';
favsPreload[1].src = '/images/fav-play.ico';
favsPreload[2].src = '/images/fav-pause.ico';
//////////////////////////////////////////// Фавиконы //////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

;

/**** /sharedfiles/js/audme/songCheck.js ****/
window.addEvent('playback_songError', function(args){
	songObj = $(args.songId);
	//var isSearch = $defined(songObj.getParent('.searchListContainer'));
	var isSearch = false;
	if (!songObj.getAttribute('filepath')) {
		if (!isSearch) {
			var winObj = showInfoWindow(lang["song_check_message_lost_at_all"], 140);
			playStop();
		}
	} else {
		if (!isSearch) {
			var winObj = showInfoWindow(lang["song_check_message_searching"], 140);
			winObj.hideCloser();
		}
		var songRequest = new Request({
			url: "/search-song/lost/", 
			secure: false,
			onComplete: function(obj){
				var resp = obj.split("////");
				if (resp[0] == "exact" || resp[0] == "first") {
					if (resp[1]) songObj.setAttribute('filepath', resp[1]);
					setSongDownloadLink(songObj);
					play(songObj.id, null, true);
					if (!isSearch) {
						if (resp[0] == "exact") {
							winObj.changeContent(lang["song_check_message_found_exact"]);
							winObj.close(4);
						} else {
							winObj.changeContent(lang["song_check_message_found_first"]);
							winObj.close(10);
						}
						winObj.showCloser();
						savePlaylist(songObj.getParent('.playListContainer').id);
						saveUserPrefs();						
					}
				} else if (resp[0] == "none") {
					if (!isSearch){
						winObj.changeContent(lang["song_check_message_found_none"]);
						winObj.close(25);
						winObj.showCloser();
					}
					playStop();
					if (!songObj.getParent('.searchListContainer')) playNextSong();
				} else {
					if (!isSearch){
						winObj.changeContent(lang["song_check_message_request_error"]);
						winObj.showCloser();
					}
					playStop();
				}
			}
		}).send('fp='+songObj.getAttribute('filepath')+'&art='+encodeURIComponent(songObj.getElement('.artist').get('text'))+'&tit='+encodeURIComponent(songObj.getElement('.title').get('text')));
	}
})
;
