"use strict"


var mobmusic; // id for audio element
var js_mob_audio_tag_track; // audio element track src
var duration = 0; // Duration of audio clip

var pButton; // jquery play button

var not_play_next_rewind_button = 'stop';
var playhead;

// timeline width adjusted for playhead
var timelineWidth;

var timeline;

var desktop_host = DESKTOP_DOMAIN_NAME;
var music_pth = desktop_host+'/music/mp3Files/';

var current_track_index;
var tracks_db = [];
var default_url = window.location.href;
var global_max_player;
document.addEventListener("DOMContentLoaded", function(event) {
mobmusic = ga('#mobmusic')[0]; // id for audio element	
js_mob_audio_tag_track = ga('.mobmusic-track-source')[0];	


});

// Boolean value so that audio position is updated only when the playhead is released
var onplayhead = false;
function getTrackCover(cvr){
	
	if(cvr.indexOf('mp3_covers') > -1){
		
		return desktop_host+'/'+cvr;
		
	} else {
	
		return cvr;
		
	}
	
}
function mmPlay(el,ev){
	
ev.preventDefault();
 
	var _this = ga(el),
		_track_info = _this.data('track-inf') ? _this.data('track-inf') : _this.data('mob-track');
 
 var is__outside = _this.data('track-inf') ? true : false;
 
		 if(is__outside){
	 
				_track_info.time = '';
				 
		}
 
 if(ga('ul.music_track_lst').length) {
	tracks_db = [];
 
	ga('ul.music_track_lst').children().each(function(){
		var $this = ga(this);
		
		
		
		tracks_db.push($this.find('button.pButton'));
		 
	});
	 
 }
 
 		 if(is__outside && _track_info.id !=  js_mob_audio_tag_track.id){
	 
				 
				ga('.commentsWidgetTracks .track_timeline').remove();
				ga('.commentsWidgetTracks .m_portal_track_pause').removeClass('m_portal_track_pause');
		}	
		
		if(is__outside){
			ga('.m_portal_track_pause').removeClass('m_portal_track_pause');
			ga('.track_timeline').remove();
			_this.addClass('m_portal_track_pause');
		}
	// pause this track	
	if( _track_info.id ===  js_mob_audio_tag_track.id && _this.closest('li').hasClass('__playing')){
	// close recent playing track
	_this.closest('li').removeClass('__playing').addClass('__paused');
	 
		 mobmusic.pause();
		 ga(mobmusic).addClass('paused');
		if(is__outside){
			_this.removeClass('m_portal_track_pause');
		}
	} 
	
	// paused track, play next
	else if (_this.closest('li').hasClass('__paused'))
	{
		_this.closest('li').removeClass('__paused').addClass('__playing');
		 
		mobmusic.play();
		ga(mobmusic).removeClass('paused');
		
	} 
	// load another track
	else

		{
		ga('.music_track_i').removeClass('__playing __paused').closest('li').removeClass('__selected');
		ga('.__playing,.__paused').removeClass('__playing __paused');
		ga('.music_track_i').find('.track_timeline').remove();
		ga(mobmusic).removeClass('paused');
		ga('.glyphicon-play.glbminpl_btn_play_pause').addClass('playing');
		
		var track_timeline_markup = '<div class="track_timeline">\
				<div class="track_playhead"></div>\
				<div class="mobmus-seekbar"></div>\
				<div class="mobmus-buffbar"></div>\
					</div>'
		
		
		
		if(!_this.find('.track_timeline').length && !is__outside)
		_this.closest('li').append(track_timeline_markup);
		else
			_this.parent().append(track_timeline_markup);
        // remove pause, add play
         _this.closest('li').addClass('__playing __selected');
		js_mob_audio_tag_track.src = music_pth + _track_info.file;
		js_mob_audio_tag_track.id = _track_info.id;
		//ga('#mobmusic-track').removeAttr('src').attr({'id':_track_info.id,'src': music_pth + _track_info.file});	
		 ga(mobmusic).removeAttr('track-cover').attr('track-cover',getTrackCover(_track_info.cover));

		 var artist_name = decodeUrlEncode(_track_info.artist);
		 var track_title = decodeUrlEncode(_track_info.track_name);
		 var track_album = decodeUrlEncode(_track_info.album_name);
		 
		 
		 
		 if (not_play_next_rewind_button == 'stop') {
		 var $body = ga('body');
		 $body.find('#background_track_play').remove();
 
 
		 $body.append('<div id="background_track_play" class="global_bg_track_play fixed_always">\
		 <div id="global_min_player-max" class="global_min_player_maximized"></div>\
		 <div class="hookData _0 global_min_player_json_dt"><!--{"id":"'+_track_info.id+'","time":"'+_track_info.time+'","cover":"'+_track_info.cover+'","artist":"'+artist_name+'","track":"'+track_title+'","album":"'+track_album+'"}--></div>\
		 <div class="global_track_play_img"><div class="global_track_ovr_play"></div><div class="global_play_btn_track"></div><div class="global_min_player-covers"><div class="track_glob_play_cover" style="background-image:url('+getTrackCover(_track_info.cover)+')"></div><div class="global-min-player-placeholder mob-audio-placeholder"></div></div></div></div>');
		 not_play_next_rewind_button = 'stop';
		 
		 
		 
		if(is__outside){
		 
		 ga('#background_track_play').fadeIn();
		}
		 
		 
		 } else {   
		 
					// set the new track's title to global mini player
					ga('.glbminpl_song_txt').html(artist_name+' - '+track_title);
					ga('.glbminpl_album_name').html(track_album);
					ga('.glbminpl_cover').css('background-image','url('+getTrackCover(_track_info.cover)+')');
					ga('#glbminpl_track_time').html( _track_info.time );
					ga('#global_min_player_add_song').show().removeAttr('onclick').attr("onclick","addTrack('pm_sec_add_"+_track_info.id+"');");
					ga('#mus_global_song_added').remove();
			 
		 }
		 
		 current_track_index = _this.closest('li').index();
		   
		// Gets audio file duration
		mobmusic.addEventListener("canplaythrough", function(e) {
			
			duration = e.target.duration;
			
		}, false);		
/*mobmusic.addEventListener('loadedmetadata', function(e) {
    console.log(e.target.duration); //0
	duration = e.target.duration;
});*/
		 
		 // timeupdate event listener
		mobmusic.addEventListener("timeupdate", function(e){timeUpdate(e,_this);}, false);
		 
		pButton = _this[0];
		timeline = not_play_next_rewind_button != 'stop' ? ga('#global_min_player-max').find('.track_timeline')[0] : _this.closest('li').find('.track_timeline')[0]; // timeline 
		playhead = not_play_next_rewind_button != 'stop' ? ga('#global_min_player-max').find('.track_playhead')[0] : _this.closest('li').find('.track_playhead')[0];
		
		timelineWidth = timeline.offsetWidth - playhead.offsetWidth;
		
 
		
		
		// makes timeline clickable
		timeline.addEventListener( hasTouchStartEvent ? "touchend" : "click", function(event) {
			moveplayhead(event);
		
			mobmusic.currentTime = duration * clickPercent(event);
			
				ga('li.__paused.__selected').removeClass('__paused').addClass('__playing');
				ga('.glyphicon-play.glbminpl_btn_play_pause').addClass('playing');
				mobmusic.play();
			
		}, false);
		
		

		// makes playhead draggable
		playhead.addEventListener( hasTouchStartEvent ? 'touchstart' : 'mousedown', mouseDown, false);
		
		
		window.addEventListener(hasTouchStartEvent ? 'touchend' : 'mouseup', mouseUp, false);



		mobmusic.load();
		mobmusic.play();
		

		
		// buffer
		var mobloop = function() {
			var buffered = mobmusic.buffered;

				if (buffered.length) {
					ga('.mobmus-buffbar').css('width', (100 * buffered.end(0) / duration) + '%');
					
				}

			setTimeout(mobloop, 100);
		}

			mobloop();
		
		
		
	}
}
function playedTime(seconds){

    var minutes = Math.floor(seconds / 60);
    var secs = Math.floor(seconds % 60);

    if (minutes < 10) {
        minutes = minutes;
    }

    if (secs < 10) {
        secs = '0' + secs;
    }

    return minutes +  ':' + secs;
}

// Synchronizes playhead position with current point in audio
function timeUpdate(e,a) {
	duration = e.target.duration;
    var playPercent = timelineWidth * (mobmusic.currentTime / duration);
	//alert(duration);
	
	var song_index = ga(a).closest('li').index();
	
    playhead.style.marginLeft = playPercent + "px";
    
	ga('.mobmus-seekbar').css('width',playPercent + 'px');
	
	ga('.music_track_seek span').html(playedTime(mobmusic.currentTime));
	
	if (mobmusic.currentTime == duration && duration > 0 && a) {
         a.closest('li').removeClass('__playing'); 
		 playNextTrack(song_index);
    }
}

// returns click as decimal (.77) of the total timelineWidth
function clickPercent(event) {
	
    return ( (hasTouchStartEvent ? event.changedTouches[0].clientX : event.clientX) - getPosition(timeline)) / timelineWidth;

}

// getPosition
// Returns elements left position relative to top-left of viewport
function getPosition(el) {
    return el.getBoundingClientRect().left;
}

// mousemove EventListener
// Moves playhead as user drags
function moveplayhead(event) {



var w,q,f,k,n,r;





    var newMargLeft = (hasTouchStartEvent ? event.changedTouches[0].clientX : event.clientX) - getPosition(timeline);

    if (newMargLeft >= 0 && newMargLeft <= timelineWidth) {
        playhead.style.marginLeft = newMargLeft + "px";
		ga('.mobmus-seekbar').css('width',newMargLeft + 'px');
    }
    if (newMargLeft < 0) {
        playhead.style.marginLeft = "0px";
		ga('.mobmus-seekbar').css('width','0px');
    }
    if (newMargLeft > timelineWidth) {
        playhead.style.marginLeft = timelineWidth + "px";
		ga('.mobmus-seekbar').css('width',timelineWidth + 'px');
    }
	
	if( ga('.music_track_seek span').text() == ga('.music_track_time').text()) return;
	
	
                        w = duration * (newMargLeft / timelineWidth);
                        q = Math.floor(w / 60);
                        w = Math.floor(w % 60);

                        if (q >= 60) {
                            f = Math.floor(q / 60);
                            k = q % 60;
                            n = (k < 10 ? "0" : "");
                            k = n + k;
                            q = f + ':' + k;
                        }
						q = q < 0 ? 0 : q;
						w = w < 0 ? 0 : w;


                        r = (q < 10 ? "" : "") + q + ":" + (w < 10 ? "0" : "") + w;
						
						
						
						ga('.music_track_seek span').html(r);
	
}


// mouseDown EventListener
function mouseDown() {
    onplayhead = true;
    window.addEventListener(hasTouchStartEvent ? 'touchmove' : 'mousemove', moveplayhead, true);
    mobmusic.removeEventListener('timeupdate', function(e){timeUpdate(e)}, false);

}

// mouseUp EventListener
// getting input from all mouse clicks
function mouseUp(event) {
    if (onplayhead == true) {
        moveplayhead(event);
        window.removeEventListener(hasTouchStartEvent ? 'touchmove' : 'mousemove', moveplayhead, true);
        // change current time
        mobmusic.currentTime = duration * clickPercent(event);
        mobmusic.addEventListener('timeupdate', function(e){timeUpdate(e)}, false);
		
	ga('li.__paused.__selected').removeClass('__paused').addClass('__playing');
	 ga('.glyphicon-play.glbminpl_btn_play_pause').addClass('playing');
	mobmusic.play();
		
		
    }
    onplayhead = false;
}
function deleteCollection(){
	
	var col_id = ga('#upload_track_in_collection').data('collid');
	
	var send = jAjax('/music.php', 'post', {'cmd':'delete-collection','id':col_id});
	send.done(function(d){
		
		if(d == 1)
			ga('#mus_header_mycol').trigger('click');
		else
			mus_ajax_err('Error! Your playlist was not deleted, please retry.');
	});
	
}
function collectionSet(el,ev){
	ev.stopPropagation();
	ga('.music_track_menu').remove();
	var mobmus_col_actionmenu = '<div class="music_track_menu __open" role="menu">\
								 <a onclick="deleteCollection();" class="fi fi-trsh menu-link" style="text-decoration:none;">\
								 <span class="mob-trash-20"></span><span class="ic_tx">Delete</span></a></div>';
								 
								 
	el = ga(el);
	
	if(	!el.closest('li').find('.music_track_menu').length )
		el.closest('li').append(mobmus_col_actionmenu);
	else el.closest('li').find('.music_track_menu').remove();
		
}
function deleteTrack(id,p){
 
	id = id.match(/\d/g).join("");
	
	 
	 
	var a_d = p ? 'p' : 'm';
	var b = p ? p : 0;
 
	var send = jAjax('/music.php', 'post', {'cmd':'deletesong','d':a_d,'b':b,'track':id});
	
	send.done(function(d){
		
			if(d == 1){
				
				ga('#track_'+id).slideUp(function(){ga(this).remove()});
				
			} else {
				
				mus_ajax_err('An error occured at delete track');
			}
		
	});
	
	
}
function addTrack(id,p,el){
	
	id = id.match(/\d/g).join("");
	
	 
	 
	var b = p ? 'p' : 'm';//!ga('#mus_collection_page').length ? 'm' : 'p';
	var c = p ? p : 0;
	var send = jAjax('/music.php', 'post', {'cmd':'addsong','c':c,'b':b,'track':id});
	
	send.done(function(d){  
		 
			if(b == 'm' && d > 0){
				ga('#mus_header_my_tracks_count').text(d);
				ga('#track_'+id).addClass('added');
				ga('#global_min_player_add_song').hide().after('<span id="mus_global_song_added" class="ic_song_added"></span>');
				ga(el).addClass('ic_added_w __disabled');
			} else {
				 
				mus_ajax_err('An error occured at adding track to your collection.');
			}
		
	});
	
	
}
function mus_ajax_err(str){
	
	
	alert(str);
}
function trackSet(el,ev){
	
	ev.stopPropagation();
	el = ga(el);
	
	var is_collection = ga('.music_album_name').length ? 1 : 0;
	var is_owner_collection = ga('#is_owner').length ? 1 : 0;
	var ext_track = el.data('track-ap'),
	    track_id = ext_track.id,
		track_artist = decodeUrlEncode(ext_track.artist),
		track_title  = decodeUrlEncode(ext_track.track_title);
	
	
	ga('.music_track_menu').remove();
	var mobmus_track_actionmenu =  	is_owner_collection ? '<div class="music_track_menu track __open" role="menu">\
										 <a '+ (is_collection ? 'style="display:none;"' : '') +' class="ic ic-pls menu-link" data-func="menuAdd" role="menuitem"><span class="ic_tx">Add to collection</span></a>\
										 <a style="display:none;" ontouchend="as_status(this,event, \''+escape(track_id)+'\', \''+escape(track_artist)+'\', \''+escape(track_title)+'\');" class="ic ic-horn menu-link" data-func="toStatus" role="menuitem"><span class="ic_tx">Post as status</span></a>\
										 <a class="ic ic-del menu-link" onclick="deleteTrack(\''+escape(track_id)+'\');" data-func="remove" role="menuitem"><span class="ic_tx">Delete</span></a>\
										 </div>' 
										 
										 : 
										 
										 '<div class="music_track_menu track __open" role="menu">\
										 <a class="ic ic-pls menu-link" onclick="addTrack(\''+escape(track_id)+'\');" data-func="menuAdd" role="menuitem"><span class="ic_tx">Add to my music</span></a>\
										 </div>';
	
	
	if(	!el.closest('li').find('.music_track_aux:not(button) .music_track_menu').length )
		el.closest('li').find('.music_track_aux:not(button)').prepend(mobmus_track_actionmenu);
	else 
		el.closest('li').find('.music_track_menu').remove();
		
}
// post as status
function as_status(el,ev, id, artist, song) {
	ev.stopPropagation();
var mobmus_col_actionmenu_done = '<div class="music_track_menu track __done __open" role="menu">\
								 <a class="fi fi-trsh menu-link" style="text-decoration:none;">\
								 <span class="mob-done-16"></span><span class="ic_tx">In the status</span></a></div>';
    id = id.split('_');
    id = id[id.length - 1];
    var send = jAjax('/profile', 'post', 'q=' + escape(artist + ' - ' + song) + '&cmd=pStatus&i=' + escape(id) + '&type=pos&view_as=json');
     ajaxLoading();

    send.done(function(r) {
        var res = validateJson(r);
       // curr_playing_song = id;
         removeAjaxLoad();

        if (res && res['response'] != 'OK') {
            return displayErr(res['response']);
        } else {
           ga(el).closest('.music_track_menu').replaceWith(mobmus_col_actionmenu_done);//addClass('__done');
         
            setTimeout(function() {
				ga('.music_track_menu.track.__done').remove();
            }, 3000);
        }


    });

}

function addCollection (evt,el,id){
	var collection_details = ga(el).data('collection');
	var send = jAjax('/music.php', 'post', {'cmd':'add-foreign-collection','b':id,'l':id,'i':collection_details.cover,'n':collection_details.collection_name});
	send.done(function(d){
		
		
		//alert(d);
	});
}
 

function uploadTracks(evt,el){
	
	evt.preventDefault();
	
	
	var t_files = el.files; 
	var count = 0;
	var totalFiles = t_files.length;
	
 

        for(var i = 0; i < totalFiles;i++){
			var upload_track_markup = '<li class="track_upload" id="track-upload-'+i+'"><div class="track-upload-progr ellip">'+t_files[i].name+'</div><div class="track-progress-bar"></div></li>';
	
			ga('#mus-upload-bar>ul').prepend(upload_track_markup);
		} 
    
 var uploadTracksN = function(c){
	
	var is_playlist = ga('body').find('#upload_track_in_collection');
	var uploadin = is_playlist.length ? is_playlist.data('collid') : 'mymusic';
 
	
	var formData = new FormData();
	formData.append('files[]', t_files[c]);
	formData.append('cmd','upload-tracks');
	formData.append('uploadin',uploadin);
	 
    $.ajax({
        url: "/cmd.php", //Server script to process data
        type: 'POST',
			xhr: function ()
			{ // Custom XMLHttpRequest
				var Xhr = $.ajaxSettings.xhr();
				if (Xhr.upload)
				{ // Check if upload property exists
					Xhr.upload.addEventListener('progress', function (e)
					{
						var t_id = ga('#track-upload-' + c);
						var p_percentage = Math.round((e.loaded / e.total) * 100);
						t_id.find('.track-progress-bar').css('width', p_percentage + '%');
						
						//mainUploadProgressHandling(e, count, totalFiles)
					}, false); // For handling the progress of the upload
				}
				return Xhr;
			},
        //Ajax events
        beforeSend: function() { 
		
		//ga('#mus-upload-bar>ul').prepend(upload_track_markup);
		
		
		
		},
        success: function(d) {  
			c++;
			
			if( c < totalFiles)
			uploadTracksN(c);
			else {
			setTimeout(function(){
				if(uploadin != 'mymusic'){   
				
			ga('.music_album_lst').before('<a style="display:none;" id="go_to_pl" href="/music/collection/'+uploadin+'?v='+ new Date().getTime()+'" hrefattr="true"></a>');
			up_href();
			ga('#go_to_pl').trigger("click");
				 
				}else { ga('#go_to_my_music').trigger('click');}
			},1200);
			kn_liveNotif(lang.upload_complete,'done',4000,lang.your_tracks_was_uploaded);
		}
		},
        error: function(e) {alert('an error occured while uploading your tracks, please contact administrator or retry.');},
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
	
 }
   
 uploadTracksN(count);
	
}
function playMusicInBackground(){
	
	if(!ga('.music_content').length){
		
		
		var $body = ga('body');
		
		
		ga('.global_bg_track_play').addClass('visible');
		
		
	} else {
		ga('.global_bg_track_play').removeClass('visible');
		
	}
	
	
}

// open mini player
ga(document).off(hasTouchStartEvent ? 'touchend.openGlobalMiniPlayer' : 'click.openGlobalMiniPlayer').on(hasTouchStartEvent ? 'touchend.openGlobalMiniPlayer' :'click.openGlobalMiniPlayer', '#background_track_play', function(e){
	
	e.preventDefault();
	e.stopImmediatePropagation();
	var $this = ga(this);
    var opened_min_playe_url = default_url+'/audio-mini-player';
 
	 if(global_max_player == 'active') return;
	 	default_url = window.location.href;
		createUrl('', '', default_url+'/audio-mini-player'); 
	
	
		is_mobile_popup = true;
		// close global player by back button
		ga(window).on('popstate.closeMobilePopup',function(e){
 
				e.preventDefault();
				e.stopImmediatePropagation();
				ga(window).off('popstate.globalAjax');
				return closeGlobalAudioPlayer(e);
				
		});
 
	
	if($this.find('#global_min_player-max').hasClass('hidden'))
	{
		 global_max_player = 'active';
		ga('#global_min_player-max').removeClass('hidden');
		ga('#background_track_play').addClass('open');
		ga('body').addClass('noscroll');
		return;
	}
	
	
	
	
	
	
	var _track_info = objHook( ga('.global_min_player_json_dt').html() );
			 var artist_name = decodeUrlEncode(_track_info.artist);
		 var track_title = decodeUrlEncode(_track_info.track);
		 var track_album = decodeUrlEncode(_track_info.album);
		 var track_id = js_mob_audio_tag_track.id;
	 var track_cover = _track_info.cover;
	if(!$this.hasClass('open')){
		    global_max_player = 'active';
		
		ga('body').addClass('noscroll');
		$this.addClass('open');
		$this.find('#global_min_player-max').html('<div class="glbminpl_center">\
		<div class="glyphicon glyphicon-remove glbminpl_hide"></div>\
		<div class="glbminpl_cover" style="background-image:url('+getTrackCover(track_cover)+');"></div>\
		<div class="global-min-player-placeholder glbminpl_cover_max mob-audio-placeholder"></div>\
		<div class="global-audio-player-footer"><div class="glbminpl_song_txt">'+artist_name+'&nbsp;-&nbsp;'+track_title+'</div>\
		<div class="glbminpl_album_name">'+track_album+'</div>\
			<div class="glbminpl_timeline"><div class="track_timeline glbmnpl">\
				<div class="track_playhead glbmnpl"></div>\
				<div class="mobmus-seekbar glbmnpl"></div>\
				<div class="mobmus-buffbar glbmnpl"></div>\
					</div><div class="music_track_time"><span class="music_track_seek"><span>00:00</span></span>&nbsp;/&nbsp;<span id="glbminpl_track_time">'+_track_info.time+'</span></div></div>\
		<div class="glbminpl_btns">\
		<div class="glyphicon glyphicon-backward glbminpl_btn_back"></div>\
		<div class="glyphicon glyphicon-play glbminpl_btn_play_pause '+ (ga(mobmusic).hasClass('paused') ? '' : 'playing') +'"></div>\
		<div class="glyphicon glyphicon-forward glbminpl_btn_next"></div>\
		</div>\
		<div class="glbminpl_add_col"><a class="ic ic-pls menu-link" id="global_min_player_add_song" data-func="menuAdd" onclick="addTrack(\'pm_sec_track_'+track_id+'\');" role="menuitem">&nbsp;</a></div>\
		</div></div>');
		timeline = ga('#global_min_player-max').find('.track_timeline')[0]; // timeline 
		playhead = ga('#global_min_player-max').find('.track_playhead')[0];
 		 /*
		if(!_this.find('.track_timeline').length)
		_this.closest('li').append('<div class="track_timeline">\
				<div class="track_playhead"></div>\
				<div class="mobmus-seekbar"></div>\
				<div class="mobmus-buffbar"></div>\
					</div>');
					
					*/
					
		setTimeout(function(){
			 
			var m_play_btn = ga('.glbminpl_btn_play_pause'),
				m_back_btn = ga('.glbminpl_btn_back'),
				m_next_btn = ga('.glbminpl_btn_next');
			
			m_play_btn.on(hasTouchStartEvent ? 'touchend' : 'click', function(e){
				
				if(ga(this).hasClass('playing')){
				mobmusic.pause();	
				ga(this).removeClass('playing');
				ga('.m_portal_track_pause').removeClass('m_portal_track_pause');
			}else{
				ga(this).addClass('playing');
				mobmusic.play();
			}
			});
			
			m_back_btn.on(hasTouchStartEvent ? 'touchend' : 'click', function(e){
				e.stopPropagation();
				prevTrack(this);
				
			});
			m_next_btn.on(hasTouchStartEvent ? 'touchend' : 'click', function(e){
				e.stopPropagation();
				nextTrack(this);
				
			});
			
			
		},100);
		

		
		
	} 
	
	
});
function prevTrack(btn){
	
	
	btn = ga(btn) || false;


	if(current_track_index <= 0){
		if(btn) btn.addClass('disabled');
		
		return;
	}
	
	ga('.glbminpl_btn_next').removeClass('disabled');
	if(!ga('.music_content').length) not_play_next_rewind_button = (current_track_index-1);
	ga(tracks_db[current_track_index-1]).trigger('click');
 
}
function nextTrack(btn){
	btn = ga(btn) || false; 

	if((current_track_index+1) >= Object.keys(tracks_db).length){
		if(btn) btn.addClass('disabled');
		return;
	}
	
	ga('.glbminpl_btn_back').removeClass('disabled');
	if(!ga('.music_content').length) not_play_next_rewind_button = (current_track_index+1);
	ga(tracks_db[current_track_index+1]).trigger('click');
	

	
}

function playNextTrack(cur_song_index){
	
	
	nextTrack();
	//not_play_next_rewind_button = (current_track_index+1);
	//ga(tracks_db[current_track_index+1]).trigger('click');
	
	//mobmusic.load();
	//mobmusic.play();
	
}


//create playlists
function doNewCollection(form, ev, update){
	ev.preventDefault();
	
	var redBord = function (el, color)
	{
		!color ? el.css('border', '1px solid red')
			.focus() : el.css('color', 'red');
		removeAjaxLoad();
	}
	var r_redBord = function (el)
	{
		el.removeAttr('style');
	};
	ajaxLoading();
	var sendForm = js_subForm(form);
	sendForm.done(function (data)
	{  
		var d = validateJson(data);
		removeAjaxLoad();
		
		r_redBord(ga('#mus_colNam'));
		
	   if ( d['a'] == 'empty')
		{
			redBord(ga('#mus_colNam'), 0);
			return;
		} else if (d['a'] == 'error'){
			
			alert('An error occured at creating the playlist, please retry.');
			return;
		} else {
  
			ga('#mus_colNam').before('<a style="display:none;" id="go_to_new_pl" href="/music/collection/'+d.id+'" hrefattr="true"></a>');
			up_href();
			ga('#go_to_new_pl').trigger("click");
			
		}
		
		
		
		
	});
	
}
function faddTrackToMyCollection(t, e)
{
	
	var track_id = ga(t).closest('.track').find('.js-track_play').attr('id').split('_')[1];
		addTrack('pm_sec_track_'+track_id,false,t);
}
function nobilMusicPlayOutsideTrack(el, evt, a)
{
	if (evt) evt.preventDefault();

	 
	
	
	
	
	
}

function nobilMusicSearch(k){
	
	
	var search_in_music = ga('<a href="/music/search/'+k+'/tk/1533594571044" hrefattr="true"></a>');
	
	ga('body').prepend(search_in_music);
	search_in_music.trigger('click');
	search_in_music.remove();	
	
}
var mus_search_tracks_timeout;

// search tracks
ga(document).off('keyup.searchMusTracks').on('keyup.searchMusTracks', '#musicSearchField', function(e){
	clearTimeout(mus_search_tracks_timeout);
	var mus_cancel_search = ga('#mus_search_clear');

	var $this = ga(this);
	
	if( $.trim($this.val()) )
	mus_search_tracks_timeout = setTimeout(function(){
		
		mus_cancel_search.show().parent().addClass('ui_search_loading');
		ga('#mus-search-a').removeAttr('href').attr('href','/music/search/'+$this.val()+'/tk/'+ new Date().getTime()).trigger('click');
 
	},900);
	else{
		
		
		mus_cancel_search.hide().parent().removeClass('ui_search_loading');
		
	}
});
ga(document).off('keydown.searchMusTracks keypress.searchMusTracks').on('keydown.searchMusTracks keypress.searchMusTracks', '#musicSearchField', function(e){
	
	
	clearTimeout(mus_search_tracks_timeout);
	
});

function closeGlobalAudioPlayer(e){
			e.preventDefault();
			e.stopPropagation();
			
			
			is_mobile_popup = false;
			global_max_player = false;
			ga('#background_track_play').slideDown(500,function(){
			ga('#global_min_player-max').addClass('hidden');
			ga('#background_track_play').removeClass('open');
			ga('body').removeClass('noscroll');
			createUrl('', '', default_url);
			});
			

}

// hide mini player
ga(document).off(hasTouchStartEvent ? 'touchend.hideGlobalMiniPlayer' : 'click.hideGlobalMiniPlayer').on(hasTouchStartEvent ? 'touchend.hideGlobalMiniPlayer' : 'click.hideGlobalMiniPlayer', '.glbminpl_hide', function(e){

closeGlobalAudioPlayer(e);
			 
});

// close menu by click on body
ga(document).on('click.mobmuscloseactmenu', 'body', function(e){//.off(hasTouchStartEvent ? 'touchend.mobmuscloseactmenu' : 'click.mobmuscloseactmenu').on(hasTouchStartEvent ? 'touchend.mobmuscloseactmenu' : 'click.mobmuscloseactmenu', 'body', function(e){
	ga('.music_track_menu').remove();
});

// play on track data -> play track
ga(document).off('click.play-audio').on('click.play-audio', '.music_track_data', function(e){ 
	e.preventDefault();
	e.stopImmediatePropagation();
	ga(this).closest('.music_track_i').find('.pButton').trigger('click');
});



