﻿/**
* The 'xssSanitizer' function tries to make sure that the user isn't
* being directed to something that would exploit an XSS vulnerability
* by verifying that the input value matches a particular rule. If the
* provided value is invalid, the page will display an error indicating
* that either the value is invalid or that it doesn't have XSS
* vulnerabilities to exploit.
* @param {string} field Mandatory A name that identifies the field being
*     validated. This will appear in the error list if the value is bad.
* @param {string} value Mandatory The value to be validated.
* @param {string} rulesOfSanitation Mandatory A string that identifies
*     the accepted format of the value -- e.g. alphanumeric, digits,
*     videoId, etc.
* @param {boolean} skipEvent Optional A flag that indicates that the
*     error should not be printed. This is used to avoid inadvertently
*     displaying an error when a field could include, say, a videoId or
*     a videoUrl.
* @return {boolean} Returns true if the value is valid and false if not.
*/

// Define quality options for validating form inputs
var qualityLevels = { 'default': 1, 'highres': 1, 'hd1080': 1, 'hd720': 1, 'large': 1, 'medium': 1, 'small': 1 };


function xssSanitizer(field, value, rulesOfSanitation, skipEvent) {
    
    if (value) {
        value = value.toString();
    }
    var regex = /[\"\<\>]/;
    if (value && value.match(regex)) {
       // console.log('These aren\'t the XSS vulnerabilities you\'re looking for.');

        return false;
    } else if (rulesOfSanitation) {

        if (rulesOfSanitation == 'alphanumeric') {
            var regex = /[\W]/;
            if (value.match(regex)) {
             //   console.log('This \'' + field + '\' value is not supported. The value must be an alphanumeric string.');
                return false;
            }
        } else if (rulesOfSanitation == 'digits') {
            var regex = /[\D]/;

            if (value && value.match(regex)) {
              
                //console.log('This \'' + field + '\' value is not supported. The value must be an integer.');
                return false;
            }

        } else if (rulesOfSanitation == 'playlist') {
            var regex = /^[\w\-]{11}(,[\w\-]{11})*$/;
            if (value.match(regex)) {

                return true;
            }
            //console.log('This \'' + field + '\' value is not supported. The value must be a comma-delimited list of 11-character YouTube video IDs.');
            return false;
        } else if (rulesOfSanitation == 'qualitylevels') {
            if (qualityLevels[value]) {
             //   console.log('This \'' + field + '\' value is not supported. The value must be a supported quality level.');
            }
        } else if (rulesOfSanitation == 'videoIdOrUrl') {
            if (!xssSanitizer(field, value, 'videoId', true)) {
                if (!xssSanitizer(field, value, 'videoUrl', true)) {
               //     console.log('This \'' + field + '\' value is not supported. The value must be an 11-character YouTube video ID or a YouTube watch page URL in the format \'http://www.youtube.com/v/VIDEO_ID\'.');
                    return false;
                }
            }
        } else if (rulesOfSanitation == 'videoId') {
            var regex = /^[\w\-]{11}$/;
            if (value.match(regex)) {
                
                return true;
            }
            if (!skipEvent) {
                //console.log('This \'' + field + '\' value is not supported. The value must be an 11-character YouTube video ID.');
            }
            return false;
        } else if (rulesOfSanitation == 'videoUrl') {
            var regex = /^http\:\/\/www.youtube.com\/v\/([\w\-]){11}$/;
            if (value.match(regex)) {
                
                return true;
            }
            if (!skipEvent) {
                //console.log('This \'' + field + '\' value is not supported. The value must be a YouTube watch page URL in the format \'http://www.youtube.com/v/VIDEO_ID\'.');
            }
            return false;
        }
    }

    
    return true;
}


/**
* The 'cueVideo' function determines whether the user is trying to
* cue a video by its video ID or its URL and then calls the appropriate
* function to actually cue the video. After cueing the video, this
* function updates the video URL and embed code for the video.
* @param {string} idOrUrl Mandatory The ID or URL that identifies the
*                                   video to cue.
* @param {number} startSeconds Optional The time offset, measured in
*                                       seconds from the beginning of the
*                                       video, from which the video
*                                       should start playing.
* @param {string} quality Optional The suggested playback quality for
*                                  the video. Please see
*                                  http://code.google.com/apis/youtube/flash_api_reference.html#setPlaybackQuality
*                                  for more information.
*/
function cueVideo(playerId, idOrUrl, startSeconds, quality) {
 
    var player = document.getElementById(playerId);
    // XSS sanitizer -- make sure params contain valid values
    if (xssSanitizer('Video ID or URL', idOrUrl, 'videoIdOrUrl') &&
            xssSanitizer('Start at', startSeconds, 'digits') &&
            xssSanitizer('Suggested quality', quality, 'qualitylevels')) {
        
        var urlRegex = /http\:/;
        if (idOrUrl.match(urlRegex)) {

            player.cueVideoByUrl(idOrUrl, parseInt(startSeconds), quality);

        } else {
            player.cueVideoById(idOrUrl, parseInt(startSeconds), quality);

        }
     //   getVideoUrl();
    }
}

/**
* The 'getVideoUrl' function returns the YouTube.com URL for the
* currently loaded/playing video. It calls player.getVideoUrl().
*/
function getVideoUrl() {
    var videoUrl = ytswf.getVideoUrl();
    updateHTML('videoUrl', videoUrl);
}


/**
* The 'getDuration' function retrieves the length of the video. It calls
* player.getDuration() function.
* @return {number} The length of the video in seconds.
*/
function getDurationFormatted(playerId) {
    var player = document.getElementById(playerId);
    return getTimeFromSec(player.getDuration());
}

function getDuration(playerId) {
    var player = document.getElementById(playerId);
    return player.getDuration();
}

function getTimeFromSec(sec) {
    sec = Math.ceil(sec);
    
    if (sec > 59) {
        var min = sec / 60;
        min = Math.floor(min);

        sec = sec % 60;
        if (min > 9) {
            if (sec > 9)
                return min + ":" + sec;
            else return "0"+min+":0" + sec; 
        }
        else {
            if (sec > 9)
                return min + ":" + sec;
            else return "0" + min + ":0" + sec; 
        }
    }
    else {
    if(sec>9)
        return "00:" + sec;
    else return "00:0" + sec; 
    }

}

/**
* The 'getCurrentTime' function returns the elapsed time in seconds from
* the beginning of the video. It calls player.getCurrentTime().
* @return {number} The elapsed time, in seconds, of the playing video.
*/
function getCurrentTimeFormatted(playerId) {
    var player = document.getElementById(playerId);

    return getTimeFromSec(player.getCurrentTime());
}


function getCurrentTime(playerId) {
    var player = document.getElementById(playerId);

    return player.getCurrentTime();
}


/**
* The 'getPlayerState' function returns the status of the player. It
* calls ytswf.getPlayerState() to retrieve an integer, which
* identifies the player status:
*   -1: unstarted
*    0: ended
*    1: playing
*    2: paused
*    3: buffering
*    5: video cued
* @return {string} The current state of the video player -- e.g.
*                  'playing', 'paused', etc.
*/
function getPlayerState(playerId) {
    var player = document.getElementById(playerId);
    var playerState = player.getPlayerState();
    switch (playerState) {
        case 5:
            return 'video cued';
        case 3:
            return 'buffering';
        case 2:
            return 'paused';
        case 1:
            return 'playing';
        case 0:
            return 'ended';
        case -1:
            return 'unstarted';
        default:
            return 'Status uncertain';
    }
    return player.getPlayerState();
}


/**
* The 'seekTo' function seeks to the specified time of the video. The
* time is specified as an offest, measured in seconds from the beginning
* of the video. The function causes the player to find the closest
* keyframe before the specified value.
* @param {number} seconds Mandatory The time offset to skip to.
* @param {boolean} allowSeekAhead Mandatory A flag that indicates if
*                                          the player will make a new
*                                          request to the server if the
*                                          specified time is beyond the
*                                          currently loaded video data.
*/
function seekTo(playerId, seconds, allowSeekAhead) {
    var player = document.getElementById(playerId);
    // XSS sanitizer -- make sure param contains a valid value
    if (xssSanitizer('Seek to', seconds, 'digits')) {
        player.seekTo(seconds, allowSeekAhead);
    }
}



function playVideo(playerId) {
    var player = document.getElementById(playerId);
    player.playVideo();
}
function pauseVideo(playerId) {
    var player = document.getElementById(playerId);
    player.pauseVideo();
}

function muteVideo(playerId) {
    var player = document.getElementById(playerId);
    player.mute();
}

function unmuteVideo(playerId) {
    var player = document.getElementById(playerId);
    player.unMute();
}

function setVolume(playerId, newVolume) {
    // XSS sanitizer -- make sure volume is just numbers.
    if (xssSanitizer('Volume', newVolume, 'digits')) {
        var player = document.getElementById(playerId);
        player.setVolume(newVolume);
    }
}

/**
* The 'getBytesTotal' function returns the size in bytes of the currently
* loaded/cued video. It calls player.getVideoBytesTotal().
* @return {number} The total number of bytes in the video.
*/
function getBytesTotal(playerId) {
    var player = document.getElementById(playerId);
    return player.getVideoBytesTotal();
}

/**
* The 'getStartBytes' function returns the number of bytes from which
* the currently loaded video started loading. It calls
* player.getVideoStartBytes().
* @return {number} The number of bytes into the video when the player
*                  began playing the video.
*/
function getStartBytes(playerId) {
    var player = document.getElementById(playerId);
    return player.getVideoStartBytes();
}

/**
* The 'getBytesLoaded' function returns the number of bytes loaded for
* the current video. It calls player.getVideoBytesLoaded().
* @return {number} The number of bytes loaded for the current video.
*/
function getBytesLoaded(playerId) {
    var player = document.getElementById(playerId);
    return player.getVideoBytesLoaded();
}


/**
* The 'onYouTubePlayerReady' function executes when the onReady event
* fires, indicating that the player is loaded, initialized and ready
* to receive API calls.
* @param {string} playerId Mandatory A value that identifies the player.
*/
function onYouTubePlayerReady(playerId) {

    // No need to do any of this stuff if the function was called
    // because the user customized the player parameters for the embedded
    // player.
    if (playerId && playerId != 'undefined') {
        player = document.getElementById(playerId);

        if (player) {


            //check in vars
            if (eval("jsVar_" + playerId + "['videoToPlay']")) {
                
                cueVideo(playerId, eval("jsVar_" + playerId + "['videoToPlay']"), 0);
            }
            else {
                
                cueVideo(playerId, player.getVideoUrl(), 0);
                
                
            }
            updateplayerInfo(playerId);

            

            player.addEventListener("onStateChange", playerId + '_onplayerStateChange');
            eval("onYouTubePlayerReady_" + playerId+"(playerId);");
            //getVideoUrl();
            //getEmbedCode(false);
            //updateytplayerInfo();
            //ytswf.addEventListener('onStateChange', 'onytplayerStateChange');
            //ytswf.addEventListener('onError', 'onPlayerError');
            //ytswf.addEventListener('onPlaybackQualityChange',
            //'onytplayerQualityChange');
        }
    }
}


/**
* The 'onplayerStateChange' function executes when the onStateChange
* event fires. It captures the new player state and updates the
* "Player state" displayed in the "Playback statistics".
* @param {string} newState Mandatory The new player state.
*/
function onplayerStateChange(playerId, newState) {

    if (newState == -1 || newState == 0 || (newState == 2 && getBytesTotal(playerId) == getBytesLoaded(playerId))) {
        //not started or ended - stop timer if started
        var id = eval("jsVar_" + playerId + "['playerTimerId']");
        if (id) {
            clearInterval(id);
            eval("jsVar_" + playerId + "['playerTimerId']='';")
        }
    }
    else if (newState == 1 || newState == 2 || newState == 3)
    {
        //started -> if timer not started -> start
        
        var id = eval("jsVar_" + playerId + "['playerTimerId']");
        if (!id) {
            id = setInterval("updateplayerInfo('" + playerId + "')", 500);
            eval("jsVar_" + playerId + "['playerTimerId']='"+id+"';")
        }
    }
    if (eval("jsVar_" + playerId + "['isSliding']") != "true") {

        if (newState == 2) {
            //pause
            if (eval("jsVar_" + playerId + "['playerState']") != "paused") {
                eval("jsVar_" + playerId + "['playerState'] = 'paused';");
                var imgId = eval("jsVar_" + playerId + "['imgPlayId']");
                document.getElementById(imgId).src = video_player_img_play_src;
            }
        }
        else if (newState == 1) {
            //play
            if (eval("jsVar_" + playerId + "['playerState']") != "play") {
                eval("jsVar_" + playerId + "['playerState'] = 'play';");
                var imgId = eval("jsVar_" + playerId + "['imgPlayId']");
                document.getElementById(imgId).src = video_player_img_pause_src;
            }

            //try to stop all videos
            try
            {
            for(i =0;i<suite_video_players.length;i++) {

                if (suite_video_players[i] != playerId) {
                    var otPlayer = document.getElementById(suite_video_players[i]);
                    var otState = otPlayer.getPlayerState();
                    if (otState != -1 && otState != 5 && otState != 2) {
                        otPlayer.pauseVideo();
                    }
                    
                }
            }
            }catch(exc){}
        }
    }
   
}





/**
* The 'updateytplayerInfo' function updates the volume and
* "Playback statistics" displayed  on the page. (It doesn't actually
* update the player itself.) The onYouTubePlayerReady uses the
* setInterval() function to indicate that this function should run
* every millisecond.
*/
function updateplayerInfo(playerId) {
    //            updateHTML('volume', getVolume());

    var duration = getDuration(playerId);
    var durationFormatted = "--:--";
    var currentTimeFormatted = "--:--";

    if (duration > 0) {
        durationFormatted = getDurationFormatted(playerId);
        currentTimeFormatted = getCurrentTimeFormatted(playerId);
    }

    updateHTML(eval("jsVar_" + playerId + "['durationId']"), durationFormatted);
    updateHTML(eval("jsVar_" + playerId + "['currentTimeId']"), currentTimeFormatted);
    
    if (eval("jsVar_" + playerId + "['isSliding']") != "true") {
        updateSlider(playerId, getStartBytes(playerId), getBytesTotal(playerId), getBytesLoaded(playerId), duration, getCurrentTime(playerId));
    }

}


/**
* The 'updateHTML' function updates the innerHTML of an element.
* @param {string} elmId Mandatory The element to update HTML for.
* @param {string} value Mandatory The updated HTML for the element.
*/
function updateHTML(elmId, value) {
    if (document.getElementById(elmId)) {
        document.getElementById(elmId).innerHTML = value;
    }
}


function updateSlider(playerId,startBytes, totalBytes, loadedBytes, duration, currentTime) {

    if (duration > 0) {
        var vSlider = $("#"+ eval("jsVar_" + playerId + "['sliderId']"));
        vSlider.slider("option", "disabled", false);
        vSlider.slider("option", "max", Math.ceil(duration));
        vSlider.slider("option", "value", Math.ceil(currentTime));
    }
    var medial = document.getElementById(eval("jsVar_" + playerId + "['loaderId']"));
    if (totalBytes > 0) {
        //totalbytes -> 100%
        // startbytes -> convert to % -> left
        //loadedbytes -> convert to % -> width
        totalBytes = Math.ceil(totalBytes);
        startbytes = Math.ceil(startBytes);
        loadedbytes = Math.ceil(loadedBytes);

        totalBytes = totalBytes + startBytes;

        var percentage = totalBytes / 100;

        medial.style.width = Math.ceil((loadedBytes / percentage)) + "%";
        medial.style.left = Math.ceil((startBytes / percentage)) + "%";
    }

    else {
        medial.style.width = "0%";
        medial.style.left = "0%";
    }



}


/** Functions for the api calls */
/**
* The 'loadVideo' function determines whether the user is trying to
* load a video by its video ID or its URL and then calls the appropriate
* function to actually load the video. After loading the video, this
* function updates the video URL and embed code for the video.
* @param {string} idOrUrl Mandatory The ID or URL that identifies the
*                                   video to load.
* @param {number} startSeconds Optional The time offset, measured in
*                                       seconds from the beginning of the
*                                       video, from which the video
*                                       should start playing.
* @param {string} quality Optional The suggested playback quality for
*                                  the video. Please see
*                                  http://code.google.com/apis/youtube/flash_api_reference.html#setPlaybackQuality
*                                  for more information.
*/
function loadVideo(playerId, idOrUrl, startSeconds, quality) {
    
    var player = document.getElementById(playerId);

    // XSS sanitizer -- make sure params contain valid values
    if (xssSanitizer('Video ID or URL', idOrUrl, 'videoIdOrUrl') &&
            xssSanitizer('Start at', startSeconds, 'digits') &&
            xssSanitizer('Suggested quality', quality, 'qualitylevels')) {
        var urlRegex = /http\:/;
        if (idOrUrl.match(urlRegex)) {
            player.loadVideoByUrl(idOrUrl, parseInt(startSeconds), quality);

        } else {
            player.loadVideoById(idOrUrl, parseInt(startSeconds), quality);

        }
        //getVideoUrl();
      //  getEmbedCode(true);
    }
}

