var _ledokol_dispatcher_version = '0.0.4'

/**
 * Usefull form of Math.random
 */
function mr() { return Math.floor(Math.random()*100000+1) }

/**
 * Second to Time string converter
 */
function secondsToTimeStr(secs) {
    var hours = Math.floor(secs/(3600))
    var dfm = secs % (3600)
    var minutes = Math.floor(dfm/60)
    var dfs = dfm % 60
    var seconds = Math.ceil(dfs)
    return [hours,
	    ':',
	    (minutes<10) ? '0' : '',
	    minutes,
	    ":",
	    (seconds<10) ? '0' : '',
	    seconds].join('')
}

/**
 * Main page object
 */
page = {
	 page: 'top', // 'top'|'playlist'
	 nextUpd: 0, //next invitation to reload page, sec
	 _wt: 0, // timer "what new"
	 init: function() {
	     $.getJSON('index.php',{page:'jtop',ac:mr()}, function(json) {
		 var colors = ['#619161','#616991','#918961','#777a65','#81b37b','#a6c078','#b6bf99','#898883']
		 var lines = (user.id) ? [10,10,10,10,10,10,10,10,10,10] : [3,5,8,12,18,24,30]
		 usertop.create('suptop',json,lines,colors)
	     })
	     this.startWhatNew(30)
	     page.isAuth()
	 },

	 isAuth: function() {
	     if ($.cookie("last_nick") != null && $.cookie("user") == null) {
	     var name = $.cookie("last_nick");
	     var width = 'width:7em';
	     if( name.length > 10 )
	    	 width = 'width:11em';
		 var s=[f_fstart('w_dialog_isAuth', 'index.php', 'post'),
			'<div style="text-align:center">',
			f_dbuttons([f_sbutton(name, ["PathDispatcher('authorize',3,[",
								      $.cookie("last_user"),", \'",
								      $.cookie("last_hash"),"\', \'",
								      $.cookie("last_nick"),"\']);closeW('vwindow')"].join(''),width),
				    '&nbsp;&nbsp;&nbsp;&nbsp;',
				    f_button('Нет', 'closeW(\'vwindow\')', 'width:4em')].join('')),
			'</div>',
			f_fend(),
			f_cboth()].join('')
		 viewInfo('Ваше имя', s, 0)
	     }
	 },

	 changePage: function(page,param) {
	     switch (page) {
	     case 'top':
		 this.page='top'
		 searchtracks.hide()
		 usertop.show()
		 ledokol.show()
		 playlist.hide()
		 break
	     case 'playlist':
		 this.page='playlist'
		 usertop.hide()
		 ledokol.show()
		 searchtracks.hide()
		 playlist.show()
		 if(typeof param != 'undefined')
			 playlist.init_playlist = param;
		 if (playlist.playlists.length==0) playlist.jinit()
		 break
	     case 'searchTracks':
		 this.page='searchTracks'
		 usertop.hide()
		 playlist.hide()
		 ledokol.show()
		 searchtracks.show()
		 break
	     case 'community':
		 this.page='community'
		 community.init()
		 break
	     }
	 },

	 startWhatNew: function(_time) {
	     this.whatNewtimer = setInterval( function() {
		 if (page._wt==0) {
		     page._wt=1
		     $.ajax({ async:true,
			      dataType:'json',
			      url:['/index.php?page=whatnew&cpage=',page.page,'&type=',ledtype,'&ac=',mr()].join(''),
			      success: function(j){
				  page._wt=0;
			      /*if( j.preorder != undefined ) {

			    	  var s = 'Вы по прежнему хотите приобрести трек <b>'+j.preorder.track_name+'</b>?';
			    	  s += f_dbuttons(f_sbutton('OK', '$(\'#w_vwindow\').remove(); PathDispatcher(\'buy\', 1, {\'u_id\':'+j.preorder.owner_id+', \'id\':'+j.preorder.track_id+', \'pl_id\':'+j.preorder.playlist_id+'})','margin:0 0 0 0.5em;width:4em'));
			    	  viewInfo( 'Покупка трека', s );
			      }	*/
				  if (!j.s) return; // server do not have news for this gamer
				  if (j.t) {
				      var u_arr=j.t.split("|");
				      for ( var i in u_arr )	{
					  u_data = u_arr[i].split("#");
					  if (typeof usertop != 'undefined')
					      usertop.update(u_data)
				      }
				  }


				  if( j.u ) {
				      var u_arr=j.u.split("#");
				      $('#usertitle_rating > span.play').text(u_arr[0]);
				      $('#usertitle_rating > span.pay').text(u_arr[1]);
				      $('#usertitle_account ').html('MONEY: <span>'+u_arr[2]+'</span>')
				      $('#usertitle_messages > span.all').text(u_arr[3]);
				      $('#usertitle_messages > span.new').text(u_arr[4]);
				      if( u_arr[2] > 10 && ledokol.buy_track_id != 0 && ledokol.buy_pl_type == '' ) { // если пришли деньги - пытаемся купить некупленый трек
						  PathDispatcher('buy', 1, {'u_id':ledokol.buy_track_user_id, 'id':ledokol.buy_track_id});
						  ledokol.buy_track_user_id = 0;
						  ledokol.buy_track_id = 0;
				      }
				      if( u_arr[2] > 0 && ledokol.buy_track_id != 0 && ledokol.buy_pl_type != '' ) {
				    	  if( (ledokol.buy_pl_type == 'album' && u_arr[2] >= 200) ||
				    		  (ledokol.buy_pl_type == 'set' && u_arr[2] >= 1000) ||
				    		  (ledokol.buy_pl_type == 'radio' && u_arr[2] >= 2000)) {
						    	  var s = 'Вы по прежнему хотите приобрести плейлист '+ledokol.buy_pl_type+' и положить в него трек?';
						    	  s += f_dbuttons(f_sbutton('OK', '$(\'#w_vwindow\').remove(); PathDispatcher(\'pledit\',7,{\'u_id\':'+ledokol.buy_track_user_id+',\'id\':'+ledokol.buy_track_id+', \'next\':'+ledokol.buy_param+'})','margin:0 0 0 0.5em;width:4em'));
						    	  viewInfo( 'Покупка трека в новый плейлист', s );
								  ledokol.buy_track_user_id = 0;
								  ledokol.buy_track_id = 0;
								  ledokol.buy_pl_type='',
								  ledokol.buy_pl_name='',
								  ledokol.buy_param=0
				    	  }
				      }
				  }
				  if( j.c2 ) {
				      $('#usertitle_messages .all').html( j.c2[0] );
				      $('#usertitle_messages .new').html( j.c2[1] );
				  }
				  if( j.lt ) {
				      var message = '<ul>';
				      var is_show = false;
				      for( k=0; k<j.lt.length; k++ ) {
					  if( j.lt[k].r != 0 ) {
					      message += '<li><b>' + j.lt[k].e + '</b> принял Ваше приглашение на прослушивание <b>"'+j.lt[k].n+'"</b>. Вам начислено ' + j.lt[k].r + ' балл(а) к рейтингу</li>';
					      is_show = true;
					  }
				      }
				      message +='</ul>';
				      if( is_show )
					  viewInfo('Поздравляем!', message);
				  }
				  if (j.stop) {
				      ledokol.stopTrack();
				      tempInfo( 'У вас запущена десктоп версия ледокола', 5 );
				  }
			      }
			    })
		     if( typeof ledokol != 'undefined' &&  ledokol.uid != $.cookie('uid') && !ledokol.ignore_second ) {
			 PathDispatcher('stopPlay', 0)
		     }
		 }
	     },_time*1000)
	 },

	 stopWhatNew: function() {
	     clearInterval(this.stopWhatNew)
	 }
}


/**
 * Диспетчер маршрутов
 *
 * @param path - имя маршрута
 * @param step - шаг
 * @param param - передаваемые параметры
 * @return
 */
function PathDispatcher(path, step, param) {
    switch(path) {
    case 'search': // search block
	switch(step) {
	case 0: // search form
	    var s=[f_fstart('w_dialog_searchForm', 'index.php', 'post'),
		   f_hidden('page', 'gett'),
		   f_hidden('type', 'nick'),
		   '<div style="float:left">',
		   f_case('трек', 'search_type_word', 'search_type_word miniradio',''),
		   '</div><div style="float:left">',
		   f_case('игрок','search_type_nick', 'search_type_nick miniradio',''),
		   '</div>',
		   f_sbutton('Поиск', 'PathDispatcher(\'search\', 1, 0)','width:4em;float:right'),
		   '<br><br>',
		   '<input type="text" class="input" id="search" name="search" style="width:250px"><br>',
		   f_fend(),
		   f_cboth()]
	    viewInfo('Поиск', s.join(''), 0)

	    $('#w_dialog_searchForm .search_type_word').attr('src', '/img/radio_w_on.gif')
	    $('#w_dialog_searchForm > input[name="type"]').val('word')
	    $("#search").suggest("/index.php?page=jsearchAuto",{ onSelect:function() { PathDispatcher('search', 1, 0) }})

	    $("#w_dialog_searchForm .search_type_nick").click( function() {
		$('#w_dialog_searchForm > input[name="type"]').val('nick')
		$(this).attr('src', '/img/radio_w_on.gif')
		$('#w_dialog_searchForm .search_type_word').attr('src', '/img/radio_w_off.gif')
	    })

	    $('#w_dialog_searchForm .search_type_word').click( function() {
		$('#w_dialog_searchForm > input[name="type"]').val('word')
		$(this).attr('src', '/img/radio_w_on.gif')
		$('#w_dialog_searchForm .search_type_nick').attr('src', '/img/radio_w_off.gif')
	    })
	    //$("#search").suggest("/index.php?page=jsearchAuto",{ onSelect:function() { PathDispatcher('search', 1, 0) }})
	    break

	case 1:
	    $('.ac_results').remove()
	    searchtracks.word=$('#w_dialog_searchForm input[name="search"]').val()
	    PathDispatcher('search', ($('#w_dialog_searchForm > input[name="type"]').val()=='word') ? 2 : 4, {page:1})
	    break

	case 2: // intro search
	    $.getJSON('index.php',{ page:'jsearchTracks',
				    rows:50,
				    pagenum:param.page,
				    sidx:'name',
				    sord:'asc',
				    s:searchtracks.word,
				    ac:mr()}, function(j) {
					closeW('vwindow');
					//if (j.st.s!=2 && j.st[1].length>0) {
					if (j.s!=2 ) {
					    searchtracks.mode="intro"
					    searchtracks.init(j.st[1])
					    searchtracks.create()
					    if (j.lt!=null) {
						$('#lucky button').click(function() {
						    ledokol.getNewTrack({page:'gett',next:true,userid:j.lt,playtype:ledokol.playtype,trackid:track.id, plist:j.lt})
						    $('#lucky').hide()
						});
					    } else {
						$('#lucky').hide()
					    }
					    page.changePage('searchTracks', 0)
					} else { // no result -- extra search
						tempInfo('Простите на ледоколе нет того что Вы ищете:(', 3, 'i');
					    //tempInfo('Трек не найден на Ледоколе. Поиск по внешним ресурсам.', 3,'i')
					    //setTimeout(function() { PathDispatcher('search', 3, {page:1})}, 3000)
					}
	    })
	    break

	case 3: // extra search
	    searchtracks.mode="extra";
	    $.getJSON('index.php',{page:'extrasearch', s:searchtracks.word, ac:mr()}, function(j) {
		closeW('vwindow')
		if (j.s==0) {
		    tempInfo('Трек не найден на внешних ресурсах.', 3,'i')
		} else {
		    searchtracks.mode="extra"
		    searchtracks.init(j)
		    searchtracks.create()
		    page.changePage('searchTracks', 0)
		}
	    });
	    break;

	case 4: // user-search
	    if (0==ledokol.gtn) {
		ledokol.gtn=1
		$('#w_dialog_searchForm').ajaxSubmit({dataType:'json', success:function(j) {
	            if (j.s==1) {
			closeW('vwindow')
				track.init( j );
	        	track.id = j.trackid
	        	track.path = j.trackpath
	        	track.u_id = j.userid
	        	track.u_name = j.user
	        	track.u_avatar = j.avatar
	        	ledokol.stopSignal()
	        	ledokol.playsource='go'
	        	ledokol.initTrackInfo()
	        	ledokol.playTrack()
	            } else {
	        	tempInfo('Возможно неверно указан игрок, либо в его плейлисте нет новых для вас треков.', 3,'i')
		    }
		    ledokol.gtn=0
		}})
	    }
	    break
	}
	break

    case 'sendmailSubmit':
    var send_to = $('#to').val();
    if( send_to == '' ) {
    	tempInfo('Вы не указали ниодного адресата', 5);
    	break;
    }
    var text = $('#text').val();
    if( text == '' ) {
    	tempInfo('Пожалуйста введите текст сообщения для Вашего приятеля', 5);
    	break;
    }
	$('#w_dialog_sendmessage').ajaxSubmit( { dataType:'json' });
	$('#as_to').hide();
	swindow.close();
	$.getJSON('index.php',{page:'check_already_sent', user:track.u_id, track:track.id, to:send_to}, function(j) {
		var msg = '';
	    if( j.users_good.length > 0 ) {
	    	msg += 'Сообщение отправлено: ' + j.users_good + '<br>';
	    }
	    if( j.users.length > 0 ) {
	    	msg += 'Сообщение не отправлено: <br> ' + j.users + ' т.к. они уже слышали посылаемый Вами трек';

	    }
	    viewInfo('Инфо', msg, 10);
	})
	break

    case 'sendmail':
	var trackId=track.id, userId=track.u_id;
	if (param!=0) { trackId = param; userId = user.id }
	var s=f_fstart('w_dialog_sendmessage', 'index.php', 'post');
	s +=f_hidden('page', 'send_email');
	s +=f_hidden('user', userId);
	s +=f_hidden('track', trackId);
	s +='<div id="track_author_name"></div><br>';
	s +=f_label('TO:', 'width:60px;');
	s +=f_param(f_textarea('to','to','','width:250px; height:50px;'));
	//s +=f_param(f_input('to','to','','width:230px; height:50px;'));
	s +=f_cboth();
	//temporaly remove top
	//s +='<div style="width: 60px;" class="label" id="w_top_label"><a href="javascript:void(0);">[+]</a>TOP</div>';
	//s +=f_param('<div id="w_top"></div>');
	s +=f_cboth();

	s +=f_label('SUBJECT:', 'width:60px;');
	s +=f_param(f_input('subj', '', 'width:250px;'));
	s +=f_cboth();

	s +=f_label('TEXT:', 'width:60px;');
	s +=f_param(f_textarea('text', 'text', '', 'width:250px;height:60px;'));
	s +=f_cboth();
	s +=f_label('&nbsp;', 'width:60px;');
	s +=f_param('<a href="javascript:void(0);" class="friendslist">[Friends]</a>', "width:150px;");
	s +=f_label('&nbsp;', 'width:60px;');
	s +=f_param('<a href="javascript:void(0);" class="gimport">[Импорт из e-mail]</a>', "width:150px;");
	/*s +=f_label('&nbsp;', 'width:45px;');
	s +=f_param('<a href="javascript:void(0);" class="vkimport">[Import from Vkontakte]</a>', "width:150px;");*/

	s +=f_label('Ссылка для  ВКонтакте:', 'width:60px;');
	s +=f_param(f_input('vk_link', 'http://ledokol.com/?vk='+track.id, 'width:250px;'));
	s +=f_cboth();

	s +=f_button('Send', 'PathDispatcher(\'sendmailSubmit\',1,\''+param+'\')','float:left;width:4em');
	s +=f_fend()+f_cboth();
	viewInfo('Отправить трек', s, 0, '', 'swindow', 360);
	$("#to").suggest("/index.php?page=getContacts",{ onSelect:function() { PathDispatcher('search', 1, 0) }})

	$('#w_top_label a').live('click', function(){

		$('#w_top_label a').text( ($('#w_top_label a').text()=="[+]"?"[-]":"[+]") );
		$('#w_top').toggle();
	});

	var options = { script:"index.php?page=getContacts&", varname:"input", json:true, maxresults:10 };
	//var as_json = new AutoSuggest('to', options);
	$("#w_dialog_sendmessage .friendslist").live('click', function() {
	    param.pageNum = 0;
	    PathDispatcher('friendslist', 10, param);
	});
	$("#w_dialog_sendmessage .gimport").live('click', function() {
	    //vwindow.close();
	    PathDispatcher('gimport', 0);
	    //window.open("?page=googleContacts&mode=import", "contacts", "location,width=450,height=300,top=0")
	});
	/*$("#w_dialog_sendmessage .vkimport").live('click', function() {
	    vwindow.close();
	    PathDispatcher('vkimport');
	});*/

	$.getJSON('/index.php', {page :'send_message', mode:'getTop', track_id:trackId, ac:mr()}, function(json) {
	    $('#track_author_name').html(json.trackInfo);
	    $("#track_author_name").css("display", "block");
	    var top_html = "";
	    for( j in json ) {
		if( parseInt(j)>=0 )
		    top_html += "<div id='"+json[j].id+"' onclick=\"$('#to').val( $('#to').val() + '"+json[j].name+"("+json[j].status+"), ' );\">"+json[j].name+"</div>";
	    }
	    if( top_html != "" ) {

		//$("#w_top").css("display", "block");
		$("#w_top_label").css("display", "block");
		$("#w_top").html(top_html);
	    }
	});
	$('#link').click( function() {this.select();} );
	break;

    case 'gimportSubmit':
	$('#results').html('Please wait...');
	$('#w_dialog_gimportForm').ajaxSubmit({
	    dataType :'json',
	    success : function(json) {
		$('#results').html(json.emails);
	    }
	});
	break;

    case 'openinviter':
    	switch(step) {
    	case 0:
    		var s=f_fstart('w_dialog_openinviter', 'index.php', 'post');
    		s += 'Пригласите друзей на прослушивание используя контакты импортированные из Вашего почтового ящика ' + user.email;
    		s += '<br><br>';
    		s +=f_hidden('page', 'importMail');
    		s +=f_label('Email', 'width:60px');
    		s +=f_param(f_input('email', user.email, 'width:200px;'));
    		s +=f_label('Пароль', 'width:60px');
    		s +=f_param(f_password('passwd', '', 'width:200px;'));
    		s +=f_cboth();
    		s +=f_dbuttons('<button id="invite_button" onclick="PathDispatcher(\'openinviter\', 2, \''+param+'\')" style="width: 8em;" type="button" class="tbutton">Пригласить</button>');
    		s +='<br><img style="padding-left:20px; float:left" src="/img/lock_icon_small.png"><font style="font-size:10px; padding-left:5px; float:left" color=gray>Ледокол не сохраняет <br> ваш пароль <a href="javascript:void(0)" onclick="PathDispatcher(\'openinviter\', 1)">Подробнее...</a></font>';
    		s +=f_fend()+f_cboth();
    		viewInfo('Приглашение друзей на прослушивание', s, 0);
    		break;
    	case 1:
    		viewInfo("Как работает сервис \"Пригласить друзей\"", "Мы импортируем информацию о Ваших друзьях и не будем сохранять Ваш пароль в дальнейшем. Используя адреса электронной почты, загруженные Вами через данный сервис, мы поможем Вам связаться с друзьями.", 0, '', 'security_info');
    		break;

    	case 2:
    		var allow = ['gmail.com', 'yandex.ru', 'mail.ru', 'list.ru', 'bk.ru', 'inbox.ru', 'hotmail.com', 'inbox.com', 'operamail.com', 'rambler.ru', 'yahoo.com'];
    		var email_arr = $('#w_dialog_openinviter input[name=email]').val().split('@');
    		var host = email_arr[1];
    		var is_allow = false;
    		for( var j = 0; j < allow.length; j++ ) {

    			if( host == allow[j] )
    				is_allow = true;
    		}
    		if( is_allow ) {

        		$('#invite_button').html('Пригласить<img src="/img/ajax-loader.gif">')
        		$('#w_dialog_openinviter').ajaxSubmit( { dataType:'json', success: function(j) {
        		    if( j.s == 1 ) {

        		    	if( param == 'invite' ) {

        		    		vwindow.close();
        		    		//$('#w_edit_profile').remove();
        		    		viewInfo( "Спасибо", "Ваши контакты успешно обновлены" );
        		    	} else {

        		    		PathDispatcher('sendmail', 0, param);
        		    	}

        		    } else {

        		    	$('#invite_button').html('Пригласить')
        		    	viewInfo( "Ошибка", j.message, 0, '', 'error_wind' );
        		    }
        		}});
    		} else {

    			tempInfo('Домен ' + host + ' не поддерживается',4,'i');
    		}
    		break;
    	}
    	break;

    case 'gimport':
	switch(step) {
	case 0: //import
		//var patt=/gmail.com/g;
		//var test = patt.test(user.email);
		var tmp = user.email.split('@');
		if( tmp[1] != 'gmail.com' ) {

			PathDispatcher('openinviter', 0, 'invite');
		} else {
		    var url = '?page=googleContacts&mode=import';
		    if( $.cookie('contact_token' + user.id) != null ) {
		    	$.getJSON('/index.php', { page :'googleContacts', mode:'import', type:2 }, function(json) {
		    		viewInfo('Импорт завершен', 'Спасибо, импорт ваших контактов успешно завершен');
		    	});
		    } else {
		    	window.open(url, "contacts", "location,width=450,height=300,top=0")
		    }
		}
	    break;
	case 1://send track

		$.getJSON('/index.php', { page :'checkImport' }, function(j) {
		    if( j.s == 1 ) {
		    	PathDispatcher('sendmail', 0, param);
		    } else {
		    	PathDispatcher('openinviter', 0, param);
		    }
		});

	    /*var url = '?page=googleContacts&mode=send&track='+param;
	    if( $.cookie('contact_token' + user.id) != null ) {

		$.getJSON('/index.php', { page :'googleContacts', mode:'send', type:2 }, function(json) {

		    PathDispatcher('friendslist', 8, {"track":param});
		});
	    } else {
		window.open(url, "contacts", "location,width=450,height=300,top=0");
	    }
	    break;*/
	}
	break;

    case 'gimportSubmit':
	$('#results').html('Please wait...');
	$('#w_dialog_vk_importForm').ajaxSubmit({
	    dataType :'json',
	    success : function(json) {
		$('#results').html(json.emails);
	    }
	});
	break;

    case 'friendslist':
	switch(step) {
	case 0:
	    $.getJSON('/index.php', { page :'jfriendsList', pagen:param },
		      function(json) {
			  var s=f_fstart('w_dialog_friendsForm', 'index.php', 'post');
			  s += f_hidden('page', 'jfriendsList');
			  s += f_hidden('mode', 'delFriend');
			  s += '<table width=100%><th><input type="checkbox" onclick="javascript:PathDispatcher(\'friendslist\', 3, 0)" id="checkall" value="1"></th><th>Имя</th><th>Email/VkId</th><th>Связь</th>';
			  for( i in json ) {
			      if(i != 'total') {
				  if( json[i].status == 'email' || json[i].status == 'gmail' ) {
				      inf = json[i].email
				  }else
				      inf = json[i].vkid;
				  var is_ch = '';
				  if (typeof ledokol.checked[json[i].id] != 'undefined' && ledokol.checked[json[i].id] != -1 )
				      is_ch = 'checked';
				  s = s + '<tr><td><input type="checkbox" '+is_ch+' onchange="PathDispatcher(\'friendslist\', 6, this);" name="friendlist[]" value="'+json[i].id+'"></td><td id="name_'+json[i].id+'"><span onclick="javascript:PathDispatcher(\'friendslist\',4,'+json[i].id+')">'+json[i].name+'</span></td><td>'+inf+'</td><td id="status_'+json[i].id+'">'+json[i].status+'</td></tr>';
			      }
			  }
			  pages = '';
			  for( i=1; i<=json.total; i++ ) {
			      if( i != param+1 )
				  pages += '<a href="javascript:void(0);" onclick="PathDispatcher(\'friendslist\', 0, '+(i-1)+')">'+i+' </a>';
			      else
				  pages += '<a href="javascript:void(0);" onclick="PathDispatcher(\'friendslist\', 0, '+(i-1)+')"><font style="font-size:1.3em; color:green">'+i+' </font</a>';
			  }
			  s += '<tr align=center><td colspan=3>'+pages+'</td></tr>'
			  s += '</table>';
			  s += f_dbuttons(f_sbutton('Send', 'PathDispatcher(\'friendslist\',1,0)','width:4em') + '&nbsp;&nbsp;&nbsp;' +f_button('Delete', 'PathDispatcher(\'friendslist\',2,0)','width:4em'));
			  viewInfo( 'Ваши контакты', s, 0, '', 'myFriends' );
		      }
		     );
	    break;
	case 1:
	    $("INPUT[name='friendlist[]']").each( function() {

		if( $(this).attr('checked') ) {

		    $('#to').val( $('#to').val() + $(this).val() + ', ' );
		    $(this).attr('checked', false);
		}
	    });
	    closeW('myFriends');
	    break;
	case 2:
	    $('#w_dialog_friendsForm').ajaxSubmit( { dataType:'json', success: function(j) {
		for (id in ledokol.checked) { ledokol.checked[id]=-1 }
		PathDispatcher('friendslist',0,0);
	    }});
	    break;
	case 3:
	    if( param == 0 ) {
		if( $('#checkall').attr('checked') ) {
		    $("INPUT[name='friendlist[]']").each( function() {
			$(this).attr('checked', true);
		    });
		} else {
		    $("INPUT[name='friendlist[]']").each( function() {
			$(this).attr('checked', false);
		    });
		}
	    }
	    if( param == 1 ) {
		$("INPUT[name='friendlist[]']").each( function() {
		    if( $(this).val().search( '(gmail)' ) != -1 ) {
			$(this).attr('checked', $('#checkall_g').attr('checked'));
		    }
		});
	    }
	    if( param == 2 ) {
		$("INPUT[name='friendlist[]']").each( function() {
		    if( $(this).val().search( '(vkontakte)' ) != -1 ) {
			$(this).attr('checked', $('#checkall_v').attr('checked'));
		    }
		});
	    }
	    break;

	case 4:
	    $('#name_' + param).html("<input id='edit_"+param+"' type='text' value=\""+$('#name_'+param).text()+"\" onblur=\"javascript:PathDispatcher('friendslist',5,"+param+");\">");
	    break;

	case 5:
	    $('body').css('cursor', 'wait');
	    $.getJSON('/index.php', { page :'jfriendsList', mode:'rename', name:$("#edit_" + param).val(), id:param }, function(j) {
		$('body').css('cursor', 'auto');
		$("#name_"+param).html('<span onclick="javascript:PathDispatcher(\'friendslist\',4,'+param+')">'+$('#edit_'+param).val()+'</span>');
	    });
	    break;

	case 6:
	    var id = param.value
            ledokol.checked[id]==(param.checked) ? $('#name_'+id).text()+'('+$('#status_'+id).text()+')' : -1;
	    break;

	case 7:
	    $.getJSON('/index.php', { page :'sendtrack', track:param }, function(j) { $("INPUT[name='link']").val(j.link) });
	    break;

	case 8:
	    $.getJSON('/index.php', { page :'jfriendsList', type:'gmail' },
		      function(json) {
			  var s=f_fstart('w_dialog_friendsForm', 'index.php', 'post');
			  s += f_hidden('page', 'sendToAll');
			  s += f_hidden('mode', 'delFriend');
			  s += f_hidden('track', param.track);
			  s += '<input type="checkbox" onclick="javascript:PathDispatcher(\'friendslist\', 3, 0)" id="checkall" value="1"> отметить всех/ни одного<br><br>';
			  s += '<div style="max-height:400px; overflow-y:auto; overflow-x:hidden;"><table width=100%><tr><td colspan=4></td></tr>';
			  var k = 0;
			  for( i in json ) {
			      if(i != 'total') {


				  if( k%3==0 ) {

				      if( k%2 == 0 )
					  s = s+ '<tr>';
				      else
					  s = s+ '<tr style="background-color:#FFAA00">';
							}
							var name = json[i].name.substr(0, 19)
							if( name != json[i].name )
							    name += '...';
				  var inf = json[i].email.substr(0, 25);
				  if( inf != json[i].email )
				      inf += '...';
				  s = s + '<td><input type="checkbox" id="check_'+i+'" name="friendlist[]" value="'+inf+'"></td><td class="friendListTd" id="name_'+json[i].id+'" onclick="$(\'#check_'+i+'\').attr(\'checked\', !$(\'#check_'+i+'\').is(\':checked\'));">'+b(name)+'<br>'+inf+'</td>';
				  k++;
				  if( k%3==0 ) s = s+ '</tr>';
			      }
			  }
			  //fill empty <td>s with bgcolor
			  if( 3-k%3 != 0 )
			      for( j=0; j<=3-k%3;j++ )
				  s+= '<td></td><td></td>';
			  s += '</table></div>';
			  s += f_dbuttons(f_sbutton('Send', 'PathDispatcher(\'friendslist\',9 )','width:4em') );
			  viewInfo( 'Ваши контакты', s, 0, '', 'myFriends', 400, 300 );
		      }
		     );
	    break;
	case 9:
	    $('#w_dialog_friendsForm').ajaxSubmit( { dataType:'json', success: function(j) {

		$('#w_myFriends').remove();
		viewInfo('', 'Приглашения к прослушиванию трека разосланы вашим друзьям', 5);
	    }});
	    break;
	case 10:
	    var cType = '';
	    if( typeof param != 'undefined' && typeof param.type != 'undefined' )
		cType = param.type;
	    cFilter = (param.filter==undefined?'':param.filter);
	    $.getJSON('/index.php', { page :'jfriendsList', type:cType, filter:cFilter },
		      function(json) {
			  var s=f_fstart('w_dialog_friendsForm', 'index.php', 'post');
			  s += f_hidden('page', 'sendToAll');
			  s += f_hidden('mode', 'delFriend');
			  /*s += '<div style="float:left">'
			  s += f_case('Все','friend_type_all', 'search_type_nick miniradio','');
			  s += '</div><div style="float:left">'
			  s += f_case('Gmail','friend_type_gmail', 'search_type_nick miniradio','');
			  s += '</div><div style="float:left">'
			  s += f_case('Вконтакте','friend_type_vk', 'search_type_nick miniradio','');
			  s += '</div><div style="float:right">';
			  s += '</div>';
			  s += f_cboth();
			  s += '<fieldset><legend style="margin-left:20px">Контакты</legend>';*/
			  s += '<table><tr><td>';
			  //s += '<div style="float:left; padding-top:5px;"><font color="white"><b>Контакты</b></font></div>';
			  s += '<div style="float:right">';
			  s += '<input type="text" value="'+cFilter+'" name="search" id="search"><img id="searchBtn" style="float:right" src="/img/search.png">';
			  s += '</div></td></tr><tr><td>';
			  s += '<hr size="3" style="background: none repeat scroll 0% 0% black;">'
			  s += '<div id="friendsContent" style="max-height:400px; overflow-y:auto; overflow-x:hidden;"><table width=100%><tr><td colspan=4></td></tr>';
			  var k = 0;
			  for( i in json ) {
			      if(i != 'total') {

				  if( k%3==0 ) {

				      if( k%2 == 0 )
					  s = s+ '<tr>';
				      else
					  s = s+ '<tr style="background-color:#FFAA00">';
								}
								var check_val = json[i].name + '(gmail)';
				  var name = json[i].name.substr(0, 19)

				  if( name != json[i].name )
				      name += '...';
				  var inf = json[i].email.substr(0, 25);
				  if( inf != json[i].email )
				      inf += '...';

				  if( inf == '' ) {
				      inf = 'vkontakte';
				      if( cType == 'vkontakte' ) inf = '';
				      check_val = name + '(vkontakte)';
				  }
				  check_val = json[i].email;
				  s = s + '<td><input type="checkbox" id="check_'+i+'" name="friendlist[]" value="'+check_val+'"></td><td class="friendListTd" id="name_'+json[i].id+'" onclick="$(\'#check_'+i+'\').attr(\'checked\', !$(\'#check_'+i+'\').is(\':checked\'));">'+b(name)+'<br>'+inf+'</td>';
				  k++;
				  if( k%3==0 ) s = s+ '</tr>';
			      }
			  }
			  //fill empty <td>s with bgcolor
			  if( 3-k%3 != 0 )
			      for( j=0; j<=3-k%3;j++ )
				  s+= '<td></td><td></td>';
			  s += '</table></div>';
			  //s += '</table></div></fieldset>';
			  s += '<hr size="3" style="background: none repeat scroll 0% 0% black;"></td></tr><tr><td>';
			  s += '<div style="float:left;"><input type="checkbox" onclick="javascript:PathDispatcher(\'friendslist\', 3, 0)" id="checkall" value="1"> отметить всех/ни одного&nbsp;&nbsp;</div>';
			  s += '<div style="float:right;padding-top:5px; padding-left:10px;">' + f_sbutton('Send', 'PathDispatcher(\'friendslist\',1 )','width:4em') + '</div>';
			  s += '</td></tr></table>';
			  s += f_fend();
			  if( cType != '' )
			      $('#w_myFriends .bttext').html( s );
			  else {
			      viewInfo( 'Ваши контакты', s, 0, '', 'myFriends', 400, 300 );
			  }
			  /*$('#search').keyup(function(e){

				  if(e.keyCode == 13) {
					  PathDispatcher('friendslist', 10, {filter: $('#search').val()})
				  }
			  });*/
			  $('#searchBtn').click(function(){

				  PathDispatcher('friendslist', 10, {filter: $('#search').val()})
			  });
			  $('#friend_type_all').click(function(){

			      PathDispatcher('friendslist', 10, {type:'all'})
			  });
			  $('#friend_type_gmail').click(function(){

			      PathDispatcher('friendslist', 10, {type:'gmail'})
			  });
			  $('#friend_type_vk').click(function(){

			      PathDispatcher('friendslist', 10, {type:'vkontakte'})
			  });

			  if( cType == 'gmail' )
			      $('#friend_type_gmail').attr('src', '/img/radio_w_on.gif');
			  if( cType == 'vkontakte' )
			      $('#friend_type_vk').attr('src', '/img/radio_w_on.gif');
			  if( cType == '' || cType == 'all' ) {
			      $('#friend_type_all').attr('src', '/img/radio_w_on.gif');
			  }


		      }
		     );
	    break;
	}
	break;

    case 'profile': // edit profile
	switch (step) {
	case 0: // edit profile form
	    var c_c='width:10em'
	    var s=[f_fstart('w_dialog_editprofile', 'index.php', 'post'),
		   f_hidden('page', 'edit_profile'),
		   f_hidden('act', 'edit'),
		   '<fieldset><legend style="margin-left: 20px;">Паспортные данные</legend>',
		   f_label('Фамилия: ', c_c),
		   '<div class="param" style="width:14em" name="fio1">',
		   user.fio1,
		   '</div>&nbsp;&nbsp;&nbsp;<a style="float:right" href="javascript:PathDispatcher(\'profile\', 3,0);">Изменить</a><br>',
		   f_label('Имя: ', c_c),
		   '<div class="param" style="width:14em" name="fio2">',
		   user.fio2,
		   '</div><br>',
		   f_label('Отчество: ', c_c),
		   '<div class="param" style="width:14em" name="fio3">',
		   user.fio3,
		   '</div><br>',
		   f_label(Lm.g('Passport')+':', c_c),
		   '<div class="param" style="width:14em" name="passport">',
		   user.passport_ser,
		   ' ',
		   user.passport_num,
		   ' выдан:',
		   user.passport_org,
		   ' ',
		   user.passport_date,
		   '</div><br>',
		   f_label('Пол: ', c_c),
		   '<div class="param" style="width:14em" name="sex">',
		   '<div style="float:left">',
		   f_case('Мужской', 'sex_male', 'sex miniradio',''),
		   '</div><div style="float:left">',
		   f_case('Женский', 'sex_female', 'sex miniradio',''),
		   '</div>',
		   '</div><br>',

		   '</fieldset>',
		   c_c='width:7em'?'':'',
		   '<fieldset><legend style="margin-left: 20px;">Коммуникационные сервисы</legend>',
		   f_label(Lm.g('Email')+': ', c_c),
		   '<div class="param" style="width:13em" name="email">',
		   user.email.length>20?user.email.substr(0, 10) + "..." + user.email.substr(user.email.length-10):user.email,
		   '</div>&nbsp;&nbsp;&nbsp;<a style="float:right" href="javascript:PathDispatcher(\'profile\', 4,0);">Изменить</a><br>',
		   f_label('Вконтакте'+': ', c_c),
		   '<div class="param" style="width:13em" id="vk" name="vk">',
		   user.vk_url,
		   '</div>&nbsp;&nbsp;&nbsp;<a style="float:right" href="javascript:PathDispatcher(\'profile\', 9,\''+user.vk_url+'\');">Изменить</a><br>',
		   f_label('Skype'+': ', c_c),
		   '<div class="param" style="width:13em" id="skype" name="skype">',
		   user.skype.length>20?user.skype.substr(0, 10) + "..." + user.skype.substr(user.skype.length-10):user.skype,
		   '</div>&nbsp;&nbsp;&nbsp;<a style="float:right" href="javascript:PathDispatcher(\'profile\', 10,\''+user.skype+'\');">Изменить</a><br>',
		   f_label('Promodj'+': ', c_c),
		   '<div class="param" style="width:13em" id="promdj" name="promdj">',
		   user.promodj,
		   '</div>&nbsp;&nbsp;&nbsp;<a style="float:right" href="javascript:PathDispatcher(\'profile\', 11,\''+user.promodj+'\');">Изменить</a><br>',
		   f_label('Facebook'+': ', c_c),
		   '<div class="param" style="width:13em" id="facebook" name="facebook">',
		   user.facebook,
		   '</div>&nbsp;&nbsp;&nbsp;<a style="float:right" href="javascript:PathDispatcher(\'profile\', 12,\''+user.facebook+'\');">Изменить</a><br>',

		   '</fieldset>',
		   f_param('<a href="javascript:PathDispatcher(\'profile\', 7, 0)">Изменить пароль</a>', 'text-align:center; width:100%'),
		   f_param('<a href="javascript:PathDispatcher(\'gimport\', 0)">Обновить контакты</a>', 'text-align:center; width:100%' ),
		   f_fend(),
		   f_cboth()].join('')
	    viewInfo(Lm.g('Profile_data'), s, 0, '', 'edit_profile', 450);

		$('.sex').unbind('click').bind('click', function(e) {

			$('.sex').each(function() { this.src='/img/radio_w_off.gif' } )
			e.target.src = '/img/radio_w_on.gif'
			var sex = e.target.id=='sex_female'?0:1;
			user.sex = sex;
			$.ajax({
				async:false,
				dataType:'json',
				url:'/index.php?page=setSex&sex='+sex,
				success: function(j) {}
			})
		})
		if( user.sex == 1 )
			$('#sex_male').attr("src", '/img/radio_w_on.gif');
		if( user.sex == 0 )
			$('#sex_female').attr("src", '/img/radio_w_on.gif');

	    break;
	case 2:// save passport data
	    if (!user.id){
	    	// hide window and wait for login
	    	// FIXME: set functionality
	    	window["passportEdit"].hide();
	    } else {
	    	// send request for change user passport data
		tempInfo('Сохранение изменений',2,'i');
	    	$('#w_dialog_editprofilepassport').ajaxSubmit({
	    	    dataType:'json',
	    	    success: function(j) {
		    	if (j.s == 1) {
		    	    $('#w_edit_profile [name=fio1]').text($('#w_passportEdit input[name=fio1]').val());
		    	    $('#w_edit_profile [name=fio2]').html($('#w_passportEdit input[name=fio2]').val());
		    	    $('#w_edit_profile [name=fio3]').html($('#w_passportEdit input[name=fio3]').val());
		    	    var _s = [$('#w_passportEdit input[name=passport_ser]').val(),
		    		      ' ',
		    		      $('#w_passportEdit input[name=passport_num]').val(),
		    		      ' выдан:',
		    		      $('#w_passportEdit [name=passport_org]').val(),
		    		      ' ',
		    		      $('#w_passportEdit input[name=passport_date]').val()].join('')
		    	    $('#w_edit_profile [name=passport]').html(_s)
		    	    window["passportEdit"].close()
		    	    user.load()
		    	} else
			    tempInfo('Ошибка сохранения изменений!',2,'i')
	    	    }
	    	});
	    	}
	    break;
	case 3://passport data
	    var c_c='width:12em'
	    var _s = [f_fstart('w_dialog_editprofilepassport', 'index.php', 'post'),
		      f_hidden('page', 'setpassport'),
		      'Введите данные для регистрации авторства и выплаты авторского вознаграждения.<br />',
		      f_label('Фамилия:', c_c),
		      f_param(f_input('fio1',((typeof user.fio1 == 'undefined') ? '' : user.fio1),''),''),
		      f_label('Имя:', c_c),
		      f_param(f_input('fio2',((typeof user.fio2 == 'undefined') ? '' : user.fio2),''),''),
		      f_label('Отчество:', c_c),
		      f_param(f_input('fio3',((typeof user.fio3 == 'undefined') ? '' : user.fio3),''),''),
		      f_label('Серия паспорта:', c_c),
		      f_param(f_input('passport_ser',((typeof user.passport_ser == 'undefined')?'':user.passport_ser),''),''),
		      f_cboth(),
		      f_label('Номер:', c_c),
		      f_param(f_input('passport_num',((typeof user.passport_num == 'undefined')?'':user.passport_num),''),''),
		      f_cboth(),
		      f_label('Дата выдачи:', c_c),
		      f_param(f_input('passport_date',((typeof user.passport_date == 'undefined')?'':user.passport_date),''),''),
		      f_cboth(),
		      f_label('Кем выдан:', c_c),
		      f_param(f_textarea('passport_org','',((typeof user.passport_org == 'undefined')?'':user.passport_org),''),''),
		      f_fend(),
		      f_cboth(),
		      f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'profile\',2,0)','width:4em'))].join('')
	    viewInfo(Lm.g('Profile_data'), _s, 0, '', 'passportEdit', 400)
	    break;
	case 4: //edit email
	    var c_c='width:7em'
	    var _s = [f_fstart('w_dialog_editprofilemail', 'index.php', 'post'),
		      f_hidden('page', 'edit_profile'),
		      f_hidden('act', 'editmail'),
		      f_label(Lm.g('Email')+':', c_c),
		      f_param(f_input('email','',''),''),
		      f_label(Lm.g('ReEmail')+':', c_c),
		      f_param(f_input('reemail','',''),''),
		      f_fend(),
		      f_cboth(),
		      f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'profile\',6, \'w_dialog_editprofilemail\')','width:4em'))].join('')
	    viewInfo(Lm.g('Profile_data'), _s, 0)
	    break;
	case 5: //edit profile
	    var c_c='width:7em'
	    var _s=[f_fstart('w_dialog_editprofilepassport', 'index.php', 'post'),
		    f_hidden('page', 'edit_profile'),
		    f_hidden('act', 'editpassport'),
		    f_label(Lm.g('Passport')+':', c_c),
		    f_param(f_input('passport','',''),''),
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'profile\',6,\'w_dialog_editprofilepassport\')','width:4em'))].join('')
	    viewInfo(Lm.g('Profile_data'), _s, 0)
	    break;
	case 6://save email, passport, password, vkontakte url

			var patt=/vkontakte.ru/g;
			if( param == 'w_dialog_editprofilevk' && ( !patt.test($('#w_dialog_editprofilevk [name=vkontakte]').val()) && $('#w_dialog_editprofilevk [name=vkontakte]').val() != "") ) {
				viewInfo('Ошибка', 'Вы ввели некорректный url адрес', 3);
				return;
			}
		    $('#'+param).ajaxSubmit( {
			dataType:'json',
			success: function(j) {
			    if (typeof j.error != 'undefined') { tempInfo( j.error, 3 ); return }
			    if (typeof j.email != 'undefined') { $('#w_dialog_editprofile div[name=email]').html( j.email.length>20?j.email.substr(0, 10) + "..." + j.email.substr(j.email.length-10):j.email ); user.email = j.email }
			    if (typeof j.passport != 'undefined') { $('#w_dialog_editprofile div[name=passport]').html( j.passport) }
			    if (typeof j.vkontakte != 'undefined') { $('#w_dialog_editprofile div[name=vk]').html( j.vkontakte ); user.vk_url = j.vkontakte; }
			    if (typeof j.skype != 'undefined') { $('#w_dialog_editprofile div[name=skype]').html( j.skype.length>20?j.skype.substr(0, 10) + "..." + j.skype.substr(j.skype.length-10):j.skype ); user.skype=j.skype; }
			    if (typeof j.promdj != 'undefined') { $('#w_dialog_editprofile div[name=promdj]').html( j.promdj ); user.promodj=j.promdj; }
			    if (typeof j.facebook != 'undefined') { $('#w_dialog_editprofile div[name=facebook]').html( j.facebook ); user.facebook=j.facebook; }
			    $('#profile_avatar').attr("src", '/avatars/'+user.id+'?' + mr());
			    if (param=='w_dialog_editprofilepass') {
				if (j.s==1) {
				    tempInfo('Пароль изменен',2,'i')
				} else {
				    tempInfo(j.error,2,'i')
				}
			    }
			    vwindow.close();
			}
		    });
	    break;
	case 7:
	    var c_c='width:7em'
	    var _s=[f_fstart('w_dialog_editprofilepass', 'index.php', 'post'),
		    f_hidden('page', 'edit_profile'),
		    f_hidden('act', 'editpass'),
		    f_label(Lm.g('OldPassword')+':', c_c),
		    f_param(f_input('old_pass','',''),''),
		    f_label(Lm.g('Password')+':', c_c),
		    f_param(f_input('new_pass','',''),''),
		    f_label(Lm.g('RePassword')+':', c_c),
		    f_param(f_input('re_new_pass','',''),''),
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'profile\',6, \'w_dialog_editprofilepass\')','width:4em'))].join('')
	    viewInfo(Lm.g('Profile_data'), _s, 0);
	    break;
	case 8:
	    var c_c='width:7em'
	    var _s=[f_fstart('w_dialog_editprofileava', 'index.php', 'post', 'multipart/form-data'),
		    f_hidden('page', 'edit_profile'),
		    f_hidden('act', 'editava'),
		    f_label(Lm.g('Avatar')+':', c_c),
		    f_param(f_file(Lm.g('Browse'),'file'),''),
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'profile\',6, \'w_dialog_editprofileava\')','width:4em'))].join('')
	    viewInfo(Lm.g('Profile_data'), _s, 0, '', '', 400)
	    break;
	case 9://edit vkontakte
	    var c_c='width:7em'
	    var _s=[f_fstart('w_dialog_editprofilevk', 'index.php', 'post'),
		    f_hidden('page', 'edit_profile')+f_hidden('act', 'edivk'),
		    'Здесь Вы можете указать свой айди Вконтакте, чтобы быть на связи с другими пассажирами Ledokol\'a<br><br>',
		    f_cboth(),
		    f_label('URL:', c_c),
		    f_param(f_input('vkontakte',param,''),''),
		    f_cboth(),
		    '<font size=1 color="gray">Варианты url: <br>http://vkontakte.ru/id123456 <br>http://yourlogin.vkontakte.ru<br>http://vkontakte.ru/yourlogin</font>',
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'profile\',6, \'w_dialog_editprofilevk\')','width:4em'))].join('')
	    viewInfo('Вконтакте', _s, 0)
	    break;
	case 10://edit skype
	    var c_c='width:7em'
	    var _s=[f_fstart('w_dialog_editprofilesk', 'index.php', 'post'),
		    f_hidden('page', 'edit_profile')+f_hidden('act', 'ediskype'),
		    'Здесь Вы можете указать свой Skype, чтобы быть на связи с другими пассажирами Ledokol\'a<br><br>',
		    f_cboth(),
		    f_label('Skype:', c_c),
		    f_param(f_input('skype',param,''),''),
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'profile\',6, \'w_dialog_editprofilesk\')','width:4em'))].join('')
	    viewInfo('Skype', _s, 0)
	    break;
	case 11://edit promdj
	    var c_c='width:7em'
	    var _s=[f_fstart('w_dialog_editprofilesk', 'index.php', 'post'),
		    f_hidden('page', 'edit_profile')+f_hidden('act', 'ediprom'),
		    'Здесь Вы можете указать свой Promodj аккаунт, чтобы быть на связи с другими пассажирами Ledokol\'a<br><br>',
		    f_cboth(),
		    f_label('Promdj:', c_c),
		    f_param(f_input('promdj',param,''),''),
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'profile\',6, \'w_dialog_editprofilesk\')','width:4em'))].join('')
	    viewInfo('Promodj', _s, 0)
	    break;

	case 12://edit facebook
	    var c_c='width:7em'
	    var _s=[f_fstart('w_dialog_editprofilesk', 'index.php', 'post'),
		    f_hidden('page', 'edit_profile')+f_hidden('act', 'ediface'),
		    'Здесь Вы можете указать свой Facebook аккаунт, чтобы быть на связи с другими пассажирами Ledokol\'a<br><br>',
		    f_cboth(),
		    f_label('Facebook:', c_c),
		    f_param(f_input('facebook',param,''),''),
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'profile\',6, \'w_dialog_editprofilesk\')','width:4em'))].join('')
	    viewInfo('Facebook', _s, 0)
	    break;
	}
	break;

    case 'money': // money block
	switch (step) {
	case 0: // main money form
	    var c_c='width:15em;margin:2px'
	    var _s=[f_button(Lm.g('Increase_balance'), 'PathDispatcher(\'money\',1,0)', c_c),
		    f_button(Lm.g('Get_money'), 'PathDispatcher(\'money\',2,0)', c_c),
		    f_button(Lm.g('Balance_information'), 'PathDispatcher(\'money\',4,0)', c_c)].join('<br>')
	    viewInfo(Lm.g('Your_balance'), _s, 0);
	    break;
	case 1: // increase balance
	    $.get('index.php?page=getaddmoneyform&mode='+param, function(s) {
	    	viewInfo(Lm.g('Increase_balance'), s, 0,'ledokol.buy_track_id = 0; ledokol.buy_track_user_id = 0; PathDispatcher("money",0,0)')
	    })
	    break;
	case 2: //
	    var c_w='width:10em'
	    var _s=[f_fstart('getMoneyForm', 'index.php', 'post'),
		    f_hidden('page', 'outputFromAcc'),
		    f_label(Lm.g('Account_WMZ')+':', c_w)+f_param(f_input('wm','',''),''),
		    f_label('На телефон:', c_w),
		    '<div class="param" style="width:300px">',
		    '<select name="operator" style="margin:0">',
		    '<option value="beeline">Билайн</option>',
		    '<option value="mts">МТС</option>',
		    '<option value="megafon">МегаФон</option>',
		    '</select>',
		    '+',
		    '<input type="text" class="input" value="7" name="phone1" size="1" maxlength="1" style="width:10px;margin:0 5px 0 0">',
		    '<input type="text" class="input" value="" name="phone2" size="3" maxlength="3" style="width:30px;margin:0 5px 0 0">',
		    '<input type="text" class="input" value="" name="phone3" size="7" maxlength="7" style="width:70px">',
		    '</div>',
		    f_label('Credit Card:', c_w),
		    f_param(f_input('card','',''),''),
		    f_label(Lm.g('Amount')+':', c_w),
		    f_param(f_input('sum',user.account,''),''),
		    f_cboth(),
		    '<div>Если у Вас еще нет электронного кошелька, Вы можете его сделать здесь <a href="http://start.webmoney.ru/" target="_blank">WebMoney</a></div>',
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'money\',3,0)','width:4em'))].join('');
	    viewInfo(Lm.g('Get_money'), _s, 0, '', 'vwindow', 500);
	    break;
	case 3:
	    $('#getMoneyForm').ajaxSubmit( { dataType:'json', success: function(j) {
		(j.s) ? viewInfo(Lm.g('Message'),'Заявка принята и будет рассмотрена в течении суток. Спасибо.',0) : tempInfo('У вас недостаточно средств для вывода',2,'w')
	    }})
	    break;
	case 4:
	    var c_w='width:20em'
	    var _s=[f_label(Lm.g('Money_in_game')+': '+'<span id="g_b">...</span> руб.', c_w),
		    f_label(Lm.g('Author_money')+': '+'<span id="i_b">...</span> руб.', c_w),
		    f_label(f_sbutton('Подробнее', 'PathDispatcher(\'money\', 5, 0)', 'width:120px'), c_w)].join('');
	    viewInfo(Lm.g('Balance_information'), _s, 0);
	    $.getJSON('/index.php', {page:'get_balance_info',ac:mr()}, function(j) { $('#g_b').text(j.gameBalance); $('#i_b').html(j.incomeBalance)	});
	    break;
	case 5:
	    $.getJSON('/index.php', {page:'get_sales_info', track_id:param, ac:mr()}, function(j) {
		var s = ['<div id="sales_info"></div>'];
		viewInfo(Lm.g('Balance_information'), s.join(''), '', '', '', 800, 300);
		var c_w='width:20em'
		if( j ) {
		    var t = ['<div id="th"><div class="thdate">Дата</div><div class="thop">Операции</div><div class="thout">Расход</div><div class="thin">Доход</div></div>'], total_in=0, total_out=0, _t
		    for( i=0; i<j.length; i++) {
			total_in += (j[i].s_in=="") ? 0 : parseFloat(j[i].s_in);
			total_out += (j[i].s_out=="") ? 0 :parseFloat(j[i].s_out);
			if (j[i].s_out == '') j[i].s_out = '&nbsp;';
			if (j[i].s_in == '') j[i].s_in = '&nbsp;';
			_t=['<div class="',
			    j[i].tranz,
			    '"><div class="tddate">',
			    j[i].d,
			    '</div><div class="tdop" nowrap>',
			    j[i].tname,
			    '</div><div class="tdout">',
			    j[i].s_out,
			    '</div><div class="tdin">',
			    j[i].s_in,
			    '</div></div>'].join('')
			t.push(_t)
		    }
		    t.push('<div class="inall"><div class="tddate">&nbsp;</div><div class="tdop">Итого: ')
		    t.push(Math.round((total_in-total_out)*100)/100)
		    t.push('</div></div>')
		} else if( param > 0 ){
		    var t = [f_label('Продажи по треку отсутствуют', c_w)]
		    $('#sales_info').css({background:'transparent',width:'300px',height:'50px'})
		} else {
		    var t = [f_label('Продажи ваших треков отсутствуют', c_w)];
		    $('#sales_info').css({background:'transparent',width:'300px',height:'50px'})
		}
		$('#sales_info').html(t.join(''))
	    })
	    break
	}
	break

    case 'pledit': // edit playlist cases
	switch (step) {
	case 0: // edit playlist form
	    var c_w='width:7em', c_s=playlist.playlists[param]
	    var _s=[f_fstart('editplistform', 'index.php', 'post'),
		    f_hidden('page', 'edit_playlist'),
		    f_hidden('id', c_s.id),
		    f_label(Lm.g('Title')+':', c_w),
		    f_param(f_input('name',c_s.name,''),''),
		    f_cboth(),
		    f_label(Lm.g('Avatar')+':', c_w),
		    f_param(f_file(Lm.g('Browse'),'file'),''),
		    f_label('', c_w),
		    f_cboth(),
		    f_param('<a href="#" onclick="PathDispatcher(\'pledit\',1,'+param+');return false">'+Lm.g('Delete_playlist')+'</a>','width:13em')+'<br>',
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'pledit\',3,'+param+')','margin:0 0 0 0.5em;width:4em'))].join('')
		    playlist.init_playlist = c_s.id;
	    viewInfo(Lm.g('Playlist_propertys'), _s, 0, '', 'plwindow', 400)
	    break;
	case 1: // delete playlist form
	    var _s=[f_label('Вы действительно хотите удалить плейлист: '+playlist.playlists[param].name+'?', 'text-align:center;width:20em'),
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'pledit\',2,'+playlist.playlists[param].id+')','margin:0 0 0 0.5em;width:4em'))].join('')
	    viewInfo(Lm.g('Delete_playlist'), _s, 0, '', 'plwindow', 300)
	    break;
	case 2: // delete info message
	    $.getJSON('/index.php', {page:'del_playlist', id:param}, function(j) {
		closeW('plwindow');
		if (j.s==1) {
		    _m= Lm.g('Playlist_deleted');
		    playlist.jinit();
		} else if (j.s==2) {
		    _m= 'Плейлист содержит неудаленные треки'
		} else {
		    _m= 'Ошибка удаления плейлиста'
		}
		tempInfo(_m, 2, 'i')
	    });
	    break;
	case 3: // send edit playlist form
	    $('#editplistform').ajaxSubmit( {dataType:'json', success:function(j) {
		closeW('plwindow');
		if (j.s) {
		    playlist.jinit();
		}
		viewInfo(Lm.g('Edit_track_info'), j.m, 2)
	    }});
	    break;
	case 4: // new playlist form
	    var c_w='width:7em', c_s=playlist.playlists[param]
	    var _s=[f_fstart('newplistform', 'index.php', 'post'),
		    f_hidden('page', 'new_playlist'),
		    f_label(Lm.g('Title')+':', c_w)+f_param(f_input('name','',''),''),
		    f_cboth(),
		    f_label(Lm.g('Avatar')+':', c_w)+f_param(f_file(Lm.g('Browse'),'file'),''),
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'pledit\',5,'+param+')','margin:0 0 0 0.5em;width:4em'))].join('')
	    viewInfo(Lm.g('Add_playlist'), _s, 0, '', 'plwindow', 400)
	    break;
	case 5: // send new playlist form
	    if ($('#w_plwindow input[name=name]').val()=='') { tempInfo('Необходимо ввести название!',2,'w'); return; }
	    $('#newplistform').ajaxSubmit( {dataType:'json', success:function(j) {
		(j.s) ? playlist.jinit() : tempInfo('Ошибка создания плейлиста',2,'w');
		closeW('plwindow')
	    }});
	    break;
	case 6: // updated new playlist form with playlist type selection. Used in Buy+Play
	    var c_w='width:7em'; //c_s=playlist.playlists[param]
	    var _s=[f_fstart('newplistform', 'index.php', 'post'),
		    f_hidden('page', 'new_playlist'),
		    f_hidden('pl_type', ''),
		    f_label(Lm.g('Title')+':', c_w)+f_param(f_input('name','',''),''),
		    f_cboth(),
		    //f_label(Lm.g('Avatar')+':', c_w)+f_param(f_file(Lm.g('Browse'),'file'),''),
		    f_cboth(),
		    f_case('Album (20 треков или 1 час), стоимость 200р','pl_type_album', 'pl_type miniradio',''),
		    f_cboth(),
		    f_case('Set (100 треков или 6 часов), стоимость 1000р','pl_type_set', 'pl_type miniradio',''),
		    f_cboth(),
		    f_case('Radio (200 треков или 12 часов), стоимость 2000р','pl_type_radio', 'pl_type miniradio',''),
		    f_cboth(),
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'pledit\',7,{\'u_id\':'+param.u_id+',\'id\':'+param.id+', \'next\':'+param.next+'})','margin:0 0 0 0.5em;width:4em'))].join('')
	    viewInfo(Lm.g('Add_playlist'), _s, 0, '', 'plwindow', 400);
		$('.pl_type').unbind('click');
		$('.pl_type').bind('click',
			function(e){

				$('.pl_type').each(
					function(){this.src='/img/radio_w_off.gif';}
				);
				e.target.src = '/img/radio_w_on.gif';
				$("input[name=pl_type]").val(e.target.id.replace("pl_type_", ""));
			}
		);

	    break;
	case 7: // send new playlist form
	    if ($('#w_plwindow input[name=name]').val()=='') { tempInfo('Необходимо ввести название!',2,'w'); return; }
	    $('#newplistform').ajaxSubmit( {dataType:'json', success:function(j) {

	    	if( j.s == 1 ) {
		    	$('input[name="playlistId"]').val(j.playlist_id);
		    	$('#w_buy_dialog').hide();
		    	PathDispatcher('buy', param.next, {'u_id':param.u_id,'id':param.id} );
		    	closeW('plwindow')
	    	} else {
	    		mess = 'У вас недостаточно денег<br><button onclick="PathDispatcher(\'money\',1,2)" style="width: 15em; margin: 2px;" type="button" class="tbutton">Увеличить баланс</button>';
				viewInfo(Lm.g('Message'), mess, 0);
	    		//tempInfo( j.msg, 5 );
	    		if(j.code == 2) { //not enough money

	    		    ledokol.buy_track_id = param.id;
	    		    ledokol.buy_track_user_id = param.u_id;
	    		    ledokol.buy_pl_type = $('#w_plwindow input[name=pl_type]').val();
	    		    ledokol.buy_pl_name = $('#w_plwindow input[name=name]').val();
	    		    ledokol.buy_param = param.next;
	    		}
	    		$('#w_buy_dialog').hide();
	    		$('#w_plwindow').hide();
	    	}
	    }});
	    break;
	}
	break;

    case 'trackinfo': // track block
	switch (step) {
	case 0: // track info
	    var absId=playlist.getTrackAbsolutePosition(param,playlist.cplaylist), c_s=playlist.tracks[playlist.cplaylist][absId];
	    var _s=[Lm.g('Title'),
		    ': ',
		    b(c_s.name),
		    '<br>',
		    Lm.g('Artist'),
		    ': ',
		    b(c_s.artist),
		    '<br>',
		    Lm.g('Bitrate'),
		    ': ',
		    b(c_s.bitrate),
		    ' kbit/s',
		    '<br>',
		    Lm.g('Price_rub'),
		    ': ',
		    b(c_s.price),
		    '<br>',
		    Lm.g('Sales'),
		    ': <b id="ts">...</b> ',
		    Lm.g('RUR'),
		    f_dbuttons([f_button(Lm.g('Delete'), ['PathDispatcher(\'trackinfo\',1,',absId,')'].join(''),''),
				(c_s.init_user=='0') ? f_button(Lm.g('Edit'), ['PathDispatcher(\'trackinfo\',2,',absId,')'].join(''), 'margin:0 0 0 0.5em;width:10em') : ''].join(''))].join('')
	    closeW('vwindow')

	    viewInfo(Lm.g('Track_information'), _s, 0, '', 'vwindow', 400)
	    $.getJSON('/index.php', {page:'jts', track:c_s.id}, function(j) { $('#ts').text(j.ts) });
	    break;
	case 1: // delete track message
	    $.getJSON('/index.php', {page:'deltrack', playlist:playlist.playlists[playlist.cplaylist].id, del:playlist.tracks[playlist.cplaylist][param].id}, function(j) {
		if (j.s) { playlist.jinit(); viewInfo(Lm.g('Delete_track'), 'Трек удален', 2) }
	    });
	    break;
	case 2: // track edit
	    var c_w='width:7em', c_s=playlist.tracks[playlist.cplaylist][param]
	    var _s=[f_fstart('edittiform', 'index.php', 'post'),
		    f_hidden('page', 'edittrack'),
		    f_hidden('id', c_s.id),
		    f_hidden('is_author', c_s.author),
		    f_label(Lm.g('Title')+':', c_w),
		    f_param(f_input('name',c_s.name,''),''),
		    f_label(Lm.g('Artist')+':', c_w),
		    f_param(f_input('artist',c_s.artist,''),''),
                    (c_s.author==1) ? [f_label(Lm.g('Price_rub')+':', c_w),f_param(f_input('price',c_s.price,''),'')].join('') : f_hidden('price', c_s.price),
		    f_cboth(),
		    f_case(Lm.g('I_am_author'), 'author_check', 'miniradio', ''),
		    '<br>',
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'trackinfo\',3,{name:\''+c_s.name+'\', artist:\''+c_s.artist+'\', price:\''+c_s.price+'\'})','width:4em'))].join('');
	    viewInfo(Lm.g('Edit_track_info'), _s, 0);
	    $("#author_check").bind('click', function(){
		if ($(this).attr('src') == '/img/radio_w_on.gif') {
		    $(this).attr('src', '/img/radio_w_off.gif');
		    $("input[name='is_author']").val(0);
		    playlist.tracks[playlist.cplaylist][param].author=0
		} else {
		    $(this).attr('src', '/img/radio_w_on.gif');
		    $("input[name='is_author']").val(1);
		    playlist.tracks[playlist.cplaylist][param].author=1
		}
		return false
	    });
            $('#author_check').attr('src','/img/radio_w_'+((c_s.author==1) ? 'on' : 'off')+'.gif');
	    break;
	case 3: // form send
	    if ($('#edittiform input[name=price]').val()<10) { tempInfo('Вы не можете установить цену менее 10 руб.', 3, 'w');	return 	}
	    $('#edittiform').ajaxSubmit( {dataType:'json', success:function(j) {
		if (j.s) {
		    param.name=$('#edittiform input[name=name]').val();
		    param.artist=$('#edittiform input[name=artist]').val();
		    param.price=$('#edittiform input[name=price]').val();
		    var c_id=$('#edittiform input[name=id]').val();
		    $('#'+c_id+'_t .lname').text(param.name);
		    $('#'+c_id+'_t .lart').text(param.artist);
		    // edit in playlist object
		    for (var plp=0; plp < playlist.tracks.length; plp++ ){
			if (playlist.tracks[plp] != null) {
			    var _pplp=playlist.tracks[plp];
			    for (var _tr=0; _tr<_pplp.length; _tr++) {
				if (_pplp[_tr].id == c_id) {
				    _pplp[_tr].name = param.name;
				    _pplp[_tr].artist = param.artist;
				    _pplp[_tr].price = param.price
				}
			    }
			}
		    }

		}
		viewInfo(Lm.g('Edit_track_info'), (j.s) ? Lm.g('Inf_update_successful') : Lm.g('Inf_update_error'), 2)
	    }});
	    break;
	}
	break;

    case 'buy': // buy tracks block
	switch (step) {
	case 0: // track info for sale
	    track.id = track.id ? track.id : track.id2 
	    var t_u_id = track.u_id, t_id = track.id;
	    if (typeof param.u_id != 'undefined' && typeof param.id != 'undefined' ) {
		t_u_id = param.u_id;
		t_id = param.id
	    }
	    $.getJSON('/index.php', {page:'getprice', userid:t_u_id, trackid:t_id}, function(j) {
		if (j.s) {
		    if (j.s==2) { viewInfo(Lm.g('Message'), 'Этот трек есть в вашем плейлисте'); return }
		    PathDispatcher('buy', 7, {'b':128, 'p':10.00, 'u_id':t_u_id,'id':t_id,'next':1})
		} else
		    viewInfo(Lm.g('Message'),((j.m==1) ? 'Нет информации по треку - покупка невозможна' : 'Для покупки треков необходима регистрация'), 0)
	    });
	    break;
	case 1: // buy track

		var pl = $('input[name="playlistId"]').val();
		if( pl == undefined ) {
			pl = param.pl_id;
		}
		$.getJSON('/index.php', {page:'AJAX_byeTrack', playlistId: pl,userid:param.u_id, trackid:param.id, credit:0}, function(j) {
		var mess = '';
		if (j.s != 1){
		    switch (j.c){
		    case 3:
			mess = 'У вас недостаточно денег<br><button onclick="PathDispatcher(\'money\',1,0)" style="width: 15em; margin: 2px;" type="button" class="tbutton">Увеличить баланс</button>';
			ledokol.buy_track_id = param.id;
			ledokol.buy_track_user_id = param.u_id;
			$.getJSON('/index.php', {page:'setPreorder', pl:pl, user:param.u_id, track: param.id});
			break;
		    case 4: mess = 'У продавца нет этого трека'; break;
		    case 5: mess = 'Этот трек уже есть в вашем плейлисте'; break;
		    case 7: mess = 'Нет свободного места в плейлисте'; break;
		    default: mess = 'Системная ошибка'
		    }
		} else {
		    mess = j.m + "<br><a href='javascript:void(0)' onclick='PathDispatcher(\"gimport\", 1, "+j.id+");'>Послать друзьям</a>";
		}
		viewInfo(Lm.g('Message'), mess, 0);
		user.load();
		playlist.jinit();
		page.changePage('playlist', pl);
	    });
	    break;
	case 2: // bye not uniq track when upload
		PathDispatcher('buy', 0, {u_id:param.ru, id:param.rt});
	    /*var _s=[f_fstart('buynuniqform', 'index.php', 'post'),
		    f_hidden('page','buyathalfprice'),
		    f_hidden('track',param.trackid),
		    f_hidden('rt',param.rt),
		    f_dtext('Трек ранее был загружен другим игроком. Для ввода трека в игру от вашего имени, вам необходимо откупиться, заплатив авторские отчисления'),
		    Lm.g('Bitrate'),
		    ': ',
		    b(param.b/1000),
		    ' KBit/s<br>',
		    Lm.g('Price_rub'),
		    ': ',
		    b(param.p),
		    f_cboth(),
		    f_dbuttons(f_sbutton(Lm.g('Buy'), (!user.id) ? 'window.buynuniqt.hide();PathDispatcher(\'authorize\', 0, \'buy\')' : 'PathDispatcher(\'buy\', 3, 0)', 'width:6em')+f_button('Не купить', 'PathDispatcher(\'upload\', 7, 0)', 'width:8em;margin:0 0 0 5px'))].join('')
	    viewInfo(Lm.g('Track_not_unique'), _s, 0, 'PathDispatcher(\'upload\', 6, 0)','buynuniqt');
	    window['buynuniqt'].close = function(){
	    	$('#w_buynuniqt').remove();
	    	window['buynuniqt'].id=null;
	    	$('#ledokol').find('.button_upload').removeClass('button_upload_in_progress')
	    }*/
	    break;
	case 3: // send request for buy not unique track
	    $('#buynuniqform').ajaxSubmit({dataType:'json', success:function(j) {
		if (j.s==1) {
		    playlist.jinit();
		    closeW('buynuniqt');
		    viewInfo(Lm.g('Message'),Lm.g('Track_upload_successful'),0);
		} else {
		    switch (j.r) {
		    case 1: var s = Lm.g('System_error'); break;
		    case 2: var s = Lm.g('System_error'); break;
		    case 3: var s = Lm.g('Not_money_for_buy'); break;
		    case 4: var s = Lm.g('Saler_do_not_have_this_track'); break;
		    case 5: var s = Lm.g('Track_already_present'); break;
		    default: var s = Lm.g('Unknown_error')
		    }
		    if (param=='auth') buynuniqt.show();
                    tempInfo(s, 3, 'w');
		}
	    }});
	    break;
	case 4:
	    var t_u_id = track.u_id, t_id = (track.id >0) ? track.id : track.id2;
	    $.getJSON('/index.php', {page:'getprice', userid:t_u_id, trackid:t_id}, function(j) {
		if (j.s)
		    (j.s==2) ? PathDispatcher('sendmail', 0, 0) : PathDispatcher('buy', 7, {'b':128, 'p':10.00, 'u_id':t_u_id,'id':t_id,'next':5})
		else
		    viewInfo(Lm.g('Message'), j.m, 0)
	    });
	    break;
	case 5:
	    $.getJSON('/index.php', {page:'AJAX_byeTrack', userid:param.u_id, trackid:param.id},
		      function(j) {
		    	  viewInfo(Lm.g('Message'), j.m, 0);
		    	  PathDispatcher('sendmail', 0, 0);
		      });
	    break;
	case 6:
	    $.getJSON('/index.php', {page:'buymp3',track:param.id}, function(j) {
		switch (j.status) {
		case 1: var _m = 'Трек успешно куплен'; break;
		case -1: var _m = 'Неудача при скачивании трека'; break;
		case -2: var _m = 'Сервер отклонил запрос'; break;
                case -3: var _m = 'У вас нет средств на покупку трека'; break;
                }
		tempInfo(_m, 2, 'i')
	    });
	    break;

	case 7:
	    PathDispatcher('upload', 11, {'u_id':param.u_id,'id':param.id, 'next':param.next})
	    break;

	case 8: // pre-upload form for unauthorize user
	    var _s=[f_fstart('w_dialog_isAuth', 'index.php', 'post'),
		    '<div style="text-align:center">',
		    f_dbuttons([f_sbutton("Звучащий", "PathDispatcher('buy',9)","width:12em"),'&nbsp;&nbsp;&nbsp;&nbsp;',f_button('Свой', "PathDispatcher('register', 0, 'buy_myself')", 'width:12em')].join('')),
		    '</div>',
		    f_fend(),
		    f_cboth()].join('')
	    viewInfo('Переход на игровой уровень<br/>Создать плейлист и добавить трек', _s, 0, '', '', 400)
	    break

	case 9: // buy current track for unauthorize user
	    ledokol.credit_track = track.id
	    ledokol.credit_user = track.u_id
	    PathDispatcher('register',0,'buy')
	    break

    case 10:


    	/*if( ledokol.credit_plname != '' ) {
    		$.getJSON('/index.php', {page:'new_playlist', name:ledokol.credit_plname}, function(j) {});
    	}*/

	    $.getJSON('/index.php', {page:'AJAX_byeTrack', userid:param.u_id, trackid:param.id, plname:ledokol.credit_plname, credit:1}, function(j) {
			var mess = '';
			if (j.s != 1){
			    switch (j.c){
			    case 3:
				mess = 'У вас недостаточно денег<br><button onclick="PathDispatcher(\'money\',1,0)" style="width: 15em; margin: 2px;" type="button" class="tbutton">Увеличить баланс</button>';
				ledokol.buy_track_id = param.id;
				ledokol.buy_track_user_id = param.u_id;
				break;
			    case 4: mess = 'У продавца нет этого трека'; break;
			    case 5: mess = 'Этот трек уже есть в вашем плейлисте'; break;
       		    case 7: mess = 'Нет свободного места в плейлисте'; break;
			    default: mess = 'Системная ошибка'
			    }
			} else {
			    mess = j.m + "<br><a href='javascript:void(0)' onclick='PathDispatcher(\"gimport\", 1, "+j.id+");'>Послать друзьям</a>";
			}
			viewInfo(Lm.g('Message'), mess, 0);
			user.load();
			playlist.jinit()
		    });
    	break;

	}

	break;

    case 'forgotPass':
	switch (step) {
	case 0: // forgot pass form
	    $('#w_vwindow').hide();
	    var c_w='width:7em'
	    var _s = [f_fstart('dialog_forgotPassForm', 'index.php', 'post'),
		      f_label(Lm.g('Email')+':', c_w),
		      f_param(f_input('email','',''),''),
		      '<br>',
		      f_cboth(),
		      f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'forgotPass\',1,\''+param+'\')','width:4em')),
		      f_fend()].join('');
	    viewInfo(Lm.g('Forgot_pass_title'), _s, 0, '$(\'#w_vwindow\').show(); window["forgot_win"].close();', 'forgot_win');
	    break;
	case 1: //password recovery
	    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	    if (filter.test($('#dialog_forgotPassForm input[name=email]').val())) {
		$.getJSON('/index.php', {page:'forgotPass', email:$('#dialog_forgotPassForm input[name=email]').val()}, function(j) {
		    window["forgot_win"].close();
		    tempInfo(j.m, 3,'i');
 		    if (j.s) $('#w_vwindow').show()
		});
	    } else
		tempInfo('Вы неправильно ввели e-mail',5,'w');
	    break;
	}
	break;

    case 'authorize': // authorize
	switch (step) {
	case 0: // authorize form
 	    if (helper.g('newupload')) return PathDispatcher('register',0,param);
	    var t, c_w='width:7em', s=[f_fstart('dialog_authForm', 'index.php', 'post')];
	    s.push(f_hidden('page','authorize'));
	    if (param=='uplnutrack') {
		st=Lm.g('Authorize_for_upload');
		t=Lm.g('Authorize_please_when_buy');
		if (param=='upload') {
		    s.push('<div style="margin:0 0 5px 0">Ваш трек уникален.  Мы приглашаем вас зарегистрироваться в игре.</div>');
		}
	    } else if (param=='buy') {
		// rezume rolling
		$('#ledokol').find('.button_upload').addClass('button_upload_in_progress');
		st=Lm.g('Authorize_for_buy_track');
		t=Lm.g('Authorize_please_when_buy')
	    } else {
		if (param=='upload') {
		    s.push('<div style="margin:0 0 5px 0">Ваш трек уникален.  Мы приглашаем вас зарегистрироваться в игре.</div>');
		}
		st=Lm.g('Authorize_for_listen_playlist');
		t='<div style="text-align:center;margin:7px 0 5px 0">Переход на <a href="#" onclick="PathDispatcher(\'rules\',2,\'tdiv_10\');return false">игровой уровень</a></div>';
		s.push('<div class="tdiv" id="tdiv_10">Игровой уровень - это уровень, который позволяет <a href="#" onclick="PathDispatcher(\'rules\',0,0);return false">играть</a> и выигрывать</div>');
	    }
	    s.push('<div class="tdiv" id="tdiv_10">Игровой уровень - это уровень, который позволяет <a href="#" onclick="PathDispatcher(\'rules\',0,0);return false">играть</a> и выигрывать</div>');
   	    s.push(f_dtext('<div style="text-align: center; padding: 0pt 0pt 0pt 25px;">Представьтесь</div>'));
	    s.push(f_dtext(st));
	    s.push(f_label(Lm.g('Name3')+':', c_w)+f_param(f_input('nick','',''),'')+'<br>');
	    s.push(f_label(Lm.g('Password')+':', c_w)+f_param(f_password('pass','',''),'')+'<br>');
	    if (param=='upload' || param=='uplnutrack' || param=='buy') {
		if (param!='buy') { //TODO!!!
		    s.push(f_label('', c_w)+f_param('<a href="#" onclick="PathDispatcher(\'register\',0,\''+param+'\');return false">'+Lm.g('register_link')+'</a>','')+'<br>')
		}
	    } else {
		if (window.invite) {
		    s.push(f_label('', c_w)+f_param('<a href="#" onclick="PathDispatcher(\'upload\',0,\'new\');return false">'+Lm.g('register_link')+'</a>','')+'<br>')
		} else {
		    //s.push(f_label('', c_w)+f_param('<a href="#" onclick="PathDispatcher(\'register\',0,\''+param+'\');return false">'+Lm.g('register_link')+'</a>','')+'<br>')
		}
				}
	    s.push(f_label('', c_w)+f_param('<a href="#" onclick="PathDispatcher(\'forgotPass\',0,\''+param+'\');return false">'+Lm.g('Forgot_pass_quest')+'</a>','')+'<br>');
	    s.push(f_fend()+f_cboth());
	    s.push(f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'authorize\',1,\''+param+'\')','width:4em')));
	    viewInfo(t, s.join(''), 0);
	    window['vwindow'].close = function() {
		$('#w_vwindow').remove();
		window['vwindow'].id = null;
		$('#ledokol').find('.button_upload').removeClass('button_upload_in_progress')
	    }
	    break;
	case 1: // send form
	    if ($('#dialog_authForm input[name=nick]').val().length<1) { tempInfo('Не указано имя', 2, 'w'); return false }
	    if ($('#dialog_authForm input[name=pass]').val().length<1) { tempInfo('Не указан пароль', 2, 'w'); return false }
	    $('#dialog_authForm').ajaxSubmit({dataType:'json', success:function(j) {
		if (j.s == 1) {
		    closeW('vwindow')
		    user.load()
		    ledokol.unmute()
		    ledokol.setAuth()
		    ledokol.setMaxi()
		    pd.playtype.setRandom()
		    ledokol.setRandom()
		    ledokol.logicTop()
		    $('#usertitle').attr('class', 'auth');
		    if (param=='upload') PathDispatcher('upload', 5, 0);
		    if (param=='buy') PathDispatcher('buy', 3, 'auth')
		    if (param=='uplnutrack') PathDispatcher('upload', 8);
		    if (param=='doUpload') $('#add_track_form_2').submit();
		    if (param=='doBuy') PathDispatcher('buy', 0, 0)
		    // change passport data on authorize
		    if ($('#w_passportEdit').length!=0) PathDispatcher('profile', 2);
		    if (j.sex==0) PathDispatcher('register', 2, 0)
		} else
		    tempInfo(Lm.g('Invalid_name_or_password'), 2, 'w')
	    }});
	    break
	case 2: // direct authorize without form for register with upload
	    $.getJSON('/index.php', {page:'authorize', nick:param[0], pass:param[1]}, function(j) {
		if (j.s) {
		    user.load();
		    ledokol.unmute()
		    ledokol.setAuth()
		    ledokol.setMaxi()
		    ledokol.setRandom()
		    ledokol.logicTop()
		    user.load();
		    $('#usertitle').attr('class', 'auth');
		    tempInfo('Вы  в игре!', 3, 'i');
		    if( ledokol.buy_myself == 1 ) {
		    	var dwindow = $('#w_vwindow');
		    	PathDispatcher('upload', 1, 0);
		    } else {
		    	PathDispatcher('upload', 5, 0);
		    }
		} else
		    tempInfo(Lm.g('Invalid_name_or_password'), 2, 'w')
	    });
	    break;
	case 3:
	    $.getJSON('/index.php', {page:'fastAuth', user:param[0], hash:param[1], nick:param[2]}, function(j) {
		if (j.s == 1) {
		    user.load()
		    ledokol.unmute()
		    ledokol.setAuth()
		    ledokol.setMaxi()
		    pd.playtype.setRandom()
		    ledokol.setRandom()
		    ledokol.logicTop()
		    $('#usertitle').attr('class', 'auth')
		    if (param[3]=='down') {
			var os = navigator.platform.indexOf('Win')!=-1?'Windows':'Mac';
			var link = 'http://ledokol.com/?page=down'+os;
			$('#w_vwindow').hide();
			setTimeout("window.location='"+link+"'", 2000)
		    }
		    if (j.sex==0) PathDispatcher('register', 2)
		} else {
		    PathDispatcher('authorize', 0)
		    $('#dialog_authForm input[name=nick]').val(param[2])
		}
	    });
	    break;
	case 4:
	    if ($('form input[name=nick]').val() != "" && $('form input[name=pass]').val() != "")
		PathDispatcher('authorize',1, 'down');
	    else
		tempInfo( 'Авторизуйтесь и снова нажмите на получи', 5 );
	    break;
	case 5: //fast authorize and download
	    param.push('down');
	    PathDispatcher('authorize',3, param);
	    break;
	case 6: //just download desktop ledokol version
	    var os = navigator.platform.indexOf('Win')!=-1?'Windows':'Mac';
	    var link = 'http://ledokol.com/?page=down'+os;
	    window.location=link;
	    break;
	}
	break;

    case 'unauthorize': // unauthorize user
	user.clear()
	$.getJSON('index.php', {page:'unauthorize',ac:mr()}, function() {
	    $('#usertitle').attr('class','unauth')
	    ledokol.setUnauth()
	    playlist.hide()
	    playlist.clear()
	    usertop.hlines=[]
	    ledokol.logicTop()
	})
	break

    case 'upload': //  upload track
	switch (step) {
	case 0: // file-upload form
	    if (param=='new') {
		helper.s('newupload',1)
		closeW('vwindow')
	    } else
		helper.s('newupload',0)
	    var _s=[f_fstart('add_track_form', 'cgi-bin/upload.cgi', 'post', 'multipart/form-data'),
		    '<div class="tdiv" id="tdiv_10">Игровой уровень - это уровень, который позволяет <a href="#" onclick="PathDispatcher(\'rules\',0,0);return false">играть</a> и выигрывать<br><br></div>',
		    'Качество загружаемого трека рекомендуется максимально высоким.<br><br>',
		    f_label(Lm.g('File')+':', 'width:5em; margin-left:5em'),
		    f_param(f_file(Lm.g('Browse'),'file'),''),
		    '<br />',
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'upload\',1,\''+param+'\')','width:4em')),
		    '<br /><a class="trule" href="#" onclick="PathDispatcher(\'rules\',2,\'tdiv_1\');return false">Авторам/Правообладателям.</a><br>',
		    '<div class="tdiv" id="tdiv_1">1. Качество звучания (bitrate) загружаемого трека рекомендуется максимальным, чтобы не лишиться права первого на получение половины с продаж.<br /><br />',
		    '2. Звучание загружаемого трека помечено <a href="#" onclick="PathDispatcher(\'upload\',3.21,\'hdiv_1\');return false">Лицензионной маркой</a> для защиты от несанкционированного копирования (Пиратства).',
		    '<div id="hdiv_1" class="hdiv">Лицензионная марка – 4-х секундные позывные наложенные на проигрываемый не из собственного плейлиста Трек.</div>',
		    '</div>'].join('')
	    var _t = (param=='new') ? 'Для продолжения регистрации, загрузите трек в игру!' : Lm.g('Track_upload');
            if (user.id == 0) _t='<span style="color:red">Переход на <a href="#" onclick="PathDispatcher(\'rules\',2,\'tdiv_10\');return false" style="color:red">игровой уровень</a></span><br>'+_t;
	    viewInfo(_t, _s, 0, 'closeW(\'dwindow\');$(\'#ledokol .button_upload\').removeClass(\'button_upload_in_progress\')', 'dwindow', 500)
	    $('#add_track_form input:file').change(function(){ $('#add_track_form input.file').val($(this).val()) })
	    $('#ledokol').find('.button_upload').addClass('button_upload_in_progress')
	    break
	case 1: // progress-bar
	    window.uplfn = $('#add_track_form input:file').val()
	    if (typeof dwindow != 'undefined') dwindow.hide()
	    viewInfo(Lm.g('Track_upload'), '<div id="progress_bar"><div id="progress_line"><!--  --></div></div>', 0, 'PathDispatcher(\'upload\',2,0)','pwindow')
	    helper.s('uplFlag',1); // emulate sync request
	    window.uploadTimer = setInterval( function() {
		if (helper.g('uplFlag')) {
		    helper.s('uplFlag',0)
		    $.getJSON('/progress.php', { f:window.uplfn.replace(/^.*[\/,\\]/, ""), fd:'c'+mr() }, function(j) {
			helper.s('uplFlag',1)
			if (j!=null &&  j.s==1) $('#progress_line').width(Math.floor($('#progress_bar').width()-20)*j.p/100)
		    })
		}
	    }, 5000)
	    $('#add_track_form').ajaxSubmit( {dataType:'json', iframe:true, success:function(j) {
		clearInterval(window.uploadTimer)
		window.uplfn = undefined
		PathDispatcher('upload', 3, j)
	    }})
	    break
	case 2: // cancel upload
	    if (typeof uploadTimer != 'undefined') clearInterval(uploadTimer)
  	    window.uplfn = undefined
	    closeW('pwindow')
	    PathDispatcher('upload', 0, 0)
	    break
	case 3.21: // hide/show license block
	    if ($('#'+param).css('display')=='none') {
		$('.hdiv').hide('normal')
		$('#'+param).show('normal')
	    } else
		$('#'+param).hide('normal')
	    break
	case 3: // add track info
	    closeW('pwindow')
	    if (param.s==1) { // track upload successful
		$.getJSON('/index.php',{page:'presave',f:param.f},function(j) {
		    closeW('twindow');
		    if (j.s==1) {
			if (j.nu==1) {
		    	    if( ledokol.buy_myself == 1 ) { //buy automaticaly without questions in credit
		    		PathDispatcher('buy', 10, {id:j.rt, u_id:j.ru});
		    		ledokol.buy_myself = 0;
		    	    } else
		    		PathDispatcher('buy', 2, j) // track not unique - show buy form
			} else {
			    var c_w='width:9em';
			    var button = f_dbuttons(f_sbutton('OK', (!user.id) ? 'window.addti.hide();PathDispatcher(\'authorize\', 0, \'upload\')' : 'PathDispatcher(\'upload\', 11, 0)', 'width:4em'));
			    if(ledokol.buy_myself == 1)
				button = f_dbuttons(f_sbutton('OK', 'window.addti.hide(); ledokol.buy_myself=0; PathDispatcher(\'register\', 1)', 'width:4em'));
			    var _s=[f_fstart('addtiform', 'index.php', 'post'),
				    f_hidden('page','addtrack'),
				    f_hidden('trackid',j.trackid),
				    f_hidden('is_author', 0),
				    '<input type="checkbox" name="author" style="display:none">',
				    'В случае указания недостоверной информации о треке, затрудняющей выплату авторских вознаграждений, трек или игрок может быть исключён из игры.<br /><br />',
				    f_label(Lm.g('Artist')+':', c_w),
				    f_param(f_input('artist',j.artist,''),''),
				    '<br>',
				    f_label(Lm.g('Title')+':', c_w),
				    f_param(f_input('name',j.name,''),''),
				    '<br>',
				    f_label(Lm.g('Comment')+':', c_w),
				    f_param(f_input('comment','',''),''),
				    '<br>',
				    '<div id="aprice">',
				    f_hidden('price','10'),
				    f_hidden('playlistId','0'),
				    '</div>',
				    '<br>',
				    f_cboth(),
				    f_case(Lm.g('I_am_author'), 'author_check', 'miniradio', ''),
				    '<br>',
				    f_cboth(),
				    button,
				    f_fend()].join('');
			    viewInfo(Lm.g('Track_information'), _s, 0, '', 'addti');
			    $("#author_check").bind('click', function(){
				if ($(this).attr('src') == '/img/radio_w_on.gif'){
				    $(this).attr('src', '/img/radio_w_off.gif');
				    $("input[name='is_author']").val(0)
				    $("#aprice").html(f_hidden('price','10'))
				} else {
				    $(this).attr('src', '/img/radio_w_on.gif');
				    $("input[name='is_author']").val(1);
				    $("#aprice").html([f_label(Lm.g('Price_rub')+':', c_w),f_param(f_input('price','10',''),'')].join(''))
				    PathDispatcher('profile', 3, 0);
				}
				return false

			    })
			}
		    } else if (j.s==2) {
			tempInfo(Lm.g('Track_already_present'), 3, 'i')
		    } else {
			tempInfo('Ошибка загрузки трека, либо несовпадение форматов', 2, 'w')
		    }
	    })
	} else  {
	    viewInfo(Lm.g('Error'), Lm.g('Error_track_upload'), 0);
	    closeW('vwindow')
	}
	break;
    case 4: // cancel add track info
	closeW('addti');
	PathDispatcher('upload', 0, 0)
	break;
    case 5: // submit track info
	if( $("#addtiform input[name='name']").val() == "" && $("#addtiform input[name='artist']").val() == "" ) {
	    tempInfo( 'Укажите пожалуйста исполнителя и название трека', 4 );
	}else
	    $('#addtiform').ajaxSubmit( {dataType:'json', success:function(j) {
		if (j.s == 1) { //если 0 то все ок
		    var s=[Lm.g('Upload_ok')];
		    if (j.smp) s.push('. '+Lm.g('Ledokol_set_minimal_price')+' '+j.p+' '+Lm.g('RUR'));
		    s.push("<br><a href='javascript:void(0)' onclick='javascript:PathDispatcher(\"gimport\", 1, "+j.id+")'>Послать друзьям</a>");
		    var activePlId = $('input[name="playlistId"]').val();
		    closeW('addti');
		    viewInfo(Lm.g('Track_upload'),s.join(''), 20, '', 'tupload');
		    playlist.jinit();
		    page.changePage('playlist', activePlId);
		} else {
			//if(j.s == 0 ) { //если 1 то ещё в simId получаем ссылку на загруженный трек
			closeW('addti');
			viewInfo( 'Ошибка', j.error, 7 );
		    /*ledokol.stopTrack();
		    var _s=[f_fstart('simform', 'index.php', 'post'),
			    '<div id="',
			    j.track,
			    '_t" class="mpllineact"><div class="lname" style="width:100%">',
			    j.name,
			    '</div></div>',
			    f_cboth(),
			    f_dbuttons(f_sbutton('Похож!', "$('#w_addti').remove(); $('#w_tsimilar').remove(); PathDispatcher('buy', 2, {trackid:"+j.track+", rt:"+j.track+", b:"+j.bitrate+", p:'"+j.price+"'})", 'width:8em')+'&nbsp;'+f_sbutton('Не Похож!', 'PathDispatcher(\'upload\', 10, '+j.tmp_track+')', 'width:8em')),
			    '<img src="window/ajax_loader.gif" id="finger_load" style="display:none; padding-left:100px;">',
			    f_fend()].join('')
		    viewInfo( 'Ледокол нашел подобный трек', _s, 0, 'javascript:void(0)', 'tsimilar' )
		    track.path = 'http://ledokol.com/trackbase/mp3/'+j.filename+'.mp3'
		    track.id = j.track
		    ledokol.playsource = 'similar'
		    playlist.bindSlider()
		    ledokol.playTrack()*/
		}
		if( j.s == 0 && j.selftrack == 1 ) {
		    viewInfo("Уникальность трека", "Этот трек уже присутствует у вас в плейлисте.");
		}
	    }});
	//buy track in credit
	if( ledokol.credit_track != 0 ) {

		PathDispatcher('buy', 10, {id:ledokol.credit_track, u_id:ledokol.credit_user});
		ledokol.credit_user = 0;
		ledokol.credit_track = 0;
	}
	break;
    case 6: // cancel buy not unit track
	if (typeof buynuniqt != 'undefined')
	    $.getJSON('index.php', {page:'deltemptrack', id:$('#buynuniqform input[name=track]').val()}, function() { closeW('buynuniqt') });
	tempInfo('Загрузка трека отменена', 2, 'i');
	break;
    case 7: // user select upload track only for your playlist
	if (!user.id) {
	    buynuniqt.hide();
	    PathDispatcher('authorize', 0, 'uplnutrack')
	} else
	    PathDispatcher('upload', 8, 0)
	break;
    case 8: // upload not unique track only for playlist use
	$.getJSON('index.php', {page:'upltrackng', track:$('#buynuniqform input[name=track]').val(), rt:$('#buynuniqform input[name=rt]').val()}, function() { playlist.jinit(); closeW('buynuniqt') });
	break;
    case 10:
	$('#simform button').hide();
	$('#finger_load').show();
	$.getJSON('index.php', {page:'checkfingerprint', tmp_track:param},
		  function(j) {
		      if (!j.s) tempInfo( 'Системная ошибка' );
		      if( j.s==1 ) {
		    	  if( j.u == 1 ) { //трек уникальный
		    	      $.getJSON('index.php', {page:'activateTmpTrack', track:param}, function(j) {
		    		  tempInfo('Трек загружен', 4);
		    		  $('#w_tsimilar').remove();
			    	  $('#w_addti').remove();
		    	      });
		    	  } else {
		    	      PathDispatcher('buy', 2, {trackid:j.t, rt:+j.t, b:j.bitrate, p:j.price});
		    	      $('#w_tsimilar').remove();
		    	      $('#w_addti').remove();
		    	  }
		      }
		  });
	break;

	case 11:

    	$.getJSON('index.php', {page:'getPlsInfo'},
    		function(j) {
    			var singlePl = j.single;
    			if( !j.pl ) {
    				PathDispatcher('pledit',6,{'u_id':param.u_id,'id':param.id,'next':param.next,'name':singlePl});
    				viewInfo('Сообщение', 'Недостаточно места в существующих плейлистах', 2);    				
    				return;
    			}

    			j = j.pl;
    			var s = '<table>';
    			var checkedPl = 0;
    			for(k=0; k<j.length; k++) {
    				var ava = '<div class="rounded" id="ava'+j[k].id+'"><img style="background-color:green; width:100px" src="/avatars/'+(j[k].avatar=="1"?j[k].id:0)+'?'+Math.floor(Math.random()*10000000)+'"></div>';
    				if( typeof j[k].checked != 'undefined' && j[k].checked == 1 ) {

    					$("input[name=playlistId]").val( j[k].id );
    					checkedPl = j[k].id;
    					s += '<tr><td id="name'+j[k].id+'" onmouseout="community.mouseout('+j[k].id+')" onmouseover="community.mouseover('+j[k].id+')">'+f_case(j[k].name, 'pl_'+j[k].id, 'select_playlist miniradio','')+ava+'</td></tr>';
    				} else {
    					//if( j[k].prior - (track.duration)/(60*60*1000) > 0 && (user.account >= 10 || (j[k].type!='single' && j[k].type!='old')) ) {
    					if( j[k].prior - (track.duration)/(60*60*1000) > 0 && j[k].tracksleft >= 0 ) {
    						s += '<tr><td id="name'+j[k].id+'" onmouseout="community.mouseout('+j[k].id+')" onmouseover="community.mouseover('+j[k].id+')">'+f_case(j[k].name, 'pl_'+j[k].id, 'select_playlist miniradio','')+ava+'</td></tr>';
    					} else {
    						s += '<tr><td id="name'+j[k].id+'" onmouseout="community.mouseout('+j[k].id+')" onmouseover="community.mouseover('+j[k].id+')"><font color=gray>'+f_case(j[k].name, 'pl_'+j[k].id, 'select_playlist miniradio','')+'</font>'+ava+'</td></tr>';
    					}
    				}
    			}
    			s += '</table>';
    			if(typeof param.next != 'undefined' ) //buy
    				s += f_dbuttons('<a href="javascript:void(0);" onclick="PathDispatcher(\'pledit\',6,{\'u_id\':'+param.u_id+',\'id\':'+param.id+', \'next\':'+param.next+', \'name\':\''+singlePl+'\'})">'+Lm.g('Add_playlist')+'</a><br><br>'+f_sbutton('Ok', "$('#w_buy_dialog').hide(); PathDispatcher(\'buy\', "+param.next+", {'u_id':"+param.u_id+",'id':"+param.id+"} )", 'width:8em'));
    			else//upload
    				s += f_dbuttons('<a href="javascript:void(0);" onclick="PathDispatcher(\'pledit\',6,\'chosepl\')">'+Lm.g('Add_playlist')+'</a><br><br>'+f_sbutton('Ok', "vwindow.close(); PathDispatcher(\'upload\', 5, 0)", 'width:8em'));
    			s+= f_hidden('playlistId', checkedPl),
    			viewInfo("Добавить трек в плейлист", s );
    			$('.select_playlist').unbind('click');
    			$('.select_playlist').bind('click',
    				function(e){

    					$('.select_playlist').each(
    						function(){this.src='/img/radio_w_off.gif';}
    					);
    					e.target.src = '/img/radio_w_on.gif';
    					$("input[name=playlistId]").val(e.target.id.replace("pl_", ""));
    				}
    			);
    			$('#pl_'+checkedPl).attr('src', '/img/radio_w_on.gif');
    		});
	    break;

	}
	break

    case 'register': // user register
        switch (step) {
	case 0: // get register form, param: "buy" -- register and buy current track, "buy_myself" -- register and upload self track
	    var c_p='width:13em', fld='', title = 'Добро пожаловать!'
	    var buttons = f_dbuttons(f_sbutton('OK', 'PathDispatcher(\'register\', 1, \''+param+'\')', 'width:9em'))
	    if( param == 'buy' || param == 'buy_myself') title = 'Переход на игровой уровень<br/>загрузить свой трек на ледокол'
	    if( param == 'buy_myself' ) {
	    	fld = [f_fstart('add_track_form', 'cgi-bin/upload.cgi', 'post', 'multipart/form-data'),
	    	       f_label('Трек: ', c_p),
		       f_param(f_file(Lm.g('Browse'),'file'),''),
	    	       f_fend()].join('')
	    	title = 'Переход на игровой уровень<br/>загрузить свой трек на ледокол'
	    	ledokol.buy_myself = 1
	    	buttons = f_dbuttons(f_sbutton('OK', '$(\'#w_vwindow\').hide();PathDispatcher(\'upload\', 1)', 'width:9em'))
	    }

	    var _s=[f_fstart('registerform', 'index.php', 'post'),
		    f_hidden('page','register'),
		    f_hidden('action','add'),
		    f_hidden('sex','sex_male'),
		    f_hidden('plname','new playlist'),
		    '<div class="tdiv" id="tdiv_11" style="margin:0 0 10px 0">Игровой уровень - это уровень, который позволяет <a href="#" onclick="PathDispatcher(\'rules\',0,0);return false">играть</a> и выигрывать</div>',
		    '<div style="margin:0 0 10px 0;text-align:center">Регистрация в музыкальной игре Ледокол</div>',
		    f_label('Имя на Ледоколе'+':', c_p),
		    f_param(f_input('nick','',''),''),
		    '<br>',
		    f_label('E-mail'+':', c_p),
		    f_param(f_input('email','',''),''),
		    '<br>',
		    f_label(Lm.g('Password')+':', c_p),
		    f_param(f_password('password','',''),''),
		    '<br>',
		    f_label(Lm.g('Repeat_pass')+':', c_p),
		    f_param(f_password('repeatpass','',''),''),
		    f_fend(),
		    fld,
		    f_label('', c_p),
		    f_param(f_sbutton('OK', 'PathDispatcher(\'register\', 1, \''+param+'\')', 'width:9em'),''),
		    f_cboth(),].join('')
	    viewInfo(title, _s, 0, '', '',450)

	    /*
	    if (param != undefined && param != null && param != '') {
		// reappend class because on close authorise his been removed
		$('#ledokol').find('.button_upload').addClass('button_upload_in_progress');
		window['vwindow'].close = function(){
		    $('#w_vwindow').remove();
		    window['vwindow'].id=null;
		    $('#ledokol').find('.button_upload').removeClass('button_upload_in_progress');
		}
	    }
	    */
	    break;

	case 1: // send register form
	    var c_q='#registerform';
	    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	    if ($(c_q+' input[name=nick]').val().length<1) { tempInfo('Не указано имя', 2, 'w'); return false }
	    if ($(c_q+' input[name=email]').val().length<1) { tempInfo('Не указан email', 2, 'w'); return false }
	    if (!filter.test($(c_q+' input[name=email]').val())) { tempInfo('Укажите корректный email', 2, 'w'); return false }
	    if ($(c_q+' input[name=password]').val()=='') { tempInfo('Не указан пароль', 2, 'w'); return false	}
	    if ($(c_q+' input[name=file]').val()=='') { tempInfo('Не указан трек', 2, 'w'); return false	}
	    if ($(c_q+' input[name=repeatpass]').val()=='') { tempInfo('Повторите пароль', 2, 'w'); return false }
	    if ($(c_q+' input[name=password]').val()!=$(c_q+' input[name=repeatpass]').val()) { tempInfo('Пароли не совпадают', 2, 'w'); return false }
	    if ($(c_q+' input[name=sex]').val()=='') { tempInfo('Укажите пол', 2, 'w'); return false }
	    ledokol.credit_plname = $(c_q+' input[name=plname]').val();
            // TODO: Anton: not correct string!
	    //if ( !(/\w+@\w+\.[a-z]{2,4}/.test($('#'+c_q+' input[name=email]').val()))){ tempInfo('Email не верный', 2, 'w '); return false }
	    $('#registerform').ajaxSubmit( {dataType:'json', success:function(j) {
		if (j.s==1)	{
			PathDispatcher('authorize',2,[$(c_q+' input[name=nick]').val(),$(c_q+' input[name=password]').val()]);
		    if( param == 'buy_myself' ) {
		    	$('#w_vwindow').hide();
		    	var dwindow = $('#w_vwindow');
		    } else
		    	closeW('vwindow');
		} else if (j.s==2) {
		    tempInfo('На Ледоколе уже есть игрок c таким именем', 2, 'w')
		} else if (j.s==3) {
		    tempInfo('На Ледоколе уже есть игрок c таким email', 2, 'w')
		} else {
		    tempInfo('Ошибка регистрации!', 2, 'w')
		}
	    }});
	    break;
	case 2: //select male/female for exists users
	    var _s=[f_fstart('w_dialog_getSex', 'index.php', 'post'),
		    '<div style="text-align:center">',
		    f_hidden('page','setSex'),
		    f_hidden('sex',''),
		    f_dbuttons( f_sbutton(Lm.g('Male'), "PathDispatcher('register', 3, 1)",'width:7em')+ '&nbsp;&nbsp;&nbsp;&nbsp;' +f_button( Lm.g('Female'), "PathDispatcher('register', 3, 0)",'width:7em')),
		    '</div>',
		    f_fend(),
		    f_cboth()].join('');
	    viewInfo('Ваш пол', _s, 0);
	    break;
	case 3:
	    $('#w_dialog_getSex input[name=sex]').val(param);
	    $('#w_dialog_getSex').ajaxSubmit({dataType:'json', success:function(j) { vwindow.close(); }});
	    break;
	case 4:
	    var _s=[f_fstart('regemailform', 'index.php', 'post'),
		    f_hidden('page','regemail'),
		    '<div style="margin:0 0 10px 0">Регистрация в музыкальной игре Ледокол идет по<br> приглашению на прослушивание музыкального трека. <br>Оставьте свой EMAIL и/или ждите приглашения )</div>',
		    f_label('email'+':', 'width:7em'),
		    f_param(f_input('email','','width:200px'),''),
		    '<br>',
		    f_fend(),
		    f_cboth(),
		    f_dbuttons(f_sbutton('ОК', 'PathDispatcher(\'register\', 5, \'\')', 'width:9em'))].join('')
	    viewInfo('Регистрация по приглашению', _s,0,'','vwindow',440);
	    break;
	case 5:
	    $('#regemailform').ajaxSubmit( {dataType:'json', success:function(j) {
		//tempInfo((j.s==1) ? 'Ваш Email принят' : 'Ошибка записи email!', 2, 'i');
		closeW('vwindow')
	    }});
	    break;

	}
	break

    case 'help':
        if( $('#w_'+ param+' .helpMessage').css('display') == 'none') {
	    $('#w_'+ param+' .helpMessage').fadeIn('slow')
	} else
	    $('#w_'+ param+' .helpMessage').fadeOut('slow')
    break

    case 'rules': // game rules
        switch (step) {
	case 0: // get rules
            // 		    '<div class="tdiv" id="tdiv_1">Первый - кто загрузит первым <a href="#" onclick="PathDispatcher(\'rules\',1,\'hdiv_1\');return false">уникальный</a> трек на ледокол предлагает его на первое прослушивание один.',
	    var _s=['<a class="trule" href="#" onclick="PathDispatcher(\'rules\',2,\'tdiv_1\');return false">Первое правило Ледокола: Первый &mdash; один.</a><br />',
		    '<div class="tdiv" id="tdiv_1"><br/><a href="#" onclick="PathDispatcher(\'rules\',1,\'hdiv_2\');return false">Игрок</a> <b>первый</b> загрузивший <a href="#" onclick="PathDispatcher(\'rules\',1,\'hdiv_3\');return false">трек</a> &mdash; <b>один</b>.<br>Каждый трек звучит <b>впервые</b> и <b>один</b> раз<br/>Каждый трек <a href="#" onclick="PathDispatcher(\'rules\',1,\'hdiv_1\');return false">прослушанный</a> <b>впервые</b> добавляет <b>один</b> балл <a href="#" onclick="PathDispatcher(\'rules\',1,\'hdiv_4\');return false">рейтинга</a>.<br/>',
		    '<div class="hdiv" id="hdiv_1"><br/><i>Прослушанный трек</i> &mdash; трек, звучание которого прекратилось без вмешательства плеера.</div>',
		    '<div class="hdiv" id="hdiv_2"><br/><i>Игрок</i> &mdash; авторизованный пользователь.</div>',
		    '<div class="hdiv" id="hdiv_3"><br/><i>Трек (track)</i> &mdash; объект авторского и смежного права в аудио формате.</div>',
		    '<div class="hdiv" id="hdiv_4"><br/><i>Рейтинг</i> &mdash; количество прослушиваний.</div>',
		    '<br/></div>',
		    '<a class="trule" href="#" onclick="PathDispatcher(\'rules\',2,\'tdiv_3\');return false">Второе правило Ледокола: Повтор за деньги.</a><br/>',
		    '<div class="tdiv" id="tdiv_3"><br/>Прослушанные треки <b>повторно</b> не звучат.<br/>Чтобы послушать трек <b>повторно</b>, его необходимо добавить в свой плейлист до начала звучания следующего.<br><br></div>',
		    '<a class="trule" href="#" onclick="PathDispatcher(\'rules\',2,\'tdiv_2\');return false">Третье правило Ледокола: Все пополам</a> <a href="#" onclick="PathDispatcher(\'rules\',1,\'hdiv_5\');return false">*</a><br/>',
		    '<div class="tdiv" id="tdiv_2"><br/>Все деньги полученные в результате игры с треком делятся пополам между игроком и автором (правообладателем).<br/>',
		    '<div class="hdiv" id="hdiv_5"><br/><a href="#" onclick="PathDispatcher(\'rules\',2,\'tdiv_1\');return false">но первый — один</a></div>',
		    '</div>'].join('');
	    viewInfo('Правила игры', _s, 0, '', 'rulwindow', 600)
	    break
	case 1: // hide/show rules
	    if ($('#'+param).css('display')=='none') {
		$('.hdiv').hide('normal')
		$('#'+param).show('normal')
	    } else
		$('#'+param).hide('normal')
	    break;
	case 2: // hide/show top-rules
	    if ($('#'+param).css('display')=='none') {
		$('.tdiv').hide('normal')
		$('#'+param).show('normal')
	    } else
		$('#'+param).hide('normal')
	    break
	}
	break

        case 'comments': // user comment resurce
            switch (step) {
	    case 0: // comment form
		var c_p='width:10em'
		var _s=[f_fstart('commentform', 'index.php', 'post'),
			f_hidden('page','questmail'),
			f_hidden('ledtype',ledtype),
			f_param(f_textarea('text','','','width:280px;height:130px'),''),
		    f_label('E-mail', 'width:75px'),
		    f_param(f_input('email','','width:200px'),''),
			'<br>',
			f_fend(),
			f_cboth(),
			f_dbuttons(f_button('Отправить', 'PathDispatcher(\'comments\', 1, 0)', 'width:7em'))].join('')
		viewInfo('Жалобы и предложения', _s, 0)
		break;
	    case 1: // send form
		$('#commentform').ajaxSubmit({dataType:'json', success:function(j) {
		    if (j.s==1) {
			tempInfo('Сообщение отправлено администратору', 2, 'i');
			$('#commentform textarea').val('')
		    } else
			tempInfo('Ошибка отправки', 2, 'i');
		    closeW('vwindow');
		}});
		break
	    }
    break;

    case 'stopPlay':
        switch( step ) {
	case 0:
	    ledokol.stopTrack();
	    var c_p='width:10em';s=[f_fstart('stopPlayform', 'index.php', 'post')];
	    s.push(f_dbuttons(f_sbutton('Играть', 'PathDispatcher(\'stopPlay\', 1, 0)', 'width:7em')));
	    s.push(f_fend());
	    viewInfo( 'Продолжить играть?', s.join(''), 0 );
	    break;
	case 1://ignore all
	    ledokol.ignore_second = true;
	    ledokol.logicGo();
	    vwindow.close();
	    break;
	}
    break
    }
}

/**
 * Path dispatcher object
 */
pd = { cpath:'',
       param:null,

       convert: function() {

	   var _s=[f_fstart('convertrating', 'index.php', 'post'),
		   f_hidden('page','convertrating'),
		   '<center>',
		   'Вы можете <a  href="#" onclick="PathDispatcher(\'rules\',2,\'hdiv_99\');return false">обменять</a> свой рейтинг на <span id="fcourse">…↻…</span> рублей<br>',
		   'по курсу <span id="icourse">…↻…</span> руб. за 1 балл рейтинга',
		   '<div class="hdiv" id="hdiv_99" style="text-align:left;margin:10px 0 0 0">',
		   '- обнуление рейтинга<br>',
		   '- изменение позиции в топе<br>',
		   '- невозможность обратного обмена: деньги на рейтинг',
		   '</div>',
		   '<div style="margin:10px 0 0 0">',
		   f_sbutton('Обменять', '$(\'#convertrating\').submit()','width:6em; margin:0 5px 0 0'),
		   f_sbutton('Нет', 'convertrate.close()','width:6em'),
		   '</div>',
		   '</center>',
		   f_fend(),
		   f_cboth()].join('')
	   viewInfo('Обменять рейтинг на деньги', _s, 0, '', 'convertrate', 400)

	   $.getJSON('/index.php', {page:'getcourse'}, function(s) { $('#icourse').text(s.course)
								     $('#fcourse').text(Math.round(s.course*user.rating*100)/100)
								   })

	   $('#convertrating').ajaxForm({dataType:'json',
					 success:function(j) {
					     if (j.s==1) {
						 tempInfo('Обмен произошел успешно', 2, 'i')
						 $('#usertitle_rating > span.play').text(0)
						 $('#usertitle_account ').html('MONEY: <span>'+j.summ+'</span>')
					     } else {
						 tempInfo('Обмен не произошел', 2, 'w')
					     }
					     convertrate.close()
					 }})
       },

       register: {

	   /**
	    * Form with select "buy current track" | "upload own track"
	    */
	   preQuest: function() {
	       var _s=[f_fstart('prequestform', 'index.php', 'post'),
		       '<div style="text-align:center">',
		       'Регистрация нового игрока',
		       f_dbuttons(/*f_sbutton('С этим треком', 'prequest.close();pd.register.withBuy()','width:12em') + '&nbsp;&nbsp;&nbsp;' +*/
		    		   f_sbutton('Со своим треком', 'prequest.close();pd.register.withUpload()','width:12em')),
		       '</div>',
		       f_fend(),
		       f_cboth()].join('')
	       viewInfo('Переход на игровой уровень<br/>загрузить свой трек на ледокол', _s, 0, '', 'prequest', 400)
	   },

	   /**
	    * Register/authorize with buy track
	    */
	   withBuy: function() {
	       var c_p='width:13em'

	       link_is_played = {}
	       if ($.cookie("link_is_played") != null && $.cookie("link_is_played")) {
		   eval ('__lip = ' + $.cookie("link_is_played"))
		   link_is_played.user = __lip.user
		   link_is_played.track = __lip.track
		   track.u_id = link_is_played.user
                   track.id = link_is_played.track
	       } else {
		   link_is_played.user = 0;
		   //$.cookie('the_cookie', null);
	       }

	       var _s=[(link_is_played.user) ? '<div style="margin:0 0 10px 0;text-align:center">ДЛЯ ТОГО ЧТОБЫ ПРОСЛУШАТЬ ЭТОТ ТРЕК ЕЩЕ РАЗ, НУЖНО ДОБАВИТЬ ЕГО В СВОЙ ПЛЕЙЛИСТ</div>' : '<div style="margin:0 0 10px 0;text-align:center">ДОБАВИТЬ <b>ЗВУЧАЩИЙ</b> ТРЕК В СВОЙ ПЛЕЙЛИСТ</div>',
		       '<div id="f1" style="display:none"><form id="dialog_authForm" action="index.php" method="post">',
		       f_hidden('page','authorize'),
		       '<div class="tdiv" id="tdiv_11" style="margin:0 0 10px 0">Игровой уровень - это уровень, который позволяет <a href="#" onclick="PathDispatcher(\'rules\',0,0);return false">играть</a> и выигрывать</div>',
		       '<div style="margin:0 0 10px 0;text-align:center">Авторизация<br>',
		       '<a href="#" onclick="$(\'#f1\').hide();$(\'#f2\').show();return false">Зарегистрироваться</a></div>',
		       f_label('Имя на Ледоколе:', c_p),
		       f_param(f_input('nick','',''),''),
		       '<br>',
		       f_label(Lm.g('Password')+':', c_p),
		       f_param(f_password('pass','',''),''),
		       '<br>',
		       f_label('', c_p),
		       f_param(f_sbutton('OK', "PathDispatcher('authorize',1,'doBuy'); uplwin.close();", 'width:4em') ,''),
		       f_fend(),
		       f_cboth(),
		       '</div>',
		       '<div id="f2"><form id="registerform" action="index.php" method="post">',
		       f_hidden('page','register'),
		       f_hidden('action','add'),
		       f_hidden('sex','sex_male'),
		       f_hidden('plname','new playlist'),
		       '<div class="tdiv" id="tdiv_11" style="margin:0 0 10px 0">Игровой уровень - это уровень, который позволяет <a href="#" onclick="PathDispatcher(\'rules\',0,0);return false">играть</a> и выигрывать</div>',
		       '<div style="margin:0 0 10px 0;text-align:center">Регистрация<br>',
		       '<a href="#" onclick="$(\'#f2\').hide();$(\'#f1\').show();return false">Уже регистировались?</a></div>',
		       f_label('Имя на Ледоколе:', c_p),
		       f_param(f_input('nick','',''),''),
		       '<br>',
		       f_label('E-mail'+':', c_p),
		       f_param(f_input('email','',''),''),
		       '<br>',
		       f_label(Lm.g('Password')+':', c_p),
		       f_param(f_password('password','',''),''),
		       '<br>',
		       f_label(Lm.g('Repeat_pass')+':', c_p),
		       f_param(f_password('repeatpass','',''),''),
		       f_label('', c_p),
		       f_param(f_submitbutton('OK', 'width:4em') ,''),
		       f_fend(),
		       f_cboth(),
		       '</div>'].join('')
	       viewInfo('Переход на игровой уровень', _s, 0, '', 'uplwin',450)

	       $('#registerform').ajaxForm({dataType:'json',
					    beforeSubmit: function() {
						var c_q='#registerform'
						var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
						if ($(c_q+' input[name=nick]').val().length<1) {
						    tempInfo('Не указано имя', 2, 'w')
						    return false
						}
						if ($(c_q+' input[name=email]').val().length<1) {
						    tempInfo('Не указан email', 2, 'w')
						    return false
						}
						if (!filter.test($(c_q+' input[name=email]').val())) {
						    tempInfo('Укажите корректный email', 2, 'w')
						    return false
						}
						if ($(c_q+' input[name=password]').val()=='') {
						    tempInfo('Не указан пароль', 2, 'w')
						    return false
						}
						if ($(c_q+' input[name=file]').val()=='') {
						    tempInfo('Не указан трек', 2, 'w')
						    return false
						}
						if ($(c_q+' input[name=repeatpass]').val()=='') {
						    tempInfo('Повторите пароль', 2, 'w')
						    return false
						}
						if ($(c_q+' input[name=password]').val()!=$(c_q+' input[name=repeatpass]').val()) {
						    tempInfo('Пароли не совпадают', 2, 'w')
						    return false
						}
						if ($(c_q+' input[name=sex]').val()=='') {
						    tempInfo('Укажите пол', 2, 'w')
						    return false
						}
						//uplwin.hide()
					    },
					    success:function(j) {
						if (j.s==1) {
							uplwin.hide()
          					ledokol.playtype='rand'
						    user.id = -1 // force init
						    user.load()
						    ledokol.logicTop()
						    ledokol.unmute()
						    ledokol.setAuth()
						    ledokol.setMaxi()
				    		    $('#usertitle').attr('class', 'auth')
						    $.getJSON('/index.php',
							      {page:'AJAX_byeTrack',
							       userid:track.u_id,
							       trackid:track.id,
							       plname:'new playlist',
							       credit:1},
							      function(s) {
								  if (s.s != 1) {
								      var _m = "Ошибка покупки в кредит"
								  } else {
								      var _m = [s.m,
										"<br><a href='javascript:void(0)' onclick='PathDispatcher(\"gimport\", 1, ",
										s.id,
										")'>Послать друзьям</a>"].join('')
								      playlist.jinit()
								      page.changePage('playlist')
								  }
								  viewInfo(Lm.g('Message'), _m, 0)
							      })
						} else if (j.s==2) {
						    tempInfo('На Ледоколе уже есть игрок c таким именем', 2, 'w')
						    //uplwin.hide()
						} else if (j.s==3) {
						    tempInfo('На Ледоколе уже есть игрок c таким email', 2, 'w')
						    //uplwin.hide()
						} else {
						    tempInfo('Ошибка регистрации!', 2, 'w')
						    uplwin.hide()
						}
					    }})

	   },

	   /**
	    * Register with upload own track
	    */
	   withUpload: function() {
	       var c_p='width:13em'
	       var _s=['<div style="margin:0 0 10px 0;text-align:center">ЗАГРУЗИТЬ ТРЕК НА ЛЕДОКОЛ</div>',
		       '<div id="f1" style="display:none">',
		       '<form id="dialog_authForm" action="index.php" method="post">',
		       f_hidden('page','authorize'),
		       '<div class="tdiv" id="tdiv_11" style="margin:0 0 10px 0">Игровой уровень - это уровень, который позволяет <a href="#" onclick="PathDispatcher(\'rules\',0,0);return false">играть</a> и выигрывать</div>',
		       '<div style="margin:0 0 10px 0;text-align:center">Авторизация<br>',
		       '<a href="#" onclick="$(\'#f1\').hide();$(\'#f2\').show();return false">Зарегистрироваться</a></div>',
		       f_label('Имя на Ледоколе:', c_p),
		       f_param(f_input('nick','',''),''),
		       '<br>',
		       f_label(Lm.g('Password')+':', c_p),
		       f_param(f_password('pass','',''),''),
		       '<br>',
		       f_fend(),
		       f_cboth(),
		       '<hr size="3" style="background: none repeat scroll 0% 0% black; margin-right:-20px;">',
    		       '<center>Качество звучания загружаемого трека рекомендуется<br> максимальным, чтобы не лишиться права первого<br>на получение половины с продаж.</center><br>',
		       f_fstart('add_track_form_2', 'cgi-bin/upload.cgi', 'post', 'multipart/form-data'),
    		       f_label('Трек: ', c_p),
    		       f_param(f_file(Lm.g('Browse'),'file'),''),
    		       f_fend(),
		       f_label('', c_p),
		       f_param(f_sbutton('OK', "PathDispatcher('authorize',1,'doUpload')", 'width:9em; margin-top: 10px;'),''),
		       f_cboth(),
		       '</div>',
	               '<div id="f2">',
	               '<form id="registerform" action="index.php" method="post">',
		       f_hidden('page','register'),
		       f_hidden('action','add'),
		       f_hidden('sex','sex_male'),
		       f_hidden('plname','new playlist'),
		       '<div class="tdiv" id="tdiv_11" style="margin:0 0 10px 0">Игровой уровень - это уровень, который позволяет <a href="#" onclick="PathDispatcher(\'rules\',0,0);return false">играть</a> и выигрывать</div>',
		       '<div style="margin:0 0 10px 0;text-align:center">Регистрация<br>',
		       '<a href="#" onclick="$(\'#f2\').hide();$(\'#f1\').show();return false">Уже регистировались?</a></div>',
		       f_label('Имя на Ледоколе:', c_p),
		       f_param(f_input('nick','',''),''),
		       '<br>',
		       f_label('E-mail:', c_p),
		       f_param(f_input('email','',''),''),
		       '<br>',
		       f_label(Lm.g('Password')+':', c_p),
		       f_param(f_password('password','',''),''),
		       '<br>',
		       f_label(Lm.g('Repeat_pass')+':', c_p),
		       f_param(f_password('repeatpass','',''),''),
		       f_fend(),
		       f_cboth(),
		       '<hr size="3" style="background: none repeat scroll 0% 0% black; margin-right:-20px;">',
    		       '<center>Качество звучания загружаемого трека рекомендуется<br> максимальным, чтобы не лишиться права первого<br>на получение половины с продаж.</center><br>',
		       f_fstart('add_track_form', 'cgi-bin/upload.cgi', 'post', 'multipart/form-data'),
	    	       f_label('Трек: ', c_p),
		       f_param(f_file(Lm.g('Browse'),'file'),''),
	    	       f_fend(),
		       f_label('', c_p),
		       f_param(f_sbutton('OK', '$(\'#add_track_form\').submit()', 'width:9em; margin-top: 10px;'),''),
		       f_cboth(),
		       '</div>',
		       '<a class="trule" href="#" onclick="PathDispatcher(\'rules\',2,\'tdiv_1\');return false">Авторам/Правообладателям.</a><br>',
		       '<div class="tdiv" id="tdiv_1">1. Качество звучания (bitrate) загружаемого трека рекомендуется максимальным,<br> чтобы не лишиться права первого<br>на получение половины с продаж.<br /><br />',
		       '2. Звучание загружаемого трека помечено <a href="#" onclick="PathDispatcher(\'upload\',3.21,\'hdiv_1\');return false">Лицензионной маркой</a><br> для защиты от несанкционированного копирования (Пиратства).',
		       '<div id="hdiv_1" class="hdiv">Лицензионная марка – 4-х секундные позывные наложенные на<br> проигрываемый не из собственного плейлиста Трек.</div>',
		       '</div>'].join('')
	       viewInfo('Переход на игровой уровень', _s, 0, '', 'uplwin',450)


	       $('#registerform').ajaxForm({dataType:'json',
					    beforeSubmit: function() {
	    	   			//проверка перенесана в #add_track_form.beforeSubmit
						uplwin.hide()
					    },
					    success:function(j) {
						if (j.s==1) {
          					    ledokol.playtype='rand'
						    user.id = -1 // force init
						    user.load()
						    ledokol.logicTop()
						    ledokol.unmute()
						    ledokol.setMaxi()
						    ledokol.setAuth()
				    		    $('#usertitle').attr('class', 'auth')
						    $('#add_track_form').submit()
						} else if (j.s==2) {
						    tempInfo('На Ледоколе уже есть игрок c таким именем', 2, 'w')
						    uplwin.show()
						} else if (j.s==3) {
						    tempInfo('На Ледоколе уже есть игрок c таким email', 2, 'w')
						    uplwin.show()
						} else {
						    tempInfo('Ошибка регистрации игрока!', 2, 'w')
						    uplwin.show()
						}
					    }})

			$('#add_track_form_2').ajaxForm({dataType:'json',
				iframe:true,
				beforeSubmit: function() {
				  window.uplfn = $('#add_track_form_2 input:file').val().replace(/^.*[\/,\\]/, "")
				  uplwin.hide()
				  viewInfo(Lm.g('Track_upload'),
					   '<div id="progress_bar"><div id="progress_line"><!--  --></div></div>',
					   0,
					   'clearInterval(uploadTimer);  window.uplfn=undefined; progresswindow.close(); pd.register.withUpload()',
					   'progresswindow')
				  window.uploadTimer = setInterval( function() {
					  $.getJSON('/progress.php', { f:window.uplfn, fd:'c'+mr() }, function(j) {
					  if (j!=null &&  j.s==1)
					      $('#progress_line').width(Math.floor($('#progress_bar').width()-20)*j.p/100)
				      })
				  }, 5000)
				  $('#ledokol').find('.button_upload').addClass('button_upload_in_progress')
				},
		      success:function(j) {
					  clearInterval(window.uploadTimer)
					  uplwin.hide()
					  if (j.s==1) { // track upload successful
					      $.getJSON('/index.php',
							{page:'presave',f:j.f},
							function(p) { progresswindow.close()
								      if (p.s==1) {
									  if (p.nu==1) {
									      $.getJSON('/index.php',
											{page:'AJAX_byeTrack',
											 userid:p.ru,
											 trackid:p.rt,
											 plname:'new playlist',
											 credit:1},
											function(s) {
											    if (s.s != 1) {
												var _m = "Ошибка покупки в кредит"
											    } else {
												var _m = [s.m,
													  "<br><a href='javascript:void(0)' onclick='PathDispatcher(\"gimport\", 1, ",
													  j.id,
													  ")'>Послать друзьям</a>"].join('')
												playlist.jinit()
												page.changePage('playlist')
											    }
											    viewInfo(Lm.g('Message'), _m, 0)
											})
									  } else {
									      p.action='register.withUpload';
									      pd.upload.addTrackInfo(p)
									  }
								      } else if (j.s==2) {
									  tempInfo(Lm.g('Track_already_present'), 3, 'i')
								      } else {
									  tempInfo('Ошибка обработки трека', 3, 'w')
								      }
								    }
						       )
					  } else {
					      tempInfo(Lm.g('Error_track_upload'), 3, 'w')
					  }
	  				  $('#ledokol').find('.button_upload').removeClass('button_upload_in_progress')
				  }
			})
	       $('#add_track_form').ajaxForm({dataType:'json',
					      iframe:true,
					      beforeSubmit: function() {
	    	   				if( user.id != 0 )
	    	   					return false
							var c_q='#registerform'
							var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
							var isValid = true;
							if ($(c_q+' input[name=nick]').val().length<1) {
							    tempInfo('Не указано имя', 2, 'w')
							    return false
							}
								$.ajax({ async:false,
									 dataType:'json',
									 url:'/index.php?page=checkNick&nick='+$(c_q+' input[name=nick]').val(),
									 success: function(j) {
										if( j.s == "1" ) {
											tempInfo('Игрок с таким именем уже существует', 2, 'w');
											isValid = false;
											return false;
										}
									 }
								})
							if( !isValid )
								return false;
							if ($(c_q+' input[name=email]').val().length<1) {
							    tempInfo('Не указан email', 2, 'w')
							    return false
							}
							if (!filter.test($(c_q+' input[name=email]').val())) {
							    tempInfo('Укажите корректный email', 2, 'w')
							    return false
							}

							$.ajax({ async:false,
								 dataType:'json',
								 url:'/index.php?page=checkEmail&email='+$(c_q+' input[name=email]').val(),
								 success: function(j) {
									if( j.s == "1" ) {
										tempInfo('Игрок с таким адресом уже существует', 2, 'w');
										isValid = false;
										return false;
									}
								 }
							})
							if( !isValid )
								return false;
							if ($(c_q+' input[name=password]').val()=='') {
							    tempInfo('Не указан пароль', 2, 'w')
							    return false
							}
							if ($(c_q+' input[name=file]').val()=='') {
							    tempInfo('Не указан трек', 2, 'w')
							    return false
							}
							if ($(c_q+' input[name=repeatpass]').val()=='') {
							    tempInfo('Повторите пароль', 2, 'w')
							    return false
							}
							if ($(c_q+' input[name=password]').val()!=$(c_q+' input[name=repeatpass]').val()) {
							    tempInfo('Пароли не совпадают', 2, 'w')
							    return false
							}
							if ($(c_q+' input[name=sex]').val()=='') {
							    tempInfo('Укажите пол', 2, 'w')
							    return false
							}
							if ($('#add_track_form input:file').val() =='') {
							    tempInfo('Выберите звуковой файл', 2, 'w')
							    return false
							}


						  window.uplfn = $('#add_track_form input:file').val().replace(/^.*[\/,\\]/, "")
						  uplwin.hide()
						  viewInfo(Lm.g('Track_upload'),
							   '<div id="progress_bar"><div id="progress_line"><!--  --></div></div>',
							   0,
							   'clearInterval(uploadTimer);  window.uplfn=undefined; progresswindow.close(); pd.register.withUpload()',
							   'progresswindow')
						  window.uploadTimer = setInterval( function() {
							  $.getJSON('/progress.php', { f:window.uplfn, fd:'c'+mr() }, function(j) {
							  if (j!=null &&  j.s==1)
							      $('#progress_line').width(Math.floor($('#progress_bar').width()-20)*j.p/100)
						      })
						  }, 5000)
						  $('#ledokol').find('.button_upload').addClass('button_upload_in_progress')
					      },
					      success:function(j) {
						  clearInterval(window.uploadTimer)
						  uplwin.hide()
						  if (j.s==1) { // track upload successful
							  $('#registerform').submit(),
						      $.getJSON('/index.php',
								{page:'presave',f:j.f},
								function(p) { progresswindow.close()
									      if (p.s==1) {
										  if (p.nu==1) {
										      $.getJSON('/index.php',
												{page:'AJAX_byeTrack',
												 userid:p.ru,
												 trackid:p.rt,
												 plname:'new playlist',
												 credit:1},
												function(s) {
												    if (s.s != 1) {
													var _m = "Ошибка покупки в кредит"
												    } else {
													var _m = [s.m,
														  "<br><a href='javascript:void(0)' onclick='PathDispatcher(\"gimport\", 1, ",
														  j.id,
														  ")'>Послать друзьям</a>"].join('')
													playlist.jinit()
													page.changePage('playlist')
												    }
												    viewInfo(Lm.g('Message'), _m, 0)
												})
										  } else {
										      p.action='register.withUpload';
										      pd.upload.addTrackInfo(p)
										  }
									      } else if (j.s==2) {
										  tempInfo(Lm.g('Track_already_present'), 3, 'i')
									      } else {
										  tempInfo('Ошибка обработки трека', 3, 'w')
									      }
									    }
							       )
						  } else {
						      tempInfo(Lm.g('Error_track_upload'), 3, 'w')
						  }
		  				  $('#ledokol').find('.button_upload').removeClass('button_upload_in_progress')
					      }})
	   }

       },

       upload: {

	   /**
	    * Upload form for registered user
	    */
	   trackUpload: function() {

    	       var _s=['<form id="add_track_form" action="cgi-bin/upload.cgi" method="post" enctype="multipart/form-data">',
    		       '<div class="tdiv" id="tdiv_10">Игровой уровень - это уровень, который позволяет <a href="#" onclick="PathDispatcher(\'rules\',0,0);return false">играть</a> и выигрывать<br><br></div>',
                   '<center>Качество звучания загружаемого трека рекомендуется <a href="#" onclick="PathDispatcher(\'upload\',3.21,\'hdiv_2\');return false">максимальным</a>, чтобы не лишиться <a href="#" onclick="PathDispatcher(\'upload\',3.21,\'hdiv_3\');return false">права первого</a> на получение половины с продаж.</center><br>',
                   '<div id="hdiv_2" class="hdiv">Любой трек может быть заменён в случае введения в игру трека с более высоким качеством с последующим извещением Вас об этом.</div>',
                   '<div id="hdiv_3" class="hdiv">Первый поместивший трек в свой плейлист получает половину со всех продаж трека.</div><br>',
    		       f_label(Lm.g('File')+':', 'width:5em; margin-left:5em'),
    		       f_param(f_file(Lm.g('Browse'),'file'),''),
    		       '<br>',
    		       f_cboth(),
    		       f_dbuttons(f_submitbutton('OK', 'width:4em')),
    		       f_fend(),
    		       '<br><a class="trule" href="#" onclick="PathDispatcher(\'rules\',2,\'tdiv_1\');return false">Авторам/Правообладателям.</a><br>',
    		       '<div class="tdiv" id="tdiv_1">',
    		       'Звучание загружаемого трека помечено <a href="#" onclick="PathDispatcher(\'upload\',3.21,\'hdiv_1\');return false">Лицензионной маркой</a> для защиты от несанкционированного копирования (Пиратства).',
    		       '<div id="hdiv_1" class="hdiv">Лицензионная марка – 4-х секундные позывные наложенные на трек.</div>',
    		       '</div>'].join('')
    	       viewInfo(Lm.g('Track_upload'), _s, 0, 'uplformwindow.close(); $(\'#ledokol .button_upload\').removeClass(\'button_upload_in_progress\')', 'uplformwindow', 500)
    	       $('#add_track_form').ajaxForm({dataType:'json',
    					      iframe:true,
    					      beforeSubmit: function() {
    						  if (!$('#add_track_form input:file').val().length) {
    						      tempInfo('Выберите звуковой файл', 2, 'w')
    						      return false
    						  }
    						  window.uplfn = $('#add_track_form input:file').val().replace(/^.*[\/,\\]/, "")
    						  uplformwindow.hide()
    						  viewInfo(Lm.g('Track_upload'),
    							   '<div id="progress_bar"><div id="progress_line"><!--  --></div></div>',
    							   0,
    							   'clearInterval(uploadTimer); window.uplfn=undefined; closeW(\'progresswindow\'); pd.upload.trackUpload()',
    							   'progresswindow')
    						  window.uploadTimer = setInterval( function() {
    						      $.getJSON('/progress.php', { f:window.uplfn, fd:'c'+mr() }, function(j) {
    							  if (j!=null && j.s==1)
    							      $('#progress_line').width(Math.floor($('#progress_bar').width()-20)*j.p/100)
    						      })
    						  }, 5000)
    						  $('#ledokol .button_upload').addClass('button_upload_in_progress')
    					      },
    					      success:function(j) {
    						  clearInterval(window.uploadTimer)
    						  uplformwindow.close()
    						  if (j.s==1) { // track upload successful
    						      $.getJSON('/index.php',{page:'presave',f:j.f}, function(s) {
    							  closeW('progresswindow')
    							  if (s.s==1) {
    							      if (s.nu==1) {
    				    				  PathDispatcher('buy', 2, s) // track not unique - show buy form
    							      } else {
    								  pd.upload.addTrackInfo(s)
    							      }
    							  } else if (s.s==2) {
    							      tempInfo(Lm.g('Track_already_present'), 3, 'i')
    							  } else if (s.s==3) {
    							      var _s=['<form id="replace_track_form" action="index.php" method="post">',
    								      f_hidden('page','replacetrack'),
    								      f_hidden('trackid',s.rt),
    								      f_hidden('filename',s.cf),
    								      'Загруженный трек лучшего качества, ',
    								      'чем имеющийся в вашем плейлисте.<br>',
    								      'Заменить?',
    								      f_cboth(),
    								      f_dbuttons([f_sbutton('Да', '$(\'#replace_track_form\').submit()', 'width:4em'),
    										  '&nbsp;&nbsp;&nbsp;&nbsp;',
    										  f_button('Нет', 'replacetrmwindow.close()', 'width:4em')].join('')),
    								      f_fend()].join('')
    							      viewInfo('Замена трека', _s, 0, 'replacetrmwindow.close()', 'replacetrmwindow', 500)
    							      $('#replace_track_form').ajaxForm({dataType:'json',
    												 beforeSubmit: function() {
    												     replacetrmwindow.hide()
    												 },
    												 success: function() {
    												     replacetrmwindow.close()
    												     tempInfo('Трек заменен', 3, 'i')
    		 										 }
    												})
    							  } else {
    							      tempInfo('Ошибка обработки трека', 3, 'w')
    							  }
    						      })
    						  } else {
    						      tempInfo(Lm.g('Error_track_upload'), 3, 'w')
    						  }
    				  		  $('#ledokol .button_upload').removeClass('button_upload_in_progress')
    					      }})
    	       $('#add_track_form input:file').change(function() {
    		   $('#add_track_form input.file').val($(this).val())
	       })

	   },

	   addTrackInfo: function(param) {
	       var c_w='width:9em';
	       var _s=[f_fstart('addtiform', 'index.php', 'post'),
		       f_hidden('page','addtrack'),
		       f_hidden('trackid',param.trackid),
		       f_hidden('is_author', 0),
		       '<input type="checkbox" name="author" style="display:none">',
		       'В случае указания недостоверной информации о треке, затрудняющей выплату авторских вознаграждений, трек или игрок может быть исключён из игры.<br /><br />',
		       f_label(Lm.g('Artist')+':', c_w),
		       f_param(f_input('artist',param.artist,''),''),
		       '<br>',
		       f_label(Lm.g('Title')+':', c_w),
		       f_param(f_input('name',param.name,''),''),
		       '<br>',
		       f_label(Lm.g('Comment')+':', c_w),
		       f_param(f_input('comment','',''),''),
		       '<br>',
		       '<div id="aprice">',
		       f_hidden('price','10'),
		       f_hidden('playlistId','0'),
		       '</div>',
		       '<br>',
		       f_cboth(),
		       f_case(Lm.g('I_am_author'), 'author_check', 'miniradio', ''),
		       '<br>',
		       f_cboth(),
		       //f_dbuttons(f_sbutton('OK', '$(\'#addtiform\').submit()', 'width:4em')),
		       f_dbuttons(f_sbutton('OK', 'pd.upload.selectPlaylist()', 'width:4em')),
		       f_fend()].join('');

	       viewInfo(Lm.g('Track_information'), _s, 0, '', 'addti');

	       $("#author_check")
		   .bind('click', function() {
		       if ($(this).attr('src') == '/img/radio_w_on.gif'){
			   $(this).attr('src', '/img/radio_w_off.gif');
			   $("input[name='is_author']").val(0)
			   $("#aprice").html(f_hidden('price','10'))
		       } else {
			   $(this).attr('src', '/img/radio_w_on.gif');
			   $("input[name='is_author']").val(1);
			   $("#aprice").html([f_label(Lm.g('Price_rub')+':', c_w),f_param(f_input('price','10',''),'')].join(''))
			   PathDispatcher('profile', 3, 0);
		       }
		       return false
	       })

	       $('#addtiform').ajaxForm({dataType:'json',
					 beforeSubmit: function() {
					     if ($("#addtiform input[name='name']").val() == "" || $("#addtiform input[name='artist']").val() == "") {
						 tempInfo('Укажите пожалуйста исполнителя и название трека', 4)
						 return false
					     }
					 },
					 success:function(j) {
					     if (j.s) {
							 var _s=[Lm.g('Upload_ok')]
							 if (j.smp) _s.push('. '+Lm.g('Ledokol_set_minimal_price')+' '+j.p+' '+Lm.g('RUR'))
							 _s.push("<br><a href='javascript:void(0)' onclick='javascript:PathDispatcher(\"gimport\", 1, "+j.id+")'>Послать друзьям</a>")
							 var activePlId = $('input[name="playlistId"]').val()
							 addti.close()
							 viewInfo(Lm.g('Track_upload'),_s.join(''), 20)
							 playlist.jinit()
							 page.changePage('playlist')
					     } else {
					    	 addti.close();
					    	 viewInfo('Ошибка', j.error);
					     }
					 }})

	   },

	   compareTracks: function(param) {
	       var _s=[f_fstart('simform', 'index.php', 'post'),
		       '<div id="',
		       j.track,
		       '_t" class="mpllineact"><div class="lname" style="width:100%">',
		       j.name,
		       '</div></div>',
		       f_cboth(),
		       f_dbuttons(f_sbutton('Похож!', "$('#w_addti').remove(); $('#w_tsimilar').remove(); PathDispatcher('buy', 2, {trackid:"+j.track+", rt:"+j.track+", b:"+j.bitrate+", p:'"+j.price+"'})", 'width:8em')+'&nbsp;'+f_sbutton('Не Похож!', 'PathDispatcher(\'upload\', 10, '+j.tmp_track+')', 'width:8em')),
		       '<img src="window/ajax_loader.gif" id="finger_load" style="display:none; padding-left:100px;">',
		       f_fend()].join('')
	       viewInfo( 'Ледокол нашел подобный трек', _s, 0, 'javascript:void(0)', 'tsimilar' )
	       track.path = 'http://ledokol.com/trackbase/mp3/'+j.filename+'.mp3'
	       track.id = j.track
	       ledokol.playsource = 'similar'
	       playlist.bindSlider()
	       ledokol.playTrack()
	   },


	   selectPlaylist: function(param) {

		   var isError = false;
		   if( $('#w_addti input[name="artist"]').val() == "" ) {
			   isError = true;
			   tempInfo('Необходимо указать автора.',2,'w');
		   }
		   if( $('#w_addti input[name="name"]').val() == "" ) {
			   isError = true;
			   tempInfo('Необходимо указать название трека.',2,'w');
		   }		   
		   if(isError)
			   return;
		   $('#w_addti').hide();
		   PathDispatcher('upload', 11, 0);
	   },

	   addPlaylist: function(param) {
	       var c_w='width:7em'
	       var _s=[f_fstart('newplistform', 'index.php', 'post'),
		       f_hidden('page', 'new_playlist'),
		       f_hidden('pl_type', ''),
		       f_label(Lm.g('Title')+':', c_w)+f_param(f_input('name',(param.name!='undefined' ? param.name: '' ),''),''),
		       f_cboth(),
		       f_case('Album (20 треков или 1 час), стоимость 200р','pl_type_album', 'pl_type miniradio',''),
		       f_cboth(),
		       f_case('Set (100 треков или 6 часов), стоимость 1000р','pl_type_set', 'pl_type miniradio',''),
		       f_cboth(),
		       f_case('Radio (200 треков или 12 часов), стоимость 2000р','pl_type_radio', 'pl_type miniradio',''),
		       f_cboth(),
		       f_fend(),
		       f_dbuttons(f_sbutton('OK', '$(\'newplistform\').submit()','margin:0 0 0 0.5em;width:4em'))].join('')
	       viewInfo(Lm.g('Add_playlist'), _s, 0, '', 'plwindow', 400);
	       $('.pl_type')
		   .unbind('click')
		   .bind('click', function(e) {
		       $('.pl_type').each(function() { this.src='/img/radio_w_off.gif' } )
			   e.target.src = '/img/radio_w_on.gif'
		       $("input[name=pl_type]").val(e.target.id.replace("pl_type_", ""));
		   }
		)
	       $('#newplistform').ajaxForm({dataType:'json',
					    iframe:true,
					    beforeSubmit: function() {
						if ($('#w_plwindow input[name=name]').val()=='') {
						    tempInfo('Необходимо ввести название!',2,'w')
						    return false
						}
					    },
					    success:function(j) {
	    					$('input[name="playlistId"]').val(j.playlist_id);
	    					$('#w_buy_dialog').hide();
	    					PathDispatcher('buy', param.next, {'u_id':param.u_id,'id':param.id} );
	    					closeW('plwindow')
					    }})

	   }
      },

       playtype: {

	   setNew: function() {
	       if (ledokol.playtype != 'rate' || ledokol.rate_type != 'new' || ledokol.rate_period != 'new')
		   ledokol.playClick()
	       ledokol.playtype = 'rate'
	       ledokol.rate_type = 'new'
	       ledokol.rate_period = 'new'
	       ledokol.setNew()
	       usertop.load({page:'jtop',playtype:'rate',rate_type:'new',rate_period:'new',rate_author:ledokol.rate_author,ac:mr()})
	   },

	   setRandom: function() {
	       if (ledokol.playtype != 'rand')
		   ledokol.playClick()
	       ledokol.playtype = 'rand'
	       ledokol.setRandom()
	       usertop.load({page:'jtop',playtype:'rand',ac:mr()})
	   },

	   setPop: function() {
	       if (ledokol.playtype != 'rate' || ledokol.rate_type != 'pop' || ledokol.rate_period != 'all')
		   ledokol.playClick()
	       ledokol.playtype = 'rate'
	       ledokol.rate_type = 'pop'
	       ledokol.rate_period = 'all'
	       ledokol.setPop()
	       usertop.load({page:'jtop',playtype:'rate',rate_type:'pop',rate_period:'all',rate_author:ledokol.rate_author,ac:mr()})
	   }
       }
     }


/**
 * User object
 */
user = { id:0,
	 lang: 'rus',
	 clear: function() {
	     this.init({'id':0, 'name':'', 'email':'', 'author':0, 'passport':'', 'rating':0, 'sales':0, 'avatar':0, 'account':0, 'messages_all':0, 'messages_new':0 })
	 },
	 init: function(p) {
	     this.id = p.id // идентификатор игрока
	     this.name = p.nick // имя игрока
	     this.email = p.email // email
	     this.author = p.author // признак автора
	     this.passport = p.passport // паспортные данные
	     this.passport_ser = p.passport_ser // паспортные данные
	     this.passport_num = p.passport_num // паспортные данные
	     this.passport_date = p.passport_date // паспортные данные
	     this.passport_org = p.passport_org // паспортные данные
	     this.rating = p.rating // рейтинг
	     this.sales =  p.sales // количество продаж
	     this.avatar = p.avatar // признак наличия аватары
	     this.account = p.account // сумма на игровом счете
	     this.messages_all = p.messages_all // общее количество сообщений
	     this.messages_new = p.messages_new // количество непрочитанных сообщений
	     this.sex = p.sex //пол
	     this.fio1=p.fio1
	     this.fio2=p.fio2
	     this.fio3=p.fio3
	     this.vk_url=p.vk_url
	     this.skype=p.skype
	     this.promodj=p.promodj
	     this.facebook=p.facebook
	     this.last_not_send_track = p.last_not_send_track // последний трек по которому не было предложений разослать друзьям
	     if (typeof p.c2 != 'undefined') {
		 this.c2all=p.c2[0] //community all users
		 this.c2o=p.c2[1] //community online only

	     }
	     this.display()
	 },
	 load: function() {
	     $.ajax({ async:false,
		      dataType:'json',
		      url:'/index.php?page=juserinfo&ac='+mr(),
		      success: function(j) {
			  if ($('#w_wnull').length!=0) {
			      closeW('wnull')
			      if (!track.id) $('#ledokol_all').css({left:'85%'})
			  }
			  (j.id) ? user.init(j) : user.clear()
		      }
		    })
	 },
	 display: function() {
	    $('#usertitle_name').text(this.name)
	    $('#usertitle_rating > span.play').text(this.rating)
	    $('#usertitle_rating > span.pay').text(this.sales)
	    $('#usertitle_account ').html('MONEY: <span>'+this.account+'</span>')
	    $('#usertitle_messages .all').html( this.c2all)
	    $('#usertitle_messages .new').html( this.c2o )
	    this.showSendFriends()
	 },
	 showSendFriends: function() {
	     var text = "Пригласите друзей на однократное прослушивание Вашего трека<br><font size='1px'>сервис доступен для владельцев аккаунта Gmail</font><br><br>";
	     text += f_dbuttons(f_sbutton('Пригласить', "javascript:PathDispatcher(\"gimport\", 1, "+this.last_not_send_track+")", 'contacts', 'location,width=500,height=300,top=0', 'width:7em'));
	     if( this.last_not_send_track > 0 ) viewInfo('Приглашение друзей', text)
	 }
}

/**
 * Track object
 */
track = { id: 0, // track ID
	  plist: 0, // playlist ID
	  path: '', // path to track on server
	  u_id: 0, // user ID
	  u_name: '', // user name
	  u_avatar: 0,	// avatar exist status
	  code: 0, // code for increase rating
	  bitrate: 0, // bitrate
	  duration: 0, // track duration
	  playtime: 0, // track positionе
	  byauth: 0, // author's track
	  skype:'', //author's skype
	  email:'', //author's email
	  vk:'', //author's vkontakte url
	  promodj: '',
	  facebook: '',
	  init: function(param) {
	      this.id = param.id
	      this.plist = param.plist
	      this.path = param.path
	      this.u_id = param.u_id
	      this.u_name = param.u_name
	      this.u_avatar = param.u_avatar
	      this.code = param.code
	      this.bitrate = param.bitrate
	      this.duration = param.duration
	      this.playtime = param.playtime
	      this.byauth = param.byauth
	      this.email = param.email
	      this.vk = param.vk
	      this.skype = param.skype
	      this.promodj = param.promodj
	      this.facebook = param.facebook
	  },
	  clear: function() {
	      this.init( {id:0,
			  plist:0,
			  path:'',
			  u_id:0,
			  u_name:'',
			  u_avatar:0,
			  code:0,
			  bitrate:0,
			  duration:0,
			  playtime:0,
			  byauth:0,
			  skype:'',
			  email:'',
			  vk:'',
			  promodj:'',
			  facebook:''})
	  },

}

/**
 * Ledokol object
 */
ledokol = { smID:'1_id', // current sound manager ID
	    x_pos: 100, // position x
	    y_pos: 100, // position y
	    playsource: 'go', // playlist, go, link, signal
	    playtype: 'rand', // rating case
	    rate_type: 'listen',
	    rate_period: 'all',
	    rate_author: false,
	    rate_new: false,
	    volume: 100, // sound volume
	    endtrack: false, // признак проигрывания трека до конца
	    signalTimeout: null,
	    is_radioButtonRed: false,
	    checked: [],
	    uid: new Date().getTime(),
	    ignore_second: false,
	    tRange: 0,
	    is_radio: 0,
	    buy_track_id: 0,
	    buy_track_user_id: 0,
	    buy_pl_type: '',
	    buy_pl_name: '',
	    buy_param: 0,
	    gtn: 0, // "getting track now" property
	    halfpoint:0,
	    onepoint:0,
	    cross_flag:0,
	    cross_id:'',
	    credit_track:0,//track to buy in credit
	    credit_user:0,//user, who sells in credit
	    credit_plname:'',//playlist name to create
	    buy_myself:0,//when to buy track myself
	    muteflag:0,
	    init: function() {
		soundManager.createSound({id:'click', url:'/tracktmp/click.mp3', volume:ledokol.volume })
		$("#ledokol_all").click(function(){ return false })
		$("#ledokol_all")
		    .mouseenter(function() {
			if (typeof user != undefined && user.id != 0) {
			    if (user.id) ledokol.setMaxi()
			    $('.communications').fadeTo(500, 1)
			} })
		    .mouseleave(function() {
			if (user.id) ledokol.setMini()
			$('.communications').hide()
		    })
		$("span.button_minus").mousedown(function(e) {
		    ledokol.timer = setInterval(function() { ledokol.decreaseVolume() },100)
		    $(this).bind('mouseout mouseup', function() { clearInterval(ledokol.timer) })
		    return false
		})
		$('span.button_top').mousedown(function() { page.changePage('top'); return false })
		$("span.button_plus").mousedown(function() {
		    ledokol.timer = setInterval(function() { ledokol.increaseVolume() },100)
		    $(this).bind('mouseout mouseup', function() { clearInterval(ledokol.timer) })
		    return false
		})
		$('span.button_myplay').mousedown(function() {
		    if( !playlist.visible ) {
			page.changePage('playlist')
			return false
		    } else {
			page.changePage('top')
			return false
		    }
		})
		$('span.button_party').mousedown(function() { tempInfo('Сервис Ё пока не доступен', 5) })
		$('span.button_search').mousedown(function() { PathDispatcher('search', 0, 0); return false })
		$('span.button_send').mousedown(function() { PathDispatcher('sendmail', 0, 0); return false })
		$('#ledokol span.button_buy').mousedown(function() { PathDispatcher('buy', 0, 0); return false })
		$("#ledokol_go")
		    .addClass((user.id) ? 'button_go_random' : 'unmute')
		    .mousedown(function(e) {
			if (user.id) {
			    var __top=$("#ledokol_go").offset().top
			    if (e.pageY <__top+30) { // new-mode
				pd.playtype.setNew()
			    } else if (e.pageY > __top+30 && e.pageY < __top+60) { // random-mode
				pd.playtype.setRandom()
			    } else { // pop-mode
				pd.playtype.setPop()
			    }
			    ledokol.unblinkRadio()
			    ledokol.logicGo()
			} else {
			    if (e.pageY > $("#ledokol_go").offset().top+60) {
				if (ledokol.muteflag) {
				    ledokol.unmute()
				} else {
				    ledokol.mute()
				}
			    } else {
				if ($('#w_wnull').length==0 && !helper.g('go')) {
				    tempInfo('Вы не авторизованы. Возможны повторы!',2,'i')
				    helper.s('go',1)
				}
				if (ledokol.muteflag) {
				    ledokol.unmute()
				}
				$.cookie("link_is_played", null)
				ledokol.logicGo()
			    }
			}
			return false
		    })
                $('.button_upload')
		    .mousedown(function(e) {
    			if ($('#w_wnull').length) ledokol.closeWnull()
    			if (!user.id) {
			    var __top=$('.button_upload').offset().top
			    if (e.pageY <__top+15) {
 				pd.register.withBuy()
			    } else {
				pd.register.withUpload()
			    }
			} else
    		    	    pd.upload.trackUpload()
    			return false
		    })
   	        $('.avatar').mousedown(function(e) {
		    var _ledall=$('#ledokol_all'), _led=$('#ledokol'), _wh=$(window).height()
		    $('#backdiv').css('z-index',_ledall.css('z-index')-1).show().css({'height':_wh+$(document).scrollTop()});
		    var ledX=e.pageX-$(this).offset().left+20, ledY=e.pageY-_ledall.offset().top, bodyW=$('body').width(), ledW=_led.width(), ledH=_led.height();
		    var bodyH=($('body').height()>_wh) ? $('body').height() : _wh, offsetL, offsetLA, minX, maxX, minY, maxY;
		    $(document)
			.mouseup(function() {
	        	    $(document).unbind('mousemove mouseup');
	        	    $('#backdiv').hide();
			    return false })
			.mousemove(function(e) {
	    		    if ($.browser.msie && !e.button) { $(document).trigger('mouseup'); return false }
	        	    ledokol.x_pos=e.pageX-ledX; ledokol.y_pos=e.pageY-ledY;
	        	    offsetL=_led.offset();
	        	    offsetLA=_ledall.offset();
	        	    minX=offsetLA.left-offsetL.left;
	        	    maxX = bodyW - (offsetL.left-offsetLA.left) - ledW;
	        	    ledokol.x_pos = (ledokol.x_pos<(minX)) ? minX : ledokol.x_pos;
	        	    ledokol.x_pos = (ledokol.x_pos>(maxX)) ? maxX : ledokol.x_pos;
	        	    minY = offsetLA.top - offsetL.top;
	        	    maxY = bodyH - (offsetL.top-offsetLA.top) - ledH;
	        	    ledokol.y_pos = (ledokol.y_pos>(maxY)) ? maxY : ledokol.y_pos;
	        	    ledokol.y_pos = (ledokol.y_pos<(minY)) ? minY : ledokol.y_pos;
			    _ledall.css({'left':ledokol.x_pos+'px','top': ledokol.y_pos+'px'});
			    return false })
		    return false
		})
		$.cookie('uid', this.uid)
		$('#usertitle.unauth').hover(
	    	    function() { if ($(this).hasClass('unauth')) $(this).find('.namegame').html(Lm.lt['Game_name'].r) },
	    	    function() { if ($(this).hasClass('unauth')) $(this).find('.namegame').html(Lm.lt['Game_name'].e) }
		)
	    },

	    crossFade: function() {
		var __t=this.smID
		this.cross_flag=1
		this.smID=[(parseInt(__t)+1),'_id'].join('')
		this.lfadeOut(__t,this.volume-40,0)
	    },

	    lfadeOut: function(__id,__volume, __step) {
		__volume=__volume-5-__step
		if (__volume <= 0 || this.cross_flag==0) {
		    this.cross_flag=0
		    soundManager.destroySound(__id)
		    return
		}
		soundManager.setVolume(__id, __volume)
		setTimeout(function() { ledokol.lfadeOut(__id,__volume,__step+1) }, 750)
	    },

	    unblinkRadio: function() {
		ledokol.is_radio=0
		$('#usertitle_my_radio').attr('class','')
	    },

	    blinkRadio: function() {
		ledokol.is_radio=1
		$('#usertitle_my_radio').attr('class','active')
	    },

	    /**
	     * Set ledokol to unauth-mode view
	     */
	    setUnauth: function() {
		$('#ledokol_all').addClass('ledokol_unauth').removeClass('ledokol_mini')
		$('#ledokol_go').attr('class','ledokol_button unmute')
		this.initTrackInfo()
	    },

	    /**
	     * Set ledokol to auth-mode view
	     */
	    setAuth: function() {
		$('#ledokol_all').removeClass('ledokol_unauth')
		this.initTrackInfo()
	    },

	    /**
	     * Set ledokol to mini-mode view for authorized user
	     */
	    setMini: function() {
		$('#ledokol_all').addClass('ledokol_mini')
	    },

	    /**
	     * Set ledokol to maxi mode for authorize user
	     */
	    setMaxi: function() {
		$('#ledokol_all').removeClass('ledokol_mini')
		$('.button_buy').parents('.authbuttons').show()
	    },

	    /**
	     * Set ledokol to "new" view
	     */
	    setNew: function() {
		$('#ledokol_go').attr('class','ledokol_button button_go_new')
	    },

	    /**
	     * Set ledokol to "random" view
	     */
	    setRandom: function() {
		$('#ledokol_go').attr('class','ledokol_button button_go_random')
	    },


	    /**
	     * Set ledokol to "random" view
	     */
	    setPop: function() {
		$('#ledokol_go').attr('class','ledokol_button button_go_pop')
	    },


	    /**
	     * Actions on finish track playing
	     */
	    finishState: function() {
		//if (this.sID !== ledokol.smID) return
		if (user.id) ledokol.endtrack=true // finish track marker
		if (ledokol.playsource=='go') {
		    if (!ledokol.onepoint)
			ledokol.addOnePoint() // increase rating
		    ledokol.playsource = 'signal'
		    ledokol.startSignal(0)
		    return
		}
		if (ledokol.playsource=='playlist' && !ledokol.is_radio ) {
		    helper.s('prevpl',1)
		    ledokol.stopSignal()
		    ledokol.startSignal(0)
		    return
		}
		if (ledokol.is_radio==1) {
		    helper.s('prevpl',1);
		    ledokol.stopSignal();
		    if (playlist.tracks.length<1) {
			ledokol.getNewTrack({page:'gett',trackid:track.id,playtype:ledokol.playtype,playlist:true});
		    } else {
			playlist.playNextTrack();
		    }
		}
	    },

	    /**
	     * Actions on track playing
	     */
	    playingState: function() {
		if (this.sID !== ledokol.smID) return;
		ledokol.move(this.position)
		if ((track.duration > 0 && (ledokol.playsource == 'similar' || ledokol.playsource == 'preview')) || (ledokol.playsource=='playlist' && !playlist.isSdrag && playlist.visible==true && track.duration > 0))
		    playlist.autoMoveSlider(this.position*100/track.duration)
		if (!ledokol.halfpoint && this.position > track.duration/2 && this.position>30000)
		    ledokol.addHalfPoint()
		if (ledokol.halfpoint && !ledokol.onepoint && this.position > 300000)
		    ledokol.addOnePoint()
	    },

 	    /**
	     * Add half rating point
	     */
	    addHalfPoint: function() {
		ledokol.halfpoint=1
		if (user.id != track.u_id) {
		    if (typeof getlink == 'undefined')
			$.getJSON('index.php',{page:'add_half_point',u:track.u_id,p:track.plist,t:track.id,c:track.code,ac:mr()})
		    else
			$.getJSON('index.php',{page:'add_half_point',link:getlink,u:track.u_id,p:track.plist,t:track.id,c:track.code,ac:mr()})
		}
	    },

   	    /**
	     * Add one rating point
	     */
 	    addOnePoint: function() {
 		ledokol.onepoint=1
		if (user.id != track.u_id) {
		    if (typeof getlink == 'undefined')
			$.getJSON('index.php',{page:'add_one_point',u:track.u_id,p:track.plist,t:track.id,c:track.code})
		    else
			$.getJSON('index.php',{page:'add_one_point',link:getlink,u:track.u_id,p:track.plist,t:track.id,c:track.code})
		}
	    },

 	    /**
	     * Clear point flags
	     */
 	    clearPoints: function() {
 		this.halfpoint=this.onepoint=0
	    },

            closeWnull: function() {
 		closeW('wnull')
		$('#ledokol_all').css({left:'85%'})
		//page.isAuth()
	    },

	    /**
	     * GO-button logic
	     */
	    logicGo: function() {
		if ($('#w_wnull').length!=0) this.closeWnull()
		var _f=0
		if (this.playsource=="playlist" || helper.g('prevpl')) { _f=1; $('.mpllineact').each(function() { this.className='mplline' })}
		if (this.playsource == 'signal') this.stopSignal()
		this.playsource='go'
		if (page.page=='top' && this.playtype=='rate' && this.rate_period=='new' ) usertop.refresh()
		if (_f==0 && this.endtrack == true && !helper.g('gonext')) // don't change playlist
		    this.getNewTrack({page:'gett',next:true,userid:track.u_id,playtype:this.playtype,trackid:track.id, plist:track.plist, acash:mr()});
		else // change playlist
		    this.getNewTrack({page:'gett',userid:track.u_id,playtype:this.playtype,rate_type:this.rate_type,rate_period:this.rate_period,rate_author:this.rate_author,trackid:track.id, plist:track.plist, acash:mr()})
	    },

	    /**
	     * Start track loader
	     */
	    trackLoader: function() {
		$('#authb').hide()
		$('.name marquee').text('загрузка трека')
		$('.avatar').empty().append('<img src="/img/loader.gif">')
	    },

	    /**
	     * TOP-button logic
	     */
	    logicTop: function() {
		$.ajax({ async:false,
			 dataType:'json',
			 url:'/index.php?page=jtop&playtype='+this.playtype+'&ac='+mr(),
			 success: function(j) {
			     var colors = ['#619161','#616991','#918961','#777a65','#81b37b','#a6c078','#b6bf99','#898883']
			     if (!user.id) {
				 var lines = [3,5,8,12,18,24,30]
			     } else {
			     var lines = (ledokol.playtype=='rate' && ledokol.rate_type=='pop') ? [3,5,8,12,18,24,30] : [10,10,10,10,10,10,10,10,10,10]
			     }
			     usertop.hlines=[]
			     usertop.init('suptop',j, lines, colors)
			     page.changePage('top')
			 }
		       })
	    },

	    /**
	     * Move ledokol
	     */
	    move: function(pos) {
  		ledokol.cross_flag=0
		if (!helper.g('gf')) {
		    setTimeout(function() {
			if (user.id==0 && $.cookie("last_nick") == null) {//user is authorized and fast authorize is not avaliable
			    viewInfo('<center>Нулевой уровень игры</center>', '<center>На нулевом уровне музыкальной игры Ледокол можно прослушать звучащий трек и/или<br> cменить его на другой.</center><br><br><br><br>', 0,'ledokol.closeWnull()','wnull',350)
			}
			page.init()
			ledokol.show()
		    }, 3000)
		    helper.s('gf',1)
		}
		if ($('#w_wnull').length==0) {
		    if (pos) {
			var newPos=124-Math.floor(pos/track.duration*124)
			if (!helper.g('gf') && newPos) {
			    ledokol.show()
			    helper.s('gf',1)
			}
			if (parseInt($('#ledokol_all').css('top')) + newPos <= 0) return false
			$('#crack').height(newPos)
		    }
		} else {
		    //$('#crack').height(0);
		    $('#ledokol_all').css({top:parseInt($('#w_wnull').css('top'))+$('#w_wnull').height()+(123-$('#crack').height())-110+'px',left:parseInt($('#w_wnull').css('left'))+$('#w_wnull').width()/2-55+'px'})
		}
	    },

	    /**
	     * Запрос плейлиста игрока -- при нажатии на аватар в топе
	     * @param integer uid идентификатор игрока
	     * @return void
	     */
	    getPlaylistUser: function(uid, pl) {
		if (this.playsource == 'signal') this.stopSignal()
		this.unblinkRadio()
		this.playsource='go';
		this.getNewTrack({page:'gett', next:true, userid:uid, plist:pl, playtype:this.playtype, rate_period:this.rate_period, rate_author:this.rate_author, acash:mr()})
	    },

	    /**
	     * Проигрывание трека из плейлиста игрока
	     * @param integer uid идентификатор игрока
	     * @return void
	     */
	    getTrackFromPlaylist: function(param) {
		this.stopSignal();
		this.stopTrack();
		this.playsource="playlist";
		track.init({id:param.id,plist:param.playlist,path:param.trackpath,u_id:user.id,u_name:user.name,u_avatar:param.avatar,code:0,bitrate:0,duration:0,playtime:0,byauth:0});
		this.initTrackInfo();
		this.playTrack(track.path)
	    },

	    /**
	     * Play track from search
	     * @param string
	     */
	    getSearchTrack: function(id) {
		ledokol.stopSignal();
		ledokol.stopTrack();
		this.playsource="go";
		this.trackLoader();
		$.getJSON('/index.php', {page:'gett',t:id}, function(j) {
		    if (j.s==1) {

				ledokol.playsource == 'search'
				track.init({id:j.trackid,plist:j.playlist,path:j.trackpath,u_id:j.userid,u_name:j.user,u_avatar:j.avatar,code:j.code,bitrate:0,duration:0,playtime:0,byauth:j.author})
				ledokol.initTrackInfo()
				ledokol.playTrack(track.path)
		    } else
		    	viewInfo('Инфо', j.m, 8)
		})

	    },

	    /**
	     * Play track from link
	     * @param string link sending track ID from base
	     */
	    getLinkTrack: function(link) {
		ledokol.stopSignal();
		ledokol.stopTrack();
		this.playsource="go";
		this.trackLoader();
		$.getJSON('/index.php', {page:'gett',link:link,ac:mr()}, function(j) {
		    if (j.s==1) {

		    	viewInfo('Добро пожаловать!', 'Игрок <b>'+j.nickSend+'</b> желает Вам приятного прослушивания', 8)
				ledokol.playsource == 'link'
				track.init({id:j.trackid,plist:j.playlist,path:j.trackpath,u_id:j.userid,u_name:j.user,u_avatar:j.avatar,code:j.code,bitrate:0,duration:0,playtime:0,byauth:j.author})
				ledokol.initTrackInfo()
				ledokol.playTrack(track.path)
		    } else {
			if ($.cookie("link_is_played") != null && $.cookie("link_is_played")) {
			    pd.register.withBuy()
			} else {
		    	    viewInfo('Инфо', j.m, 8)
			}
		    }
		})
	    },

	    /**
	     * Play track from VKontakte
	     * @param string link sending track ID from base
	     */
	    getVKTrack: function(vk) {
		ledokol.stopSignal();
		ledokol.stopTrack();
		this.playsource="go";
		this.trackLoader();

		$.getJSON('/index.php', {page:'gett', vk:vk, vk_user:vk_user, ac:mr()}, function(j) {
		    if (j.s==1) {
		    	viewInfo('Добро пожаловать!', 'Игрок <b>'+j.user+'</b> желает Вам приятного прослушивания', 8)
			ledokol.playsource == 'link'
			track.init({id:j.trackid,plist:j.playlist,path:j.trackpath,u_id:j.userid,u_name:j.user,u_avatar:j.avatar,code:j.code,bitrate:0,duration:0,playtime:0,byauth:j.author})
			ledokol.initTrackInfo()
			ledokol.playTrack(track.path)
		    } else {
			track.u_id = j.user
			track.id2 = j.track
			pd.register.withBuy()
		    }
		})

	    },


	    /**
	     * Проигрывание трека
	     * @return void
	     */
	    playTrack: function() {
		if (soundManager.canPlayURL(track.path)) {
		    this.endtrack=false
		    this.clearPoints()

		    soundManager.createSound({id:this.smID, url:track.path, volume:this.volume, autoPlay:true, whileplaying:this.playingState, whileloading:this.calcDuration, onfinish:this.finishState })
		} else
		    tempInfo('Трек недоступен', 2, 'i')
		//$('#ledokol_all').css('background-image','url("img/crack.gif")')
	    },

	    /**
	     * Get new track from server
	     */
	    getNewTrack: function(param) {
		(this.endtrack==true) ? this.stopTrack() : this.crossFade()
		if (1==this.gtn) return;
		helper.s('gofirst',1);
		this.trackLoader();
		this.gtn=1;
		$.getJSON('/index.php', param, function(j)  {
		    if (j.s==1) {
			helper.s('gonext',0);
			if (ledokol.playsource=='playlist') {
			    _avatar = (user.avatar!=0) ? user.id : 0;
			    track.init({id:j.trackid,plist:j.playlist,path:j.trackpath,u_id:user.id,u_name:user.name,u_avatar:_avatar,code:0,bitrate:0,duration:0,playtime:0,byauth:j.author});
			    ledokol.c_pl=j.playlist;
			    ledokol.c_tr=j.trackid;
			    playlist.bindSlider()
			} else {
			    track.init({id:j.trackid,plist:j.playlist,path:j.trackpath,u_id:j.userid,u_name:j.user,u_avatar:j.avatar,code:j.code,bitrate:0,duration:0,playtime:0,byauth:j.author,skype:j.skype,vk:j.vk,email:j.email,promodj:j.promodj,facebook:j.facebook});
			}
			ledokol.endtrack=false;
			ledokol.initTrackInfo();
			ledokol.playTrack(track.path)
		    } else if (j.s==2) {
			tempInfo('Ошибка сервера', 1,'i')
		    } else if (j.s==3) {
			helper.s('gonext',1);
			ledokol.startSignal();
			$('.name marquee').text('');
			$('.avatar').empty().append('<img src="/img/blank.gif">');
			var _m='Вы прослушали все треки плейлиста: '+j.name;
			tempInfo(_m, 2,'i')
		    } else {
			tempInfo('Ошибка', 1,'i')
		    }
		    ledokol.gtn=0
		})
	    },

            /**
             * Init track owner information: avatar, name
             */
            initTrackInfo: function() {
		$('.name').html('<div id="w">'+track.u_name+'</div>')
		$('#w').css({'margin-left':'100px'})

		$('.avatar').empty().append('<img src="'+((track.u_avatar) ? '/index.php?page=gla&id='+track.u_avatar : '/img/blank.gif')+'">')

		var communications = '<img id="comm_email" src="/img/email.png">';
		if( track.skype != null && track.skype != '' ) {
			communications += '<img id="comm_skype" src="/img/SkypeBlue_16x16.png">'
		}
		if( track.vk != null && track.vk != '' ) {
			communications += '<img id="comm_vk" src="/img/vk_icon.png">'
		}
		if( track.promodj != null && track.promodj != '' ) {
			communications += '<img id="comm_promodj" src="/img/promdj.png">'
		}
		if( track.facebook != null && track.facebook != '' ) {
			communications += '<img id="comm_facebook" src="/img/facebook.png">'
		}
		$('.communications').empty().append( communications );

		var communications_r = '<img id="comm_down" src="/img/download.png" width="16px">';
		//communications_r += '<img id="comm_sc" src="/img/shopping_cart.png" width="16px">';

		$('.communications_r').empty().append( communications_r );

		$('#comm_email').unbind("click");
		$('#comm_skype').unbind("click");
		$('#comm_vk').unbind("click");
		$('#comm_facebook').unbind("click");
		$('#comm_promdj').unbind("click");
		$('#comm_down').unbind("click");

		$('#comm_email').bind("click", function(){ community.send( track.email )});
		$('#comm_skype').bind("click", function(){ window.open('callto:' + track.skype); });
		$('#comm_vk').bind("click", function(){	window.open(track.vk);	});
		$('#comm_facebook').bind("click", function(){	window.open(track.facebook);	});
		$('#comm_promodj').bind("click", function(){	window.open(track.promodj);	});

		/*$('#comm_sc').bind("click", function(){

			PathDispatcher('buy', 8);
		});*/
		$('#comm_down').bind("click", function(){

			window.open( track.path );
		});
		if (track.byauth==1)
		    $('#authb').show()
		clearInterval(this.marqueTimer)
		this.marqueTimer=setInterval(function() {
		    var _t=parseInt($('#w').css('margin-left'))
		    _t= (_t<-100) ? 100 : _t-5
		    $('#w').css('margin-left',_t+'px')
		}, 500)
	    },

            /**
	     * Stop playing track
	     */
            stopTrack: function() {
		soundManager.destroySound(this.smID)
	    },

            /**
	     * Dynamic calculation duration of track
	     */
            calcDuration: function() {
		track.duration=Math.floor((this.bytesTotal/this.bytesLoaded)*this.duration)
		if (ledokol.playsource=='playlist') {
		    __t=$('#'+playlist.c_tr+'_t .lname')
		    __t.css('background-position',Math.floor(this.bytesLoaded*__t.width()/this.bytesTotal-1000)+'px 10px')
		}
	    },

	    /**
	     * Start signal between tracks
	     */
            startSignal: function(it) {
		ledokol.playsource = 'signal';
		switch (it) {
		case 0: var param = {n:1,f:'poziv-01.mp3',t:24}; break
		case 1: var param = {n:2,f:'poziv-01.mp3',t:24}; break
		case 2: var param = {n:3,f:'poziv-01.mp3',t:24}; break
		case 3: var param = {n:0,f:'poziv-03.mp3',t:36}; ledokol.tRange +=6; break // increase timer
		default: var param = {n:1,f:'poziv-01.mp3',t:24}
		}
		soundManager.destroySound(this.smID)
		soundManager.createSound({ id:this.smID, url:'http://93.95.101.79/system/'+param.f, volume:this.volume, autoPlay:true})
		this.signalTimeout = setTimeout( function() { ledokol.startSignal(param.n) }, (param.t+ledokol.tRange)*1000)
	    },

            /**
	     * Stop signal
	     */
            stopSignal: function() {
		clearTimeout(this.signalTimeout)
		this.stopTrack()
	    },

            /**
	     * Increase player volume
	     */
            increaseVolume: function() {
		if (this.volume<100) {
		    this.volume += 10
		    soundManager.setVolume(this.smID, this.volume)
		}
	    },

	    /**
	     * Desrease player volume
	     */
            decreaseVolume: function() {
		if (this.volume>0) {
		    this.volume -= 10
		    soundManager.setVolume(this.smID, this.volume)
		}
	    },

            /**
             * Show ledokol-player
             */
            show: function() {
		this.visible = true
		$('#ledokol_all').show()
		if (user.id) this.setMini()
	    },

            /**
             * Hide ledokol-player
	     */
            hide: function() {
		this.visible = false
		this.stopSignal()
		$('#ledokol_all').hide()
	    },

            /**
	     * Mute
	     */
            mute: function() {
		$('#ledokol_go').removeClass('unmute').addClass('mute')
		ledokol.muteflag=1
		soundManager.mute()
	    },

            /**
	     * Unmute
	     */
            unmute: function() {
		$('#ledokol_go').removeClass('mute').addClass('unmute')
		ledokol.muteflag=0
		soundManager.unmute()
	    },

	    playClick: function() {
	    	soundManager.play('click')
	    }
}

/**
 * Internalization messages class
 */
Lm =  { lt: [],
        lang: 'rus',
        init: function(lang) {
	   this.lt['Name']={r:'Имя', e:'Name'}
 	   this.lt['Name2']={r:'Название', e:'Name'}
	   this.lt['Name3']={r:'Имя на Ledokol\'e', e:'Name'}
	   this.lt['Password']={r:'Пароль', e:'Password'}
	   this.lt['OldPassword']={r:'Старый пароль', e:'Old Password'}
	   this.lt['RePassword']={r:'Повторите пароль', e:'Repeat Password'}
	   this.lt['Invalid_name_or_password']={r:'Имя или пароль введены неверно', e:'Invalid name or password'}
	   this.lt['Add_gamer_to_point']={r:'Добавить игрока на точку', e:'Add gamer to party point'}
	   this.lt['Authorize_please']={r:'Представьтесь', e:'Authorize, please'}
	   this.lt['File']={r:'Файл', e:'File'}
	   this.lt['Browse']={r:'Выбрать', e:'Browse'}
	   this.lt['Track_upload']={r:'Загрузка трека в игру', e:'Track upload'}
	   this.lt['Title']={r:'Название', e:'Title'}
	   this.lt['Artist']={r:'Исполнитель', e:'Artist'}
	   this.lt['Comment']={r:'Комментарий', e:'Comment'}
	   this.lt['Price_rub']={r:'Цена, руб.', e:'Price, RUR'}
	   this.lt['Email']={r:'Email', e:'Email'}
	   this.lt['ReEmail']={r:'Повторите Email', e:'Repeat Email'}
	   this.lt['Passport']={r:'Данные паспорта', e:'Passport'}
	   this.lt['Profile_data']={r:'Данные профиля', e:'Profile data'}
	   this.lt['Track_information']={r:'Информация о треке', e:'Track information'}
	   this.lt['Upload_ok']={r:'Трек загружен успешно', e:'Track upload successful'}
	   this.lt['Ledokol_set_minimal_price']={r:'На трек установлена минимальная цена в размере', e:'Ledokol_set_minimal_price'}
	   this.lt['RUR']={r:'руб.', e:'RUR'}
	   this.lt['Increase_balance']={r:'Увеличить баланс', e:'Increase balance'}
	   this.lt['Get_money']={r:'Вывод средств', e:'Get money'}
	   this.lt['Balance_information']={r:'Информация о балансе', e:'Balance information'}
	   this.lt['Your_balance']={r:'Ваш баланс', e:'Your balance'}
	   this.lt['Amount']={r:'Сумма', e:'Amount'}
	   this.lt['Avatar']={r:'Аватар', e:'Avatar'}
	   this.lt['Delete_playlist']={r:'Удаление плейлиста', e:'Delete playlist'}
	   this.lt['Playlist_deleted']={r:'Плейлист удален', e:'Playlist deleted successful'}
	   this.lt['Playlist_propertys']={r:'Свойства плейлиста', e:'Playlist propertys'}
	   this.lt['Delete_track']={r:'Удаление трека', e:'Delete track'}
	   this.lt['Track_moved_to_trash']={r:'Трек перемещен в корзину', e:'Track moved to trash successful'}
	   this.lt['Edit_track_info']={r:'Редактирование трека', e:'Edit track info'}
	   this.lt['Delete_gamer_from_point']={r:'Удалить игрока с точки', e:'Delete gamer from point'}
	   this.lt['Message']={r:'Сообщение', e:'Message'}
	   this.lt['You_authorize']={r:'Вы успешно авторизованы', e:'You authorize successful'}
	   this.lt['Authorize_for_upload']={r:'', e:'Authorize for upload, please!'}
	   this.lt['Authorize_for_listen_playlist']={r:'', e:'Authorize for listen playlist'}
	   this.lt['New']={r:'Новые', e:'New'}
	   this.lt['Day']={r:'День', e:'Day'}
	   this.lt['Week']={r:'Неделя', e:'Week'}
	   this.lt['Month']={r:'Месяц', e:'Month'}
	   this.lt['All']={r:'Популярные', e:'Popular'}
	   this.lt['Author_rate']={r:'Авторский', e:'Authors'}
	   this.lt['Rating']={r:'Рейтинг', e:'Rating'}
	   this.lt['Rate_it']={r:'Применить', e:'Rate it!'}
	   this.lt['Rating_type']={r:'Вид рейтинга', e:'Rating type'}
	   this.lt['Account_WMZ']={r:'Кошелек WMZ/WMR', e:'Account WMZ/WMR'}
	   this.lt['WM_account_invalid']={r:'Вы неверно ввели WM-кошелек!', e:'WM account invalid'}
	   this.lt['Money_in_game']={r:'Игровые деньги', e:'Money in game'}
	   this.lt['Author_money']={r:'Авторские начисления', e:'Author\'s money'}
	   this.lt['Bitrate']={r:'Битрейт', e:'Bitrate'}
	   this.lt['Sales']={r:'Продажи', e:'Sales'}
	   this.lt['RUR']={r:'руб.', e:'RUR'}
	   this.lt['Delete']={r:'Удалить', e:'Delete'}
	   this.lt['Edit']={r:'Редактировать', e:'Edit'}
	   this.lt['Buy']={r:'Купить', e:'Buy'}
	   this.lt['Inf_update_successful']={r:'Информация о треке изменена успешно...', e:'Informatio updated successful'}
	   this.lt['Inf_update_error']={r:'Ошибка обновления информации', e:'Error update information'}
	   this.lt['Track_upload_successful']={r:'Трек загружен успешно', e:'Track upload successful'}
	   this.lt['Error_track_upload']={r:'Ошибка загрузки трека', e:'Error track upload'}
	   this.lt['Track_not_unique']={r:'Трек не уникален', e:'Track not unique'}
	   this.lt['System_error']={r:'Системная ошибка', e:'System error'}
	   this.lt['Not_money_for_buy']={r:'У вас не хватает денег для покупки трека', e:'You not have money for buy this track'}
	   this.lt['Saler_do_not_have_this_track']={r:'Этого трека нет у выбранного продавца', e:'Saler do not have this track'}
	   this.lt['Track_already_present']={r:'Трек уже есть в вашем плейлисте', e:'Track already present in your playlist'}
	   this.lt['Unknown_error']={r:'Неизвестная ошибка', e:'Unknown error'}
	   this.lt['Authorize_for_buy_track']={r:'', e:'Authorize for buy track'}
	   this.lt['I_am_author']={r:'Я автор/правообладатель', e:'I am author'}
	   this.lt['Invalid_artist_name']={r:'Укажите имя исполнителя', e:'Invalid artist name'}
	   this.lt['Invalid_track_name']={r:'Укажите название трека', e:'Invalid track name'}
	   this.lt['Repeat_pass']={r:'Повтор пароля', e:'Repeat password'}
	   this.lt['Sex']={r:'Пол', e:'Sex'}
	   this.lt['Male']={r:'Мужской', e:'Male'}
	   this.lt['Female']={r:'Женский', e:'Female'}
	   this.lt['Register']={r:'Регистрация', e:'Register'}
	   this.lt['Register_form']={r:'Регистрация игрока', e:'Register form'}
	   this.lt['register_link']={r:'Регистрация', e:'Register'}
	   this.lt['Forgot_pass_title']={r:'Восстановление пароля', e:'Password Recovery'}
	   this.lt['Forgot_pass_quest']={r:'Забыли пароль?', e:'Forgot password?'}
	   this.lt['Add_playlist']={r:'Создать плейлист', e:'Add playlist'}
	   this.lt['Community']={r:'Комьюнити', e:'Community'}
	   this.lt['Add_contact']={r:'Новый контакт', e:'Add contact'}
	   this.lt['Send_message']={r:'Отправить сообщение', e:'Send message'}
	   this.lt['Date']={r:'Дата', e:'Date'}
	   this.lt['Saler']={r:'Продавец', e:'Saler'}
	   this.lt['Party']={r:'Пати', e:'Party'}
	   this.lt['BuyDate']={r:'Дата покупки', e:'Buy Date'}
	   this.lt['Authorize_please_when_buy']={r:'Заходи - не бойся', e:'What are you waiting for?'}
	   this.lt['Game_name']={r:'<table><tr><td>Музыкальная игра &nbsp;</td><td><div><img src="img/ledokol_lic.gif" /></div></td></tr></table>', e:'<div>LEDOKOL MUSIC GAME</div>'}
       },
       g: function(p) {
	   return (typeof this.lt[p] != 'undefined') ? ((this.lang=='rus') ? this.lt[p].r : this.lt[p].e) : false
       }
}

/**
 * Helper object
 */
helper = { c: [],
	   s: function(_p,_v) {
	       this.c[_p]=_v
	   },
	   g: function(_p) {
	       return (typeof this.c[_p] != 'undefined') ? this.c[_p] : false
	   },
	   clear: function() {
	       this.c=[]
	   }
}

/**
 * Search Track object
 */
searchtracks = { id:'searchTracks',
                 word:'', // search word
           	 tracks:[],
		 visible:true,
		 mode:'intro', // intro | extra
		 luckyuser:0,

		 init: function(plists) {
		     this.tracks = []
		     var l = plists.length
		     for (var i=0;i<l;i++) {
			 if (this.mode=='intro')
			     this.tracks.push({id:plists[i].id,user:plists[i].user,name:plists[i].name,artist:plists[i].artist,album:plists[i].album, idnum:plists[i].idnum,rating:plists[i].rating,uname:plists[i].uname,urate:plists[i].urate})
			 else
			     this.tracks.push({link:plists[i].l,ancor:plists[i].a})
		     }
		 },

		 create: function() {
		     var ml=[], _c=' header', _t, _p=this.param, _act, l = Math.min(50, this.tracks.length);
		     ml.push('<div id="srTrack">');
		     ml.push('<div id="lucky" style="position:absolute;top:35px;left:5px"> <button class="tbutton" type="button">удачный трек</button></div>');
		     ml.push('<div class="searchTracksheader">');
		     if (this.mode=='intro') {
			 ml.push(f_divcl('N','lnum'+_c))
			 ml.push(f_divcl('Название','lname'+_c))
			 ml.push(f_divcl('Рейтинг','lrate'+_c))
			 ml.push(f_divcl('Артист','lart'+_c))
			 ml.push(f_divcl('Альбом','lart'+_c))
			 //ml.push(f_divcl('Игрок','lrate'+_c))
			 //ml.push(f_divcl('Рейтинг','lrate'+_c))
			 ml.push(f_divcl('Купить','lrate'+_c))
		     } else
			 ml.push(f_divcl('N','lnum'+_c)+f_divcl('Трек','ltrack'+_c)+f_divcl('Переход','lparty'+_c));
		     ml.push('</div>');
		     for (i=0;i<l;i++) {
			 _t=this.tracks[i];
			 if (this.mode=='intro') {
			     ml.push('<div class="serlline" id="'+this.tracks[i].id+'_t" '+((i%2==0) ? 'style="background:#222"' : '')+'>');
			     ml.push(f_divcl(i+1,'lnum'))
			     ml.push(f_divcl((_t.name.length>0) ? '<img width="16px" onclick="javascript:searchtracks.play('+this.tracks[i].id+');" src="img/track_play.gif" id="search_play">'+_t.name : '&nbsp;','lname'))
			     ml.push(f_divcl(_t.rating,'lrate2'))
			     ml.push(f_divcl((_t.artist.length>0) ? _t.artist : '&nbsp;','lart'))
			     ml.push(f_divcl((_t.album.length>0) ? _t.album :'&nbsp;','lart'))
			     //ml.push(f_divcl(_t.uname+' <span>'+_t.urate+'</span>','lrate'))
			     //ml.push(f_divcl(_t.urate,'lrate'))
			     ml.push(f_divcl('<a href="javascript:PathDispatcher(\'buy\', 0, {id:'+_t.id+',u_id:'+_t.user+'})">buy</a>','lrate'));
			 } else {
			     ml.push('<div class="serlline">');
			     ml.push(f_divcl(i+1,'lnum')+f_divcl(_t.ancor,'ltrack')+f_divcl('<a target="_blank" href="http://fuckcd.ru'+_t.link+'">go & get</a>','lparty'));
			 }
			 ml.push('</div>');
		     }
		     ml.push('<div><br>'); ml.push('<div id="mp3search"><a href="#" onclick="PathDispatcher(\'search\', 3, {page:1}); return false">поиск по внешним ресурсам</a></div>');
		     ml.push('<br><br><br>');
		     $('#searchTracks').empty().append(ml.join(''));
		     for( i=0;i<l;i++ ) {
		    	 /*$("#"+this.tracks[i]+"_t").bind("click", function(){

		    		 //alert('He');
		    		 //searchtracks.play(i);
		    	 });*/
		     }
		     delete(ml)
		 },

		 play: function(trackId) {
     		     if (ledokol.playsource=='signal') ledokol.stopSignal()
		     $.getJSON('/index.php', {page:'gett', track:trackId}, function(j) {
			 if (j.s==1) {
			     ledokol.stopTrack()
			     track.init({id:j.trackid,plist:j.playlist,path:j.trackpath,u_id:j.userid,u_name:j.user,u_avatar:j.avatar,code:j.code,bitrate:0,duration:0,playtime:0,byauth:j.author})
			     ledokol.initTrackInfo()
			     ledokol.playTrack()
			 } else {
				 j.m += '<br><br><center>'+f_button('Купить', 'PathDispatcher(\'buy\', 0, {id:'+j.track+',u_id:'+j.user+'})')+'</center>';
			     viewInfo('Инфо', j.m, 8)
			 }
		     })
		 },
		 hide: function() {
		     this.visible=false;
		     $("#"+this.id).empty().hide()
		 },

		 show: function() {
		     this.visible=true
		     $("#"+this.id).show()
		 }
}

/**
 * Top object
 */
usertop = { visible: true,
	    lines: [],
	    hlines: [],
	    correct: 0,
	    create: function(id,param,lines,colors) {
  		this.id = id
		this.users = param
		this.lines = lines
		this.colors = colors
		this.width = $('#'+id).width()
		this.height =$('#'+id).height()
		this.getLines()
		var u=this.users.length, cl = this.colors.length, dl=[], width, height, avatar, sales, img, pa
		for (var i=0;i<u;i++) {
		    dl.push(['<div class="tUser" id="',
			     this.users[i].p,
			     '_u" style="background:',
			     this.colors[Math.floor(Math.random()*cl)],
			     ';width:',
			     this.getWidth(i),
			     'px;height:',
			     this.hlines[this.users[i].l-1],
			     'px;"><img src="/avatars/',
			     (this.users[i].a) ? this.users[i].a : 'noavatar.jpg',
			     '" alt=""><div class="tInfo"><span>',
			     this.users[i].n,
			     '</span></div>',
			     ,'<div class="tSub">',
			     '<big>',
			     this.users[i].r,
			     '</big>',
			     '</div>',
			     '<div class="tSub2">',
			     '<small>',
			     this.users[i].t,
			     ' tracks<br>',
			     this.users[i].tm,
			     '</small>',
			     '</div>',
			     //'<img class="downloadtop" src="/img/download.png" style="width:15%; height:15%">',
			     '</div>'].join(''))
		}
		dl.push(f_cboth())
		$('#'+this.id).append(dl.join(''))
		this.bindTop()
		if (this.width != $('#'+id).width()) this.resizeIt()
		this.resizeFonts()
		$(window).resize(function() { usertop.resizeIt() })
	    },

	    load: function(param) {
		$.getJSON('index.php',param, function(json) {
		    usertop.hlines=[]
		    var colors = (ledokol.rate_author) ? ['#c10606','#e13131','#b12727','#e84c83','#a4003a','#dc5f2e'] : ['#619161','#616991','#918961','#777a65','#81b37b','#a6c078','#b6bf99','#898883'], lines = (ledokol.playtype=='rate' && ledokol.rate_type=='pop') ? [3,5,8,12,18,24,30] : [10,10,10,10,10,10,10,10,10,10]
		    usertop.init('suptop',json,lines,colors)
		})
	    },

	    refresh: function() {
		this.load({page:'jtop',playtype:ledokol.playtype,rate_type:ledokol.rate_type,rate_period:ledokol.rate_period,rate_author:ledokol.rate_author,ac:mr()})
	    },

	    /**
	     * Скачивание трека
	     */
	    download: function() {

    		//$('.downloadtop').show();
    		//$('.downloadtop').click(function(){alert('download something')});
	    },
	    /**
	     * Заполнение массива местоположения по линиям
	     */
	    getLines: function() {
		var alines=[0], line=1, tpos=0, pl=this.lines.length, u=this.users.length
		for (i=1;i<=pl;i++) {
		    tpos += this.lines[i-1]
		    alines.push(tpos)
		}
		for (i=0;i<u;i++) {
		    var f = 0;
		    for (var j=1;j<=pl;j++) {
			if (alines[j-1] >= i+1) {
			    this.users[i].l = j-1
			    f = 1
			    break
			}
		    }
		    if (!f) this.users[i].l=pl
		}
	    },

	    /**
	     * Определение ширины блока
	     *
	     * @param int it - индекс в массиве
	     * @return int ширина блока, px
	     */
	    getWidth: function(it) {
		var l = this.users[it].l
		if (it==0 || l != this.users[it-1].l) {
		    this.cwidth = Math.floor((this.width-this.lines[l-1]*2)/this.lines[l-1])
		    this.hlines.push(this.cwidth)
		    this.correct = this.width - (this.cwidth+2)*this.lines[l-1]
		}
		if (this.correct) {
		    this.correct--
		    return this.cwidth + 1
		}
		return this.cwidth
	    },

	    /**
	     * Изменение размера топа
	     * (размеры определяются размером окна)
	     *
	     * @return void
	     */
	    resizeIt: function() {
		if (this.width == $(window).width()) return;
		this.width = $(window).width();
		if( navigator.platform.indexOf('Mac') != -1 )
		    this.width = $(window).width()
		this.hlines = []
		this.correct = 0
		var i=0
		$('#'+this.id+' > .tUser').each(function(){
		    this.style.width = usertop.getWidth(i)+'px'
		    this.style.height = usertop.hlines[usertop.users[i].l-1]+'px'
		    i++
		})
		if (this.width != $('#'+this.id).width()) this.resizeIt()
		$('#'+this.id).width(this.width)
		this.resizeFonts()
	    },

	    /**
	     * Масштабирование шрифтов
	     *
	     * @return void
	     */
	    resizeFonts: function() {
		var i=c_l=h=0, _l, _c
		$('#'+this.id+' > .tUser > .tInfo').each(function(){
		    if (c_l != usertop.users[i].l) {
			h = Math.floor(0.18*usertop.hlines[usertop.users[i].l-1]);
			c_l = usertop.users[i].l
		    }
		    _l = usertop.users[i].n.length; _c = (_l<9) ?  1 : 9/_l
		    __font=Math.floor(_c*h)
		    this.style.fontSize =this.style.lineHeight=[__font,'px'].join('')
		    this.style.paddingTop=[Math.floor(parseInt(this.parentNode.style.height)/2-__font+__font/2),'px'].join('')
		    i++
		});
		i=0; c_l=0;
		$('#'+this.id+' .tSub2').each(function(){
		    if (c_l != usertop.users[i].l) {
			h = Math.floor(0.07*usertop.hlines[usertop.users[i].l-1])
			c_l = usertop.users[i].l
		    }
		    if (h < 6)
			this.style.display = 'none'
		    else
			this.style.fontSize = (h > 28) ? '28px' : [h,'px'].join('')
		    i++
		})
		i=0; c_l=0;
		$('#'+this.id+' .tSub').each(function(){
		    if (c_l != usertop.users[i].l) {
			h = Math.floor(0.11*usertop.hlines[usertop.users[i].l-1])
			c_l = usertop.users[i].l
		    }
		    if (h < 5)
			this.style.display = 'none'
		    else
			this.style.fontSize = (h > 28) ? '28px' : [h,'px'].join('')
		    i++
		})
	    },

	    /**
	     * Инициализация данных
	     *
	     * @param array - входящий массив данных
	     * @return void
	     */
	    init: function (id,param,lines,colors) {
		this.unbindTop()
		$('#'+id).empty()
		this.create(id,param,lines,colors)
	    },

	    /**
	     * Update top position
	     *
	     * @param array -
	     * @return void
	     */
	    update: function (param) {
		var u = this.users.length;
		for (var i=0;i<u;i++) {
		    if (this.users[i].p==param[0]) {
			this.users[i].r=param[1]
			this.users[i].s=param[2]
			$('#'+param[0]+'_u .tSub').text(param[1])
    			break
		    }
		}
	    },

	    /**
	     * Binding events on top
	     */
	    bindTop: function() {
		$('#suptop')
		    .mousemove(function(e) {
			if (e.target.className=='tInfo') {
			    var pN= e.target.parentNode, c_ud=$('#suptop').data('c_ud')
			    if (c_ud == pN.id) return
			    usertop.cl_flag=0
			    if (c_ud!=null) $('#'+c_ud).removeClass('aUser')
			    $(pN).addClass('aUser')
			    $('#suptop').data('c_ud',pN.id)
			}
			e.stopPropagation()
		    })
		    .click(function(e) {
			if (user.id == 0) {
			    helper.s('newupload',0)
			    PathDispatcher('authorize', 0, 0)
			}
		    })
 		    .dblclick(function(e) {
			if ($(e.target).is('img')) {
			    var pN2=e.target.parentNode
			    if (user.id != 0) {
				if (usertop.users[$('#'+usertop.id+' .tUser').index($(pN2))].i == user.id) {
				    tempInfo('Вы можете прослушать свои треки в плейлисте', 1, 'i')
				    return
				}
				__pl=parseInt($(pN2).attr('id'))
				if (__pl==track.plist && !ledokol.endtrack) {
				    ledokol.logicGo()
				} else {
				    ledokol.getPlaylistUser(usertop.users[$('#'+usertop.id+' .tUser').index($(pN2))].p, __pl)
				}
			    }
			}
			e.stopPropagation()
		    })
	    },

	    /**
	     * Unbinding top envents
	     */
	    unbindTop: function() {
		$('#suptop').unbind('mousemove');
		if ($('#suptop').data('c_ud')!=null) $('#'+$('#suptop').data('c_ud')).unbind('click')
	    },

	    /**
	     * Hide top
	     */
	    hide: function() {
		$('#'+this.id).hide()
		this.visible = false
	    },

	    /**
	     * Show top
	     */
	    show: function() {
		$('#'+this.id).show()
		this.visible = true
		this.resizeIt()
	    }
}

/**
 * Playlist object
 */
playlist = { id:'plists',
	     playlists:[],
	     cplaylist:-1,
	     tracks:[],
	     trash:[],
	     visible:false,
	     isdrag:0,
	     sortflag:'track_date',
	     sortflow:'desc',
	     view:'playlist',
	     c_pl:null,
	     c_tr:null,
	     seek_wait:5,
	     init_playlist:0,//устанавливаем плейлист, который будет отображаться при старте
	     create: function(plists) {
		 this.createAvatars()
		 this.createPlaylist(0)
		 this.sTop=$('#usertitle').height()+3
		 $(window).scroll(function() { playlist.scrollIt() })
	     },

	     clear: function() {
		 this.playlists=[]
		 this.tracks=[]
	     },

             createAvatars: function() {
		 $('#alist').remove()
		 var _w='width:100%', ml=['<div id="alist">']
		 for (i=0,l = this.playlists.length;i<l;i++) {
		     ml.push(['<div class="ablock',
			     (this.cplaylist==i) ? ' aact' : '',
			     (l>=3) ? ' half' : '',
			     '" id="',
			     this.playlists[i].id,
			     '_a">',
			     '<img class="avlist" src="/avatars/',
			     (this.playlists[i].avatar>0) ? this.playlists[i].id : '0',
			     '?',
			     mr(),
			     '">',
			     f_divcl(this.playlists[i].name,'aname'),
 			     '</div>'].join(''))
		 }
		 //remove button 'Создать плейлист'
		 /*ml.push([f_cboth(),
			  f_button(Lm.g('Add_playlist'), 'PathDispatcher(\'pledit\',4,0)',_w),
			  '<div>'].join(''))*/
		 $('#'+this.id).append(ml.join(''))
		 this.bindAvatars()
	     },

             createPlaylist: function(idx) {
		 $('#mpllist').remove()
		 var _pl=this.playlists.length, _s, p, i=0, j=0, _tl, l, _cpl, _time=0
		 var ml=['<div id="mpllist">',
			 '<div class="mplheader">',
			 f_divcl('N','lnumt header'),
			 f_divcl(Lm.g('Name2'),'lname header'),
			 f_divcl(Lm.g('Artist'),'lart header'),
			 f_divcl(Lm.g('Rating'),'lrate header'),
			 f_divcl(Lm.g('Date'),'ldate header'),
			 f_divcl(Lm.g('Saler'),'lsell header'),
			 f_divcl('Kbps','lkbps  header'),
			 '</div>']
		 for (j=0;j<_pl;j++) {
		     _cpl=(this.view=='playlist') ? this.tracks[idx] : this.tracks[j]
		     if (_cpl==null && this.view=='playlist') return
		     if (_cpl==null && this.view=='trash') continue
		     l=_cpl.length
		     for(el in _cpl) {
			 _tl=_cpl[el]
			 if ((this.view=='playlist' && _tl.del=='1') || (this.view!='playlist' && _tl.del!='1')) continue
			 if (this.view!='playlist' && _tl.del=='1') this.trash.push(_tl);
			 ml.push(['<div class="mplline" id="',
				  _tl.id,
				  '_t">',
				  f_divcl('&nbsp;','send_track'),
				  f_divcl('&nbsp;','ed'),
				  f_divcl(++i+'.','lnum'),
				  f_divcl((_tl.name.length>0) ? _tl.name.replace(/\\(['"])+/gi, '$1') : '&nbsp;','lname'),
				  f_divcl((_tl.artist.length>0) ? _tl.artist.replace(/\\(['"])+/gi, '$1') : '&nbsp;','lart'),
				  f_divcl(_tl.rating_play+((_tl.rating_sell>0) ? [' [',_tl.rating_sell,']'].join('') : ''),'lrate'),
				  f_divcl(_tl.date+((_tl.days>0) ? [' [',_tl.days,']'].join('') : ''),'ldate'),
				  f_divcl((_tl.init_user!=0) ? _tl.init_user : '&nbsp;','lsell'),
				  f_divcl(_tl.bitrate,'lkbps'),
				  '</div>'].join(''))
			 _time+=parseInt(_tl.sectime)
		     }
		     if (this.view=='playlist') {
			 ml.push(['<div class="mpltime">Общее время плейлиста: ',
				  secondsToTimeStr(_time),
				  '</div>'].join(''))
			 break
		     }
		 }
		 ml.push('</div>')
		 $('#'+playlist.id).append(ml.join(''))
		 $('.mplline').bind('selectstart', function(){ return false })
		 delete(ml)
		 this.cplaylist=idx
		 this.bindPlaylist(idx)
	     },

             changePlaylist: function(idx) {
		 if (typeof idx == 'undefined' || idx == -1) idx=0
		 $('#'+this.playlists[this.cplaylist].id+'_a').removeClass('aact')
		 $('#'+this.playlists[idx].id+'_a').addClass('aact')
		 this.unbindPlaylist()
		 this.createPlaylist(idx)
		 this.cplaylist=idx
		 this.bindPlaylist()
		 $(document).scrollTop(0)
	     },

             init: function(_pl) {
		 for (i=0,l=_pl.length;i<l;i++) {
		     this.playlists.push({id:_pl[i].id,name:_pl[i].name,rating:_pl[i].rating,avatar:_pl[i].avatar});
		     this.tracks.push(_pl[i].tracks);
		 }
		 this.create()
		 playlist.sortflow = (playlist.sortflow=='asc') ? 'desc' : 'asc'
		 playlist.sortIt(playlist.sortflag)
	     },

             jinit: function() {
		 $.getJSON('index.php',{page:'jplists',ac:mr()}, function(j) {
		     playlist.clear()
		     playlist.init(j)
		     var _c=playlist.cplaylist
		     playlist.cplaylist=0

		     //если указан плейлист, который будем открывать по умполчанию
		     for( i=0; i<playlist.playlists.length; i++ ) {
			     if( playlist.playlists[i].id == playlist.init_playlist ) {
			    	 _c = i;
			    	 playlist.cplaylist = _c;
			     }
		     }
		     playlist.changePlaylist(_c)
		 })
	     },

             playTrack: function(id) {
		 var track = this.getTrackPositionsById(id,this.cplaylist)
		 var _t = (track.pl != null) ? this.tracks[track.pl][track.ap].filename : this.tracks[this.cplaylist][0].filename
		 ledokol.getTrackFromPlaylist({id:id,playlist:track.pl,trackpath:['http://93.95.101.79/mp3/',_t,'.mp3'].join(''), avatar:this.tracks[track.pl][track.ap].avatar})
		 this.c_pl=this.cplaylist
		 this.c_tr=id
		 this.bindSlider()
		 return false
	     },

             playNextTrack: function() {
		 // search wheare is current track
		 var curTrackPos = this.getTrackPositionsById(this.c_tr)
		 if (curTrackPos.pl == null) return this.playTrack(this.tracks[this.cplaylist][0].id)
		 // get next track in mod
		 var nextTrackAbsPos = this.getTrackAbsolutePosition(curTrackPos.mp+1, curTrackPos.pl)
		 this.playTrack(this.tracks[curTrackPos.pl][nextTrackAbsPos].id)
	     },

             /**
	      * Playlist resize
	      */
             resizeIt: function() {
		 //
	     },

  	     /**
	      * Fonts resize
	      */
             resizeFonts: function() {
		 //
	     },

	     bindAvatars: function() {
	       $('.ablock')
		     .mouseenter(function() { this.className=[this.className,' ahover'].join('') })
		     .mouseleave(function() { this.className=this.className.replace(/ ahover/g, '') })
		     .click(function(e) {
			 var c_i = $('#alist .ablock').index($(this))
			 if (e.target.className != 'aname') {
			     playlist.view='playlist'
			     playlist.changePlaylist(c_i)
			 } else
			     PathDispatcher('pledit',0, c_i)
		     })
	     },

             bindPlaylist: function() {
		 $('.lname, .lart, .lrate, .ldate, .lsell, .lkbps','.mplheader')
		     .mouseenter(function() { this.style.backgroundColor='#6f6f6f'; this.style.cursor='pointer' })
		     .mouseleave(function() { this.style.backgroundColor='' })
		     .click(function() {
			 var __hflag=0
  			 switch (this.className) {
			 case 'lname header': __hflag='name'; break
			 case 'lart header': __hflag='artist'; break
			 case 'lrate header': __hflag='rating_play'; break
			 case 'ldate header': __hflag='track_date'; break
 			 case 'lsell header': __hflag='init_user'; break
 			 case 'lkbps header': __hflag='bitrate'; break
			 }
			 if (__hflag) {
			     playlist.sortIt(__hflag)
			     return false
			 }
		     })

		 $('.mplline', '#mpllist')
		     .mouseenter(function() {
			 if (this.className == 'mplline') this.className='mplline mpl_hover';
			 if (this.className == 'mpllineact') this.className='mpllineact mpl_hover'})
		     .mouseleave(function() {
			 if (this.className == 'mplline mpl_hover') this.className='mplline';
			 if (this.className == 'mpllineact mpl_hover') this.className='mpllineact'})
		     .mousedown(function(e) {
			 if (playlist.isdrag) { $(document).trigger('mouseup'); return false }
			 playlist.objDOM=this;
			 var ledX=e.pageX-$(this).offset().left;
			 var ledY=e.pageY-$(this).offset().top;
			 $(document)
			     .mouseup(function(e) {
				 $(this).unbind('mousemove').unbind('mouseup');
				 $('#backdiv').hide();
				 var c_idx = $(['#',playlist.id,' .mplline, #',playlist.id,' .mpllineact, #',playlist.id,' .dragline'].join('')).index($(playlist.objDOM));
				 var absPos = playlist.getTrackAbsolutePosition(c_idx,(playlist.view!='trash')?playlist.cplaylist:null);
				 if (!playlist.isdrag) { // it's click :)
				     switch (e.target.className) {
				     case 'ed': PathDispatcher('trackinfo', 0, c_idx); break;
				     case 'send_track': PathDispatcher('sendmail', 0, parseInt($(playlist.objDOM).attr('id'))); break;
				     //case 'lrate': PathDispatcher( 'money', 5, parseInt($(playlist.objDOM).attr('id'))); break;
				     default: playlist.playTrack(parseInt($(playlist.objDOM).attr('id')));
				     }
				 } else {
				     playlist.isdrag=0;
				     if (playlist.c_ava=='trash') {
					 PathDispatcher('trackinfo',1,absPos);
				     } else if (playlist.c_ava!==false) {
					 if (playlist.c_ava == playlist.cplaylist && playlist.tracks[((playlist.view!='trash')?playlist.cplaylist:absPos.p)][((playlist.view!='trash')?absPos:absPos.ap)].del != 1) {
					     tempInfo('Трек нельзя переместить в текущий плейлист', 1, 'i');
					     if (playlist.objDOM.className == 'mplline dragline') playlist.objDOM.className='mplline';
					     if (playlist.objDOM.className == 'mpllineact dragline') playlist.objDOM.className='mpllineact'
					 } else
					     playlist.moveTrack(absPos, playlist.c_ava)
				     } else {
					 if (playlist.objDOM.className == 'mplline dragline') playlist.objDOM.className='mplline';
					 if (playlist.objDOM.className == 'mpllineact dragline') playlist.objDOM.className='mpllineact'
				     }
				 }
				 return false})
			     .mousemove(function(e) {
				 return false
			     })
		     })
		 this.bindSlider()
	     },

             scrollIt: function() {
		 $('#alist').stop().animate({top:[$(window).scrollTop()+this.sTop,'px'].join('')},500)
	     },

             moveDragTrack: function( track_id, playlist_to, playlist_from ) {
		 $.getJSON('/index.php', {page:'move_track', track:track_id, playlist:playlist_to, old_playlist:playlist_from,ac:mr()}, function(j) {
		     (j.s) ? playlist.jinit() : tempInfo('Ошибка перемещения трека',2,'w')
		 })
	     },

             moveTrack: function(idx,pl) {
		 var o = {}
		 if (typeof idx != 'object') {
		     o.ap = idx
		     o.p = this.cplaylist
		 } else
		     o = idx
		 $.getJSON('/index.php', {page:'move_track', track:this.tracks[o.p][o.ap].id, playlist:this.playlists[pl].id, old_playlist:this.playlists[o.p].id,ac:mr()}, function(j) {
		     (j.s) ? playlist.jinit() : tempInfo('Ошибка перемещения трека',2,'w')
		 })
	     },

             sortIt: function(sflag) {
		 if (typeof this.tracks =='undefined' || !this.tracks.length || typeof this.tracks[this.cplaylist] == 'undefined') return
		 var flow = (this.sortflag != sflag) ? 'asc' : ((this.sortflow=='desc') ? 'asc' : 'desc')
		 this.tracks[this.cplaylist].sort(function(a,b) {
		     if (sflag=='rating_play') {
			 return a[sflag]-b[sflag]
		     } else if (sflag=='name' || sflag=='artist' || sflag=='init_user') {
		    	 var _s1=new String(a[sflag]), _s11=_s1.toLowerCase(), _s2=new String(b[sflag]), _s22=_s2.toLowerCase()
		    	 return _s11.localeCompare(_s22)
		     } else {
			 return (a[sflag] > b[sflag]) ? 1 : -1
		     }
		 })
		 if (flow=='desc') this.tracks[this.cplaylist].reverse()
		 this.sortflow = flow
		 this.sortflag = sflag
		 this.unbindPlaylist()
		 var _p=this.cplaylist
		 this.cplaylist=-1
		 this.createPlaylist(_p)
	     },

             unbindPlaylist: function() {
		 $('.mplheader .lname, #mpllist .mplline').unbind()
	     },

             autoMoveSlider: function(proc) {
		 if (this.isSdrag) return;
		 if (this.seek_wait) { this.seek_wait--; return }
		 this.seek_wait=5;
		 var trackLine = $('#'+track.id+'_t .lname'), s2 = $('em.tslider2', trackLine), offset = Math.round(proc*(trackLine.width()-s2.width())/100);
		 if (s2.length) s2.css({'left':  offset + 'px'})
	     },

             unbindSlider: function() {
		 $('#tslider').unbind().remove() /* new slider no need to remove */
	     },

             bindSlider: function(){
		 if (track.id != this.c_tr
		     && this.cplaylist != this.c_pl
		     && ledokol.playsource != 'similar'
		     && ledokol.playsource != 'preplay') return
		 var trackLine = $(['#',track.id,'_t'].join(''))
		 trackLine.parent().children('.mpllineact').children('.lname').children('.tslider2').remove()
		 trackLine.parent().children('.mpllineact').each(function() { this.className='mplline' })
		 trackLine.attr('class','mpllineact')
		 var t = trackLine.children('.lname'), s=$(['#tslider_',track.id].join(''),t)
		 if (!s.length)
		     trackLine.children('.lname').append(['<em class="tslider2" id="tslider_',track.id,'"></em>'].join(''))
		 else
		     s.unbind()
		 s = $(['#tslider_',track.id].join(''),t)
		 s.css({left:0})
		 s.mousedown( function() {
		     playlist.isSdrag=1
		     $('#backdiv').css({'z-index':s.css('z-index')-1,'height':[$(window).height(),'px'].join('')}).show()
		     $(document)
		       .mouseup(function() {
			   soundManager.setPosition(ledokol.smID,Math.round(track.duration*parseFloat(s.css('left'))/t.width()))
			   playlist.isSdrag=0
			   $(this).unbind('mousemove').unbind('mouseup')
			   $('#backdiv').hide()
			   return false })
		       .mousemove(function(e) {
			   if ($.browser.msie && !e.button) { $(document).trigger('mouseup'); return false }
			   var to = t.offset()
	        	   if (e.pageX > to.left && e.pageX < to.left+t.width() && e.pageY > to.top-5 && e.pageY < to.top+t.height()+5)
		               s.css('left',[e.pageX-to.left-s.width()/2,'px'].join(''))
	        	   else
	        	       $(this).trigger('mouseup')
			   return false
	               })
		     return false
		 }).mousemove(function() { return false })
	   },

           getTrash: function () {
	       this.trash=[]
	       this.view='trash'
	       this.changePlaylist(0)
	   },

           hide: function() {
	       this.visible = false
	       $("#plists").hide()
	       this.unbindSlider()
	       $('#usertitle_my_radio').unbind('click').hide()
	   },

           show: function() {
	       this.visible = true
	       $("#plists").show()
	       this.bindSlider()
	       $('#usertitle_my_radio').show()
	       this.bindRadio()
	   },

           bindRadio: function() {
	       $('#usertitle_my_radio').bind('click', function(){
		   if (ledokol.is_radio==0) {
		       if (ledokol.playsource!="playlist") ledokol.finishState()
		       ledokol.playsource='playlist'
		       ledokol.blinkRadio()

		   } else
		       ledokol.unblinkRadio()
	       })
	   },

           /**
	    * Получаем абсолютную позицию трека в плейлисте по его индексу в текущем режиме(корзина|плейлист)
	    */
           getTrackAbsolutePosition: function(trackInModId, _pll){
	       var absCounter = counter = p = 0, _flag = false, rv={p:null,ap:null}, mod=(this.view=='trash') ? 1 : 0
	       for (var pl=0,l=this.playlists.length;pl<l;pl++) {
		   p=pl
		   if (typeof _pll != 'undefined' && _pll != null ) {
		       if (pl!=_pll) continue // switch for request playlist
		   }
		   if (this.tracks[pl] != null)
		       for (var t in this.tracks[pl]) {
			   if (counter == trackInModId && this.tracks[pl][t].del==mod) { _flag=true; break }  // second rule need to 0 node
			   counter += (this.tracks[pl][t].del==mod) ? 1 :0
			   absCounter++
		       }
		   if (_flag) break
		   absCounter=0 // for new playlist set start absolute position to 0
	       }
	       if (typeof _pll != 'undefined' && _pll != null)
		   return absCounter
	       else {
		   rv.p = p
		   rv.ap = absCounter
		   return rv
	       }
	   },

           /**
	    * Получаем позиции трека по его id
	    * необязательный параметр pll - искать в определенном плейлисте
	    * return.pl - плейлист в котором находится трек
	    * return.mp - mod position - позиция трека с учетом в корзине он или в плейлисте
	    * return.ap - абсолютная позиция трека в плейлисте
	    */
           getTrackPositionsById: function(id, pll){
	       var _pos = {pl:null,mp:0,ap:0}, _flag=0, mod=(playlist.view=='trash') ? 1 : 0
	       if (typeof pll=='undefined') pll=0
	       for (i=pll,l=this.playlists.length;i<l;i++) {
		   if (this.tracks[i] != null) // for empty playlists
		       for (j=0;j<this.tracks[i].length;j++) {
			   if (this.tracks[i][j].id==id) { _pos.pl=i; _flag=1; break }
			   _pos.mp += (this.tracks[i][j].del==mod) ? 1 : 0
			   _pos.ap++
		       }
		   if (_flag) break
		   _pos.mp=_pos.ap=0
	       }
	       return _pos
	   }
}

community = { users:[],
	      users_me:[],
	      users_tmp:[],
	      messages:[],
	      lines : [3,5,8,12,18,24,30],
	      colors : ['#999','#bbb','#ccc','#ddd','#eee'],
	      width : $('#community').width(),
	      height : $('#community').height(),
	      visible : true,
	      hlines : [],
	      correct : 0,
	      show : 'i',
	      bf:0,
	      init: function() {
		  $.getJSON('index.php',{page:'getcontacts2'}, function(j) {
			  community.show = 'me';
		      $('#community').empty();
		      community.users=j.i;
		      community.users_me=j.me;
		      community.create();
		  })
		  $('#usertitle_announce').show()
	      },

	      create: function() {
		  var dl = [];
		  /*dl.push('<div style="float:left">');
		  dl.push(f_case('Меня слушают','listen_me', 'listen_me miniradio',''));
		  dl.push('</div><div style="float:left">');
		  dl.push(f_case('Я слушаю','listen_by_me', 'listen_by_me miniradio',''));
		  dl.push('</div>');*/

		  dl.push('<div class="mpllist" style="width:100%;max-height:400px;overflow-y:auto;overflow-x:hidden;z-index:250">');
		  var prev = 1;
		  for( j in this.users ) {
		      var height = "19px";
		      var mtop = "-30px";
		      var color= "color: gray;";
		      if( this.users[j].o == 1 )
		    	  color= "";

		      if( this.users[j].o == 0 && prev == 1 ) {
		    	  dl.push('<div class="mplline" style="height:19px;border:none;padding:0 4px 0 2px;text-align:center">');
		    	  dl.push("-------Оффлайн--------");
		    	  dl.push('</div>');
		      }
		      prev = this.users[j].o;
		      dl.push('<div class="mplline" style="height:'+height+';border:none;padding:0 4px 0 2px;">');
		      dl.push('<div id="name'+this.users[j].i+'" onclick="community.click(\''+this.users[j].n+'\')" onmouseout="community.mouseout('+this.users[j].i+')" onmouseover="community.mouseover('+this.users[j].i+')" style="border:none;font-size:16px;float:left;'+color+'">'+this.users[j].n+'</div>');
		      dl.push('<div style="float:left;padding-left:5px;padding-top:1px" onclick="community.send(\''+this.users[j].e+'\');"><img src="/img/email.png"></div>');
		      if( this.users[j].v != "" ) {
		    	  dl.push('<div style="float:left; padding-left:4px"><a target="_blank" href="'+this.users[j].v+'"><img border=0 src="/img/vk_icon.png"></a></div>');
		      }
		      if( this.users[j].sk != "" ) {
		    	  dl.push('<div style="float:left; padding-left:4px"><a target="_blank" href="callto:'+this.users[j].sk+'"><img border=0 src="/img/SkypeBlue_16x16.png"></a></div>');
		      }
		      dl.push('<div style="text-align:right; padding-right:5px;">'+this.users[j].cnt+'</div>');
		      dl.push('</div>');
		      //dl.push('<div style="-moz-border-radius: 10px; -webkit-border-radius: 10px;-khtml-border-radius: 10px;border-radius: 10px;border:5px solid #F8C301;position:absolute; display:none;" id="ava'+this.users[j].i+'"><img style="width:100px" src="/avatars/'+this.users[j].a+'"></div>');
		      dl.push('<div class="rounded" id="ava'+this.users[j].i+'"><img style="background-color:green; width:100px" src="/avatars/'+this.users[j].a+'?'+Math.floor(Math.random()*10000000)+'"></div>');
		  }
		  dl.push('</div>');
		  viewInfo( 'Комьюнити', dl.join(''), 0, '', 'commun', 260);
		  $('#w_commun').css({top:$('#usertitle_messages').position().top + 30+'px', left:$('#usertitle_messages').position().left-50+'px'});
		  /*$('#listen_me').attr('src', '/img/radio_w_on.gif');

		  $('#listen_me').live('click', function(){community.exchange('me')});
		  $('#listen_by_me').live('click', function(){community.exchange('i')});*/
	      },

	      click: function(nick) {
		  $.getJSON('index.php',{page:'gett', search:nick, type:'nick'}, function(j) {
		      if (j.s==1) {
			  closeW('vwindow');
    			  track.id = j.trackid;
    			  track.path = j.trackpath;
    			  track.u_id = j.userid;
    			  track.u_name = j.user;
    			  track.u_avatar = j.avatar;
			  ledokol.stopSignal();
			  ledokol.playsource='go';
    			  ledokol.initTrackInfo();
    			  ledokol.playTrack()
    		      } else {
    			  tempInfo('Вы прослушали все треки игрока ' + j.user, 3,'i')
		      }
		  });
	      },
	      exchange:function( t ) {

			if( t != this.show ) {
				this.users_tmp = this.users;
				this.users = this.users_me;
				this.users_me = this.users_tmp;
				this.create();
				this.show = t;
			}
			if( t=='i' ) {
				$('#listen_by_me').attr('src', '/img/radio_w_on.gif');
				$('#listen_me').attr('src', '/img/radio_w_off.gif');
			} else {
				$('#listen_by_me').attr('src', '/img/radio_w_off.gif');
				$('#listen_me').attr('src', '/img/radio_w_on.gif');
			}
	      },
	      mouseover: function(id) {
		  $('#ava'+id).css({top:$('#name'+id).position().top - 20 + 'px', left:$('#name'+id).position().left - 130 + 'px'})
		  $('#ava'+id).fadeTo(1000, 1)
	      },

	      mouseout: function(id) {
		  $('#ava'+id).hide()
	      },

	      send: function(email) {
		  var c_p='width:10em'
		  var _s=[f_fstart('commSend', 'index.php', 'post'),
			  f_hidden('page', 'commSend'),
			  f_hidden('email', email),
			  f_label('Тема: ', 'width:4em'),
			  '<input type="text" name="subject" class="input" style="width:190px">',
			  f_label('Текст: ', 'width:4em'),
			  f_param(f_textarea('text','','','width:190px;height:130px'),''),
			  '<br>',
			  f_fend(),
			  f_cboth(),
			  f_dbuttons(f_button('Отправить', 'community.sendPost();', 'width:7em'))].join('')
		  viewInfo('Сообщение', _s, 0);
	      },

	      sendPost: function() {
		  $('#commSend').ajaxSubmit({dataType:'json', success:function(j) {
		      $('#w_vwindow').remove()
		      viewInfo('Сообщение отправлено', 'Спасибо, Ваше сообщение отправлено')
		  }})
	      },

	      hide: function() {
		$('#community').hide()
		$('#usertitle_announce').hide()
	      },

	      show: function() {
		  $('#community').show()
	      }
}

/**
 * Pre-view player
 */
preplayer = { is_play: false,

	      test: function(param) {
		  var _s = this.print(param)
		  viewInfo( '1', _s, 0, 'javascript:void(0)', 'testplayer')
		  $('#pre'+param.trackid).unbind('click').bind('click',function() { preplayer.play(preplayer.p);return false })
	      },

	      play: function(param) {
		  $('#pre'+param.trackid).unbind('click').bind('click',function() { preplayer.stop(preplayer.p);return false })
		  $('#pre'+param.trackid+' img').attr('src','/img/stop1.gif')
		  ledokol.stopSignal()
		  ledokol.stopTrack()
		  track.init({id:param.trackid,plist:0,path:param.trackpath,u_id:user.id,u_name:user.name,u_avatar:0,code:0,bitrate:0,duration:0,playtime:0,byauth:0})
		  ledokol.initTrackInfo()
		  ledokol.playsource="preview"
		  playlist.c_tr=param.trackid
		  playlist.c_pl=0
		  playlist.cplaylist=0
		  playlist.bindSlider()
		  ledokol.playTrack(track.path)
	      },

	      stop: function() {
		  $('#pre'+preplayer.p.trackid).unbind('click').bind('click',function() { preplayer.play(preplayer.p);return false })
		  $('#pre'+preplayer.p.trackid+' img').attr('src','/img/play1.gif')
		  ledokol.stopTrack()
	      },

	      print: function(param) {
		  preplayer.p={trackid:param.trackid, trackpath:param.trackpath}
		  return ['<a href="#" id="pre'+param.trackid+'">',
			  '<img src="img/play1.gif" style="float:left;margin:3px">',
			  '</a>',
			  '<div id="',
			  param.trackid,
			  '_t" class="mpllineact" style="clear:none;width:90%"><div class="lname" style="width:100%">',
			  param.trackname,
			  '</div>',
			  '</div>'].join('')
	      }

}



