var stop_pressed = false ;	//	checks if the stop button has been pressed
	
var mute_pressed = false ;	//	state of mute button pressed
var repeat_forever_all = true ;	//	if true, whne we arrive to the last video from the playlist, the player will begin again with the first one
var repeat_forever_current_track = false ;	//	if true, we will play forever the current video
	
var shuffle = false ;	//	random playlist video start
	
var duration = 0 ;	//	the duration in seconds of the currently playing video
	
var currenttime = 0 ;	//	the elapsed time in seconds since the video started playing
	
var curr_pos = 0 ;
var video_track_slider = false ;
	
var title_set = false ;	//	the current video title
	
var play_next = false ;
var TimerId = 0 ;
var VolumeTimerId = 0 ;
	
var player_state = -1 ;	//	the state of the player. Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
	
var player_play_state = "" ;
var player_pause_state = "" ;
var player_stop_state = "" ;
	
var buffering_for_nr_of_seconds = 0 ;
	
var load_to_parent = false ;	

var video_progress_ch_from_update = false ;

// This function is automatically called by the player once it loads
function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById("ytPlayer");
    
    var init_volume = 20 ;
    $("#sliderVolume_slider").slider("option", "value", Math.ceil((init_volume / 100) * 100));
    setVolume(init_volume) ;
    
    // This causes the updatePlayerInfo function to be called every 250ms to
    // get fresh data from the player
    setInterval("updateytplayerInfo()", 250);
    
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
    ytplayer.addEventListener("onError", "onPlayerError");

    //  Load an initial video into the player
    if (current_video_id != '') {
        loadNewVideo(current_video_id, 0);
    }
}
	
function updateytplayerInfo() {
    player_state = getPlayerState() ;
		
    if (player_state == 1) {	//	playing
   
        duration = getDuration() ;	//	Returns the duration in seconds of the currently playing video. Note that getDuration() will return 0 until the video's metadata is loaded, which normally happens just after the video starts playing.
   		
        currenttime = getCurrentTime() ;	//	Returns the elapsed time in seconds since the video started playing.	
   			
        if (duration > 0) {	//	if the video started to play
    			
            //	building the current time to display on player
            var update_current_time = "" ;
            update_current_time += Math.floor(currenttime / 60) ;	//	minutes
            update_current_time += ':' ;
            //	building the seconds format 01, 10, ..	for current time
            if (currenttime%60 < 10)
                update_current_time += '0' + Math.floor(currenttime%60) ;
            else
                update_current_time += Math.floor(currenttime%60) ;
    				
            var update_duration = "" ;
            update_duration += Math.floor(duration / 60) ;	//	minutes
            update_duration += ':' ;
            //	building the seconds format 01, 10, .. for duration
            if (duration%60 < 10)
                update_duration += '0' + Math.floor(duration%60) ;
            else
                update_duration += Math.floor(duration%60) ;
       					
            update_current_time += " of " + update_duration ;
            //	prints out the current duration
            $('#span_current_duration').html(update_current_time) ;
        				
            if (isNaN(currenttime / duration)) {
                video_progress_ch_from_update = true ;
                var trackDrag = 0;                
            } else {
                video_progress_ch_from_update = true ;
                var trackDrag = Math.ceil((currenttime / duration) * 100);
            }
                   
            $("#sliderTrack").slider("option", "value", trackDrag);
        				
            //	building the current video loaded
            var bytesloaded = getBytesLoaded() ;	//	Returns the number of bytes loaded for the current video.
            var bytestotal = getBytesTotal() ;	//	Returns the size in bytes of the currently loaded/playing video.
            //	prints out the current video loaded
            $('#span_loaded').html( "loaded: " + Math.floor((bytesloaded * 100) / bytestotal) + "%" ) ;
               
            //  setting the title of the current played video        
            if (!title_set) {            
                var currentDuration = '';
                currentDuration += '(' + Math.floor(duration / 60) + ':';
                var temp_curr_sec_duration = new String(duration%60)  ;			
                curr_sec_duration = temp_curr_sec_duration.substr(0, 2) ;				
                if (temp_curr_sec_duration < 10)
                    currentDuration += '0' + curr_sec_duration ;
                else
                    currentDuration += curr_sec_duration ;
                currentDuration += ')' ;
                      
                setVideoTitle(current_video_id, currentDuration);
            			
                title_set = true ;	//	the video title has been set
                           
                //  we activate the video played from the playlist, but only if the video has been started from the playlist, not from the search iframe
                if (!load_to_parent) {	//  if we have to activate the current started video in the playlist
                    activateVideo(current_video);
                }
            }
        			
            play_next = false ;
        }		
    } else {	//	if the player state is not 1 (playing) we check if the video has finished from playing ad see what to do next
        check_stop_status() ;			
    }
}
	
function check_stop_status() {
    if (player_state == 0) {	//	if the video has ended
        /*if (repeat_forever_current_track && !repeat_forever_all)		//	daca tre sa repete melodia curenta
				setTimeout(play, 6000) ;
			else if (!repeat_forever_current_track && repeat_forever_all) {	//	daca tre sa repete toate melodiile
				if (shuffle)
					play_shuffle_video() ;
				else
					play_next_video() ;
				play_next = true ;
			}*/
        if (repeat_forever_current_track)		//	daca tre sa repete melodia curenta
            setTimeout(play, 3000) ;
        else {
            if (shuffle)	//	if shuffle button has been pressed
                play_shuffle_video() ;
            else
                play_next_video() ;
            play_next = true ;
        }
    } 
}

// This function is called when an error is thrown by the player
function onPlayerError(errorCode) {
    alert("An error occured of type:" + errorCode);
}

// This function is called when the player changes state
function onytplayerStateChange(newState) {
    setytplayerState(newState);
}	
	
function setytplayerState(newState) {
    if (newState == 0) {    //  stop
        //  change the current play button into a play button
        $('#div_play').css("background-image",'url(images/play.jpg)');
        
        //  change the button events handlers
        $('#div_play').attr("onmouseout", "$('#div_play').css('background-image','url(images/play.jpg)');");
        $('#div_play').attr("onmouseover", "$('#div_play').css('background-image','url(images/play_over.jpg)');");
        $('#div_play').attr("onclick", "play();");
        $('#div_play').attr("title", "Play the current video");
    } else if (newState == 1) { //  play			
        //  change the current play button into a pause button
        $('#div_play').css("background-image",'url(images/pause.jpg)');
        
        //  change the button events handlers
        $('#div_play').attr("onmouseout", "$('#div_play').css('background-image','url(images/pause.jpg)');");
        $('#div_play').attr("onmouseover", "$('#div_play').css('background-image','url(images/pause_over.jpg)');");
        $('#div_play').attr("onclick", "pause();");    
        $('#div_play').attr("title", "Pause the current video");
    } else if (newState == 2) { //  pause			
        //  change the current play button into a play button
        $('#div_play').css("background-image",'url(images/play.jpg)');
        
        //  change the button events handlers
        $('#div_play').attr("onmouseout", "$('#div_play').css('background-image','url(images/play.jpg)');");
        $('#div_play').attr("onmouseover", "$('#div_play').css('background-image','url(images/play_over.jpg)');");
        $('#div_play').attr("onclick", "play();");
        $('#div_play').attr("title", "Play the current video");
    } else if (newState == 3) { //  buffering			
        //  change the current play button into a play button
        $('#div_play').css("background-image",'url(images/play.jpg)');
        
        //  change the button events handlers
        $('#div_play').attr("onmouseout", "$('#div_play').css('background-image','url(images/play.jpg)');");
        $('#div_play').attr("onmouseover", "$('#div_play').css('background-image','url(images/play_over.jpg)');");
        $('#div_play').attr("onclick", "play();");
        $('#div_play').attr("title", "Play the current video");
			
        $('span_loaded').update("buffering...") ;			
    } else {
}
}   	
	
function play_next_video() {
    if (!repeat_forever_current_track) {	//	if we do not have to repeat forever the current video
        var increment_value = 1 ;	//	the incremental step of playing the videos from the playlist
        current_video += increment_value ;
        if (current_video > videos_ids.length) {	//	if we finished playing the playlist
            if (repeat_forever_all)	//	if we have to repeat th whole playlist
                current_video = current_video - videos_ids.length ;	//	sets the current video index to the first one from the playlist
            else	//	if we do not have to repeat the whole playlist we stop playing videos
                return ;
        }		
    }
		
    //	starts the video
    var id = videos_ids[current_video] ;
    if (id) {				
        loadNewVideo(id, 0) ;		
    } else {
        current_video = 1 ;
        id = videos_ids[current_video] ;
        loadNewVideo(id, 0) ;
    }
}
	
function play_prev_video() {
    var increment_value = 1 ;	//	the incremental step of playing the videos from the playlist
    current_video -= increment_value ;
    if (current_video < 1)
        current_video = 1 ;
		
    //	starts the video
    var id = videos_ids[current_video] ;
    if (id) {				
        loadNewVideo(id, 0) ;			
    }
    else {
        current_video = 1 ;
        id = videos_ids[current_video] ;
        loadNewVideo(id, 0) ;
    }
}
	
function play_shuffle_video() {
    if (!repeat_forever_current_track) {	//	if we do not have to repeat forever the current video
        if (shuffle)	//	if shuffle is set to true
            var increment_value = Math.floor(Math.random() * 10) ;	//	 number from 0 to 9
        else
            var increment_value = 1 ;
        current_video += increment_value ;
        if (current_video > videos_ids.length)
            current_video = current_video - videos_ids.length ;
    }
		
    //	starts the video
    var id = videos_ids[current_video] ;
    if (id) {				
        loadNewVideo(id, 0) ;		
    }
    else {
        current_video = 1 ;
        id = videos_ids[current_video] ;
        loadNewVideo(id, 0) ;
    }
}
	
// functions for the api calls
function loadNewVideo(id, startSeconds) {
    title_set = false ;		//	this is set to false, to change the current displayed title to the correct one (of the video just started)
    buffering_for_nr_of_seconds = 0 ;
			
    if (load_to_parent)	//	if the video has been started from the search iframe
        var my_ytplayer = parent.window.ytplayer ;
    else	//	if the video has been started from the playlist
        var my_ytplayer = ytplayer ;
    if (my_ytplayer) {
        my_ytplayer.loadVideoById(id, parseInt(startSeconds));
    }		
}

function cueNewVideo(id, startSeconds) {
    if (ytplayer) {
        ytplayer.cueVideoById(id, startSeconds);
    }
}

///////////////////////////////////////////////////////////////////////////////////
//	control player	///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
function play() {	//	plays the current video
    if (ytplayer) {
        if (stop_pressed) {	//	if the stop button was previously pressed
            ytplayer.seekTo(0, true);	//	we go to the begining of the current video
            ytplayer.playVideo();		//	we play it
        } else {
            ytplayer.playVideo();		//	if the video hasn't been stoped, but just paused, play the video from the last frame
        }
        stop_pressed = false ;	//	sets to false the stop button pressed state
    }
}

function pause() {	//	pause the current video
    if (ytplayer) {
        ytplayer.pauseVideo() ;
    }
}

function stop_y() {	//	stops the current video
    if (ytplayer) {
        stop_pressed = true ;	//	sets to true the stop button pressed state
        //ytplayer.stopVideo();
        ytplayer.pauseVideo() ;
        $("#sliderTrack").slider("option", "value", 0);
    }
}

function mute() {
    if (ytplayer) {
        ytplayer.mute();
    }
}

function unMute() {
    if (ytplayer) {
        ytplayer.unMute();
    }
}
	
function mute_unmute() {
    if (!mute_pressed) {
        mute() ;
        $('#img_main_volume_on').hide() ;
        $('#img_main_volume_mute').show() ;
        mute_pressed = true ;			
    } else {
        unMute() ;
        $('#img_main_volume_on').show() ;
        $('#img_main_volume_mute').hide() ;
        mute_pressed = false ;
    }		
}

// Allow the user to set the volume from 0-100
function setVolume(newVolume) {
    var volume = parseInt(Math.floor(newVolume));
    if(isNaN(volume) || volume < 0 || volume > 100) {
        alert("Please enter a valid volume between 0 and 100.");
    }
  
    if (ytplayer) {
        ytplayer.setVolume(volume);
					
        $('#span_volume').html("VOLUME: " + volume + "%") ;
    }
}
	
function seekTo(seconds) {
    if (ytplayer) {
        ytplayer.seekTo(seconds, true);
    }
}
	
function repeat_videos() {
    if (!repeat_forever_current_track && !repeat_forever_all) {	//	daca sunt dezactivate amandoua
        repeat_forever_current_track = false ;
        repeat_forever_all = true ;
        $("#span_repeat").html("REPEAT:ALL") ;			
    } else if (!repeat_forever_current_track && repeat_forever_all) {
        repeat_forever_current_track = true ;
        repeat_forever_all = false ;
        $("#span_repeat").html("REPEAT:VIDEO") ;	
    } else if (repeat_forever_current_track && !repeat_forever_all) {
        repeat_forever_current_track = false ;
        repeat_forever_all = false ;
        $("#span_repeat").html("REPEAT:OFF") ;	
    }	
}
	
function shuffle_videos() {
    if (shuffle) {
        shuffle = false ;
        $("#span_shuffle").html("SHUFFLE:OFF") ;	
    } else {
        shuffle = true ;
        $("#span_shuffle").html("SHUFFLE:ON") ;	
    }
}

///////////////////////////////////////////////////////////////////////////////////
//	end control player	///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////
//	updateytplayerInfo	///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
function getBytesLoaded() {
    if (ytplayer) {
        return ytplayer.getVideoBytesLoaded();
    }
}

function getBytesTotal() {
    if (ytplayer) {
        return ytplayer.getVideoBytesTotal();
    }
}

function getCurrentTime() {
    if (ytplayer) {
        return ytplayer.getCurrentTime();
    }
}

function getDuration() {
    if (ytplayer) {
        return ytplayer.getDuration();
    }
}

function getStartBytes() {
    if (ytplayer) {
        return ytplayer.getVideoStartBytes();
    }
}
	
function getVolume() {
    if (ytplayer) {
        return ytplayer.getVolume();
    }
}

function getVideoTitle(videoId) {
    var currentHost = $(location).attr('host');    
    
    $.ajax({
        type: "POST",
        url: 'http://' + currentHost + '/index.php/yt/getVideoTitle',
        data: 'videoId=' + videoId,
        success: function(response) {
            try {
                return response;
            } catch(err) {
            //alert(err) ;
            }                       
        },
        error:function (xhr, ajaxOptions, thrownError){
        //alert('Error: ' + 'status -> ' + xhr.status + '; thrownError -> ' + thrownError + '');
        } 
    });
}


function setVideoTitle(videoId, videoDuration) {   
    var currentHost = $(location).attr('host');
 
    $.ajax({
        type: "POST",
        url: 'http://' + currentHost + '/index.php?r=yt/getVideoTitle',
        data: 'videoId=' + videoId,
        success: function(response) {
            try {
                $('#span_video_title').html(response + '&nbsp;' + videoDuration) ;
            } catch(err) {
            //alert(err) ;
            }                       
        },
        error:function (xhr, ajaxOptions, thrownError){
        //alert('Error: ' + 'status -> ' + xhr.status + '; thrownError -> ' + thrownError + '');
        } 
    });   
}
///////////////////////////////////////////////////////////////////////////////////
//	end updateytplayerInfo	///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////
//	others	///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
function getPlayerState() {
    if (ytplayer) {
        return ytplayer.getPlayerState();
    }
}    
        
function getEmbedCode() {
    alert(ytplayer.getVideoEmbedCode());
}

function getVideoUrl() {
    alert(ytplayer.getVideoUrl());
}        

function clearVideo() {
    if (ytplayer) {
        ytplayer.clearVideo();
    }
}
///////////////////////////////////////////////////////////////////////////////////
//	end others	///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
