

(function($){
    $.extend({});
    
    $.fn.extend({
        ViderPlayListManager: function(){
            /**
             @Description: a class for video player
             */
            var config = {
                VideoNavWrapperDOMID: 'fragment-1',
                sortablePlayListClassName: '.sortablePlayList',
                playLists: [],
                PlayListIndexAttributename: 'playListIndex',
                PlayListIndexDomContainerClassName: '.PlayListOrder',
                TrackWrapperClassName: '.sortable-list-default',
                TrackIDAttributeName: 'songid',
                PlayHeadSignContainerClassName: '.playHead',
                PlayHeadSignHTML: '<img class="playheadSign" src="images/playHeadSign.gif"/>',
                PlayListHTML: ''
            };
            this.config = config;
            
            var PlayListsController;
            var PlayUserListsController;
            
            this.VarValue = function(_id){
                /**
                 @Description: returns value of matched config property
                 @param _id: string representing config property name
                 */
                return (config[_id]);
            }
            
            this.SetClientPlayList = function(_node){
                /*param _node: */
                config.playLists[config.playLists.length] = new PlayList(_node);
            }
            
            this.addToClientPlayList = function(_playListObj, _plstId){
                var plstUl = $('ul#' + _plstId);
                if (($('ul#playlistUser').css('display')=="block") && ($("#playList_tabs").height() > 30)){
					$('#playlistUser').css({'visibility':'hidden'});
					fixPlaylistHeight();
				}
                var domStr = channelv.Page.VideoPlayListController.AppendPlayListHTMLString(_playListObj, _plstId);
                var theListIndex, theList, oldIndex, newIndex, tempTrackNameHolder = 0, tempIndex = [];
                theListIndex = GetPlayListIndexByListName(_playListObj.PlaylistId);
               
                plstUl.append(domStr);
                UpdatePresentationPlayListOrderNumber(plstUl);
                UpdateDOMPlayListIndexValue(plstUl);
                if (typeof(theListIndex) == 'undefined') {
                    channelv.Page.VideoPlayListController.SetClientPlayList($(plstUl).get(0));
                } else {
                
                    oldIndex = config.playLists[theListIndex].memberTracks.length;
                    config.playLists[theListIndex].memberTracks = CreateTrackListPerPlayList(config.playLists[theListIndex].ListName);
                    newIndex = config.playLists[theListIndex].memberTracks.length;
                    if (PlayListsController.IsThisPlayListCurrentlyPlayed(config.playLists[theListIndex].ListName)) {
                        for (m = 0; m < oldIndex; m++) {
                            if (config.playLists[theListIndex].memberTracks[m] == PlayListsController.GetCurrentlySelectedVideoInHTML()) tempTrackNameHolder = m;
                        }
                        var tmpCount = 0;
                        for (n = tempTrackNameHolder; n < newIndex; n++) {
                            tempIndex[tmpCount] = config.playLists[theListIndex].memberTracks[n];
                            tmpCount++;
                        }
                        for (n = 0; n < tempTrackNameHolder; n++) {
                            tempIndex[tmpCount] = config.playLists[theListIndex].memberTracks[n];
                            tmpCount++;
                        }
                        movideoplayer.customPlaylistCall('video', tempIndex)
                    }
                }
                channelv.Page.VideoPlayListController.BindEvents($(plstUl).get(0));
				if($('.PlayListHTMLTemplate').find('div.selected').length>0){
					if(($('#playlistUser').css('display')=='block') && ($("#playList_tabs").height() > 30)){
						var hgt = 0;
						$('#playlistUser').css({'visibility':'hidden'}).find('li').each(function(){hgt+=$(this).height();});
						hgt+=10;
						if (hgt<75)hgt=75;
						if (hgt>170)hgt=170;	
						$('#playlistUser').height(hgt+'px').css({'visibility':'visible'});
						fixPlaylistHeight();
						}
				}
            };
            
            this.AppendPlayListHTMLString = function(_obj, _par){
                var htmlStr = '';
                var theId =  _obj.PlaylistId;
                var _l = config.playLists.length;
                if (_l > 5) _l = 5;
                $(_obj.Entries).each(function(g){
                    htmlStr += '<li class="sortable-list-default clearfix" songid="' + this.VideoId + '" playListIndex="' + g + '">';
                    htmlStr += '<div class="PlayListOrder">' + (g + 1) + '</div>';
                    htmlStr += '<div class="PlayHead">&nbsp;</div>'
                    htmlStr += '<div class="SongTitle">' + this.SongTitle + '</div>';
                    htmlStr += '<div class="ArtistName">' + this.ArtistName + '</div>';
                    htmlStr += '<div class="PlayNowLink" onclick="doPlayBackVideo(' + this.VideoId + ', \'' + _par + '\')"><a href="javascript:void(0)" title="Play this track now">play</a></div>';
                    htmlStr += '<div class="Buy">';
                    if (this.BuyLink) htmlStr += '<a target="_blank" title="Buy now on iTunes" href="' + this.BuyLink + '">Buy</a>'
                    htmlStr += '</div>';
                    htmlStr += '<div class="DeleteSongFromPlaylist" onclick="doDeleteTrackFromList(' + this.VideoId + ', this)"><a href="javascript:void(0)" title="Delete this track from this playlist">delete</a></div>';
                    htmlStr += '</li>';
                });
                
                return htmlStr;
            };
            this.CreatePlayListHTMLString = function(_obj, _l){
                var htmlStr = '';
                var theId = "playlist"+_obj.PlaylistId;
				var title = _obj.PlaylistName;
                if (_l > 5) _l = 5;
                htmlStr += '<div id="lh_' + theId + '" class="ListHeader LH' + _l + '" onclick="channelv.Page.VideoPlayListControllerObject.SetCurrentlySelectedPlayListInHTML(\'' + theId + '\')" title="Click to open/close this playlist">' + title + '</div>';
                htmlStr += '<ul id="' + theId + '" class="sortablePlayList clearfix">';
                $(_obj.Entries).each(function(g){
                    htmlStr += '<li class="sortable-list-default clearfix" songid="' + this.VideoId + '" playListIndex="' + g + '">';
                    htmlStr += '<div class="PlayListOrder">' + (g + 1) + '</div>';
                    htmlStr += '<div class="PlayHead">&nbsp;</div>'
                    htmlStr += '<div class="SongTitle">' + this.SongTitle + '</div>';
                    htmlStr += '<div class="ArtistName">' + this.ArtistName + '</div>';
                    htmlStr += '<div class="PlayNowLink" onclick="doPlayBackVideo(' + this.VideoId + ', \'' + theId + '\')" title="Play now" ><a href="javascript:void(0)">play</a></div>';
                    htmlStr += '<div class="Buy">';
                    if (this.BuyLink) htmlStr += '<a target="_blank" title="Buy now on iTunes" href="' + this.BuyLink + '">Buy</a>';
                    htmlStr += '</div>';
                    if (theId == "playlistUser") htmlStr += '<div class="DeleteSongFromPlaylist" onclick="doDeleteTrackFromList(' + this.VideoId + ', this)"><a href="javascript:void(0)" title="Delete this track from this playlist">delete</a></div>';
                    htmlStr += '</li>';
                });
                htmlStr += ' </ul>';
                return htmlStr;
            };
            
            this.BindEvents = function(_node){
				if(!_node) return;
                $(_node).sortable('destroy');
                $(_node).sortable({
                    stop: function(e, ui){
                        $this.VideoPlayListController.SortOrderCallBackEvtHandler(this, ui);
                    },
                    opacity: 0.6
                });
                
                //Trigger settings for list selected css
                $('li.sortable-list-default', _node).each(function(i){
                    if ((i++) % 2) {
                        $(this).addClass("even");
                    } else {
                        $(this).addClass("odd");
                    }
                    
                    $(this).mouseover(function(e){
                        $(this).addClass('liOver');
                    });
                    
                    $(this).mouseout(function(e){
                        $(this).removeClass('liOver');
                    });
                    
                    $(this).dblclick(function(){
                        channelv.Page.VideoPlayListControllerObject.SetCurrentlySelectedVideoInHTML($(this).attr('songid'));
                        
                        //if ($(this).parent().attr('id')=='Top20')
                        doPlayBackVideo($(this).attr('songid'), $(this).parent().attr('id'));
                        //else
                        //doPlayBackUserVideo($(this).attr('songid'), this);
                    });
                });
				$('.ListHeader').each(function(){
					$(this).unbind('click', plstAccordeon);
              		$(this).bind('click', plstAccordeon);
			   })
            };
            this.BindOneSongEvent = function(_node, _addedLi){
                $(_node).sortable('destroy');
                $(_node).sortable({
                    stop: function(e, ui){
                        $this.VideoPlayListController.SortOrderCallBackEvtHandler(this, ui);
                    },
                    opacity: 0.6
                });
                
                $(_addedLi).mouseover(function(e){
                    $(this).addClass('liOver');
                });
                
                $(_addedLi).mouseout(function(e){
                    $(this).removeClass('liOver');
                });
                
                $(_addedLi).dblclick(function(){
                    channelv.Page.VideoPlayListControllerObject.SetCurrentlySelectedVideoInHTML($(this).attr('songid'));
                    doPlayBackVideo($(this).attr('songid'), this.parent().attr('id'));
                });
            };
            this.updateUserPlaylist = function(){
                var _usrEntriesStr = [];
                var idxUP = GetPlayListIndexByListName("playlistUser");
                
                $('ul#playlistUser li').each(function(i){
                    var song = {};
                    song['ArtistName'] = $(this).find('div.ArtistName').eq(0).text();
                    song['BuyLink'] = $(this).find('div.Buy a').eq(0).attr('href');
                    if (typeof(song['BuyLink']) == 'undefined') song['BuyLink'] = null;
                    song['SongTitle'] = $(this).find('div.SongTitle').eq(0).text();
                    song['VideoId'] = $this.VideoPlayListController.config.playLists[idxUP].memberTracks[i];
                    _usrEntriesStr[i] = $.toJSON(song);
                });
                
                
                var postStr = '{"Entries":[' + _usrEntriesStr + '],"PlaylistId":"playlistUser"}';
                $.ajax({
                    type: "POST",
                    data: postStr,
                    url: "/MediaPlayerService.svc/UpdateUserPlaylist",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                });
                
            }
            
            this.GetClientPlayList = function(){
                return config.playLists;
            }
            
            this.GetPlayListControlObject = function(){
                return PlayListsController;
            }
            
            
            this.SortOrderCallBackEvtHandler = function(_node, ui){
                /**
                 @param _node: <ul> representing each playlist
                 @param ui: node that sort event is fired (<li>)
                 */
                var oldIndex, newIndex, postbackData, _listName, theList, tempTrackNameHolder;
                
                /**@comment: get palylist id*/
                _listName = _node.getAttribute('id');
                
                /**@comment: get index number of the moved track in the playlist before the sort happened*/
                oldIndex = $(ui.item).attr(config.PlayListIndexAttributename);
                /**@comment: Update index number being diplayed at far left number in the playlist*/
                UpdatePresentationPlayListOrderNumber(_node);
                
                /**@comment; Update the values of "playListIndex" attribute attached to <li> representing each track of the playlist*/
                UpdateDOMPlayListIndexValue(_node);
                
                /**@commen: Update the css values of <li> representing each track of the playlist*/
                UpdatePresentationPlayListCSSValues(_node);
                
                /**@comment: get an updated track index number in the playlist*/
                newIndex = $(ui.item).attr(config.PlayListIndexAttributename);
                
                if (parseInt(oldIndex) == parseInt(newIndex)) return;
                
                /**@comment: Retirve a PlayList instance*/
                theList = GetPlayListByListName(_listName);
                
                /**@comment: Update the memberTracks value to reflect the sort change*/
                tempTrackNameHolder = theList.memberTracks[oldIndex];
                //Remove first
                theList.memberTracks.splice(parseInt(oldIndex), 1);
                //then add it
                theList.memberTracks.splice(newIndex, 0, tempTrackNameHolder);
                /**@Description: change track orders in the playlist that is curently on play*/
                
                /**@comment: check to see the playlist id subject in this function is one that is being played*/
                if (PlayListsController.IsThisPlayListCurrentlyPlayed(_node.getAttribute('id'))) {
                
                    var alteredNewIndex, theSongID;
                    
                    /**@comment: retrieve songid (video id) of track that is moved*/
                    theSongID = $(ui.item).attr(config.TrackIDAttributeName);
                    
                    alteredNewIndex = parseInt(newIndex);
                    
                    /**@comment: remove the video from the list of video player (see movideoplayer.js)*/
                    movideoplayer.removeFromPlaylistCall(theSongID, 'video');
                    
                    /**@comment: then add the video to the list of video player by the new index(see movideoplayer.js)*/
                    movideoplayer.addToPlaylistCall(theSongID, 'video', alteredNewIndex);
                    
                }
                //postbackData = JSONSerialisationForPostBack(_node); //Post back the list to ajax
                
                PlayListsController.SetCurrentlySelectedVideoInHTML($(ui.item).attr('songid'));
                if (_node.getAttribute('id') == "playlistUser") channelv.Page.VideoPlayListController.updateUserPlaylist();
                
            };
            
            this.InstanciatePlayListController = function(){
                /**
                 @Description: Returns an instance of PlayListsControlClass() that encaplsulates controls for custom playlists, track songids, and interfacing to videoplayer
                 */
                if (config.playLists.length == 0) return;
                PlayListsController = new PlayListsControlClass(config.playLists[0]);
                return PlayListsController;
            }
            
            function PlayListsControlClass(_playList){
                /**
                 @param _playList: an instance of PlayList class
                 */
                /**@comment: contains string that represents the name (id) of playlist currently being played*/
                var CurrentlyPlayedPlayListNameInFlash = _playList.ListName;
                var AdHocId = "";
                var TempAdHocId = "";
                
                /**@comment: contains an object that encapsulates index number and trackID of video being currently played in Flash movir*/
                //var CurrentlyPlayedVideoInFlash;
                
                /**@comment: What is on show*/
                var CurrentlySelectedPlayListNameInHTML = _playList.ListName;
                
                /**@comment: store songid that is double clicked, in effect, to be player*/
                var CurrentlySelectedVideoInHTML;
                
                /**@comment: Prepare pushing playlist into the Flash player via an array object containing songids*/
                var customtracks = [];
                for (var t = 0; t < _playList.memberTracks.length; t++) {
                    customtracks[t] = parseInt(_playList.memberTracks[t]);
                }
                
                
                try {
                    /**@comment: create a custom playlist by passing in an array object containing  */
                    movideoplayer.customPlaylistCall('video', customtracks);
                } catch (e) {
                    alert(e)
                }
                
                
                this.GetCurrentlyPlayedPlayListInFlash = function(){
                    /**@Description: returns the value of playlist ID currently being played*/
                    return CurrentlyPlayedPlayListNameInFlash;
                }
                
                
                this.SetCurrentlyPlayedPlayListInFlash = function(_val){
                    /**
                     @Description:called at the playback event of track
                     @param _val; PlaylistId that is being opened
                     */
                    /**@comment: the playlist that was open is now active playing one of its tracks*/
                    CurrentlyPlayedPlayListNameInFlash = _val;
                    /**@comment: getting an index number of the playlist within config.playLists that is being played*/
                    var thePlayListIndex = UpdateStatusInPlayListCollection(_val);
                    /**@comment: prepare pushing the playlist to the Flash player to play*/
                    var theResult = PushPlayListToFlash(thePlayListIndex);
                }
                
                
                this.IsThisPlayListCurrentlyPlayed = function(_val){
                
                    /**
                     @param _val: playList Id
                     @Description: returns true if the passed-in playlist id matches the playlist ID
                     currently being played
                     */
                    if (CurrentlyPlayedPlayListNameInFlash == _val) {
                        return true;
                    } else return false;
                }
                this.IsThisIdInThePlayListCurrentlyPlayed = function(_val, _plName){
                
                    /**
                     @param _val: track Id
                     @param _plName: playkist name
                     @Description: returns true if the passed-in track id is already in the playlist
                     currently being played
                     */
                    var plst = GetPlayListByListName(_plName);
                    if (typeof(plst) == 'undefined') return false
                    
                    for (i = 0; i < plst.memberTracks.length; i++) {
                        if (plst.memberTracks[i] == _val) return true
                    }
                    return false;
                }
                
                /*
                 this.ReplaceWholePlayListInFlash = function(_val) {
                 CurrentlyPlayedPlayListInFlash = _val;
                 var _list = GetPlayListByListName(_val);
                 //Wait for API
                 return true;
                 //config.playLists
                 }
                 */
                /////////////////////  Navigations on HTML /////////////////////////
                this.SetCurrentlySelectedPlayListInHTML = function(_val){
                    /**@param _val: string PlaylistId that is being opened(selected)*/
                    CurrentlySelectedPlayListNameInHTML = _val;
                };
                
                this.SetCurrentlySelectedVideoInHTML = function(_val){
                    /**@param _val: string songid that is double clicked, in effect, to be played*/
                    CurrentlySelectedVideoInHTML = _val;
                }
                
                this.GetCurrentlySelectedVideoInHTML = function(){
                    /**
                     @Description: returns the palylistId
                     Function that is called to retirve HTML strings from trackinfo tab
                     */
                    return CurrentlySelectedVideoInHTML;
                }
                
                this.MovePlayHead = function(_videoID){
                    /**
                     @Description: a call back function from the flash video player executed at
                     the begining of each track
                     @param _videoID: int video id (songid)
                     */
                    try {
                        //if (this.AdHocId==""){
                        UpdateVideoPlayHeadEvtHandler(_videoID, this.GetCurrentlyPlayedPlayListInFlash())
                        //}
                        //else  {
                        //	this.TempAdHocId=this.AdHocId;
                        //	this.AdHocId="";
                        //	}
                    } catch (e) {
                        alert(e)
                    }
                }
                
                this.doPlayBack = function(_trackID){
                    /**@param _trackID: string songid*/
                    
                    var theTrackID = _trackID;
					this.SetCurrentlySelectedVideoInHTML(_trackID);
                    if (this.IsThisPlayListCurrentlyPlayed(CurrentlySelectedPlayListNameInHTML)) {
                        movideoplayer.playTrackCall(_trackID, "video");
                        
                    } else {
                    
                        this.SetCurrentlyPlayedPlayListInFlash(CurrentlySelectedPlayListNameInHTML);
                        setTimeout(timer, 1000);
                        
                    }
                    function timer(){
                        movideoplayer.playTrackCall(theTrackID, "video");
                    }
                    //$.scrollTo('.sliderMenu',400);
                }
                this.doPlayOneSong = function(_songid, _ArtistName, _SongTitle, _buyLink){
                    /**@param _trackID: string songid*/
                    $('#VideoTopController a.PlayedDownload').hide();
					this.SetCurrentlySelectedVideoInHTML(_songid);
                    if (this.IsThisIdInThePlayListCurrentlyPlayed(_songid, CurrentlyPlayedPlayListNameInFlash)) {
                        this.AdHocId = "";
                        this.doPlayBack(_songid);
                    } else {
                        var theTrackID = _songid;
                        
                        movideoplayer.playTrackCall(theTrackID, "video");
                        setTimeout(timer, 1000);
                        $.scrollTo('#VideoTopController',800);
                    
                    }
                    function timer(){
                        if (_buyLink != '') {
                        
                            $('#VideoTopController a.PlayedDownload').eq(0).attr('href', _buyLink);
                            $('#VideoTopController a.PlayedDownload').show();
                        }
                        $('#PlayedAuthor').eq(0).text(_ArtistName);
                        $('#PlayedSong').eq(0).text(_SongTitle);
                        $('#VideoTopController').get(0).songId = _songid;
                        //this.TempAdHocId = _songid;
						this.AdHocId = _songid;
						if ($("#playList_tabs").height() > 24) {
							var _LI=$('#playList_tabs ul li')
							if (_LI.eq(1).hasClass('set')) _LI.eq(1).find('a').click();
							if (_LI.eq(2).hasClass('set')) _LI.eq(2).find('a').click();
							if (_LI.eq(3).hasClass('set')) _LI.eq(3).find('a').click();
						}
                    }  
                }
				
                this.isPlayListNameUsed = function(_val){
                    /**
                     @param _val: playlist ID
                     @Description: returns PlayList index
                     */
                    idx = false
                    for (var i = 0; i < config.playLists.length; i++) {
                        if (config.playLists[i].ListName == _val) {
                            idx = true
                            break;
                        }
                    }
                    return idx;
                }
                
                this.doDeleteTrack = function(_trackID, _evtSrc){
                
                    var theTrackInfo, theListInfo, listIndex, theList;
                    theTrackInfo = $(_evtSrc).parents("li").eq(0);
                    theListInfo = $(_evtSrc).parents("ul").eq(0);
                    
                    listIndex = parseInt($(theTrackInfo).attr('playlistindex'));
                    theList = GetPlayListByListName($(theListInfo).attr('id'));
                    
                    //Remove this from the internal cache
                    theList.memberTracks.splice(listIndex, 1);
                    
                    //Then remove from the flash play list
                    movideoplayer.removeFromPlaylistCall(_trackID, 'video');
                    
                    //Remove the list element
                    $(theTrackInfo).remove();
                    
                    //Update the playlist presentation table
                    UpdatePresentationPlayListOrderNumber(theListInfo);
                    UpdateDOMPlayListIndexValue(theListInfo);
                    
                    
                }
                
                function UpdateStatusInPlayListCollection(_playListID){
                    /**
                     @Description: To indicate the PlayList instance being currently played
                     Returns an index number of the playlist within config.playLists
                     @param _playListID: string the playlist id of what's currently being played
                     */
                    var theKeyPlayListIndex = 0;
                    for (var i = 0; i < config.playLists.length; i++) {
                        if (config.playLists[i].ListName == _playListID) {
                            theKeyPlayListIndex = i;
                            config.playLists[i].currentStatus = 1;
                        } else config.playLists[i].currentStatus = 0;
                    }
                    
                    return theKeyPlayListIndex;
                }
                
                function PushPlayListToFlash(_key){
                    /**
                     @param _key: int index number of config.playLists
                     @Description: Create a custom playlist by passing in an array containing track's songids
                     */
                    var customtracks = [];
                    for (var t = 0; t < config.playLists[_key].memberTracks.length; t++) {
                        customtracks[t] = parseInt(config.playLists[_key].memberTracks[t]);
                    }
                    try {
                        movideoplayer.customPlaylistCall('video', customtracks);
                        return true;
                    } catch (e) {
                        return e;
                    }
                    
                }
            }
            
            
            function GetPlayListByListName(_val){
                /**
                 @param _val: playlist ID
                 @Description: returns PlayList instance
                 */
                for (var i = 0; i < config.playLists.length; i++) {
                    if (config.playLists[i].ListName == _val) {
                        return config.playLists[i];
                        break;
                    }
                }
            }
            function GetPlayListIndexByListName(_val){
                /**
                 @param _val: playlist ID
                 @Description: returns PlayList index
                 */
                for (var i = 0; i < config.playLists.length; i++) {
                    if (config.playLists[i].ListName == _val) {
                        return i;
                        break;
                    }
                }
                
            }
            
            
            function UpdatePresentationPlayListOrderNumber(_node){
                /**
                 @param node: <ul> representing a playlist
                 @Description: Update index number being diplayed at far left number in the playlist
                 */
                var i = 0;
                $(_node).find(config.PlayListIndexDomContainerClassName).each(function(){
                    i++;
                    $(this).text(i);
                });
            };
            
            function UpdateDOMPlayListIndexValue(_node){
                /**
                 @param node: <ul> representing a playlist
                 @Description: Update the values of "playListIndex" attribute attached to <li> representing each track of the playlist
                 */
                var i = 0;
                $(_node).find(config.TrackWrapperClassName).each(function(){
                    $(this).attr(config.PlayListIndexAttributename, i);
                    i++;
                });
            };
            function UpdatePresentationPlayListCSSValues(_node){
                /**
                 @param node: <ul> representing a playlist
                 @Description: Update the css values of <li> representing each track of the playlist
                 */
                var i = 0;
                var currentClassName;
                var classValueString = '';
                $(_node).find('li').each(function(){
                    classValueString = $(this).attr('class');
                    if (classValueString.indexOf("even") >= 0) $(this).removeClass("even");
                    if (classValueString.indexOf("odd") >= 0) $(this).removeClass("odd");
                    
                    if ((i++) % 2) {
                        $(this).addClass("even");
                    } else {
                        $(this).addClass("odd");
                    }
                    
                });
            };
            
            function CreateTrackListPerPlayList(_listID){
                /**
                 @param _listID: string PlaylistId
                 @Description: return all songid values that are member of the playlist in an array
                 */
                /**@comment: config.TrackWrapperClassName is "sortable-list-default"*/
                var str = [];
                $('#' + _listID).find(config.TrackWrapperClassName).each(function(){
                    str[str.length] = $(this).attr('songid');
                })
                return str;
            }
            
            
            function JSONSerialisationForPostBack(_node){
                var compiliedObjCollection = [];
                var testStr = '';
                $(_node).find(config.TrackWrapperClassName).each(function(){
                
                    compiliedObjCollection[compiliedObjCollection.length] = new TrackObject(this);
                    testStr += (compiliedObjCollection[compiliedObjCollection.length - 1].TrackID + ",")
                })
                return testStr;
            }
            
            /*
             function InitialisePlayersPlayList(_array) {
             CreatePlayList();
             }
             */
            function TrackObject(_src){
                this.palyListOrder = $(_src).find(config.PlayListIndexDomContainerClassName).eq(0).text();
                this.TrackID = $(_src).attr('songid');
            }
            
            function PlayList(_src){
                /**@param _src: <li class="sortable-list-default"> representing each track*/
                
                /**@comment $(_src).attr('id') = VideoId*/
                this.ListName = $(_src).attr('id');
                this.currentStatus = "hidden";
                
                /**@comment: Recieving an array containing songid values that are member of the playlist*/
                this.memberTracks = CreateTrackListPerPlayList(this.ListName);
            }
            function adhocPlayList(_pl){
                /**@param _pl: playlist object*/
                
                /**@comment $(_src).attr('id') = VideoId*/
                var tracks = "", tempStr = [];
                var theId = _pl.PlaylistId.replace(" ", "");
                $(_pl.Entries).each(function(g){
                    tempStr[g] = this.VideoId;
                });
                
                this.ListName = _pl.PlaylistId;
                this.currentStatus = "hidden";
                this.memberTracks = tempStr;
            }
            
            function UpdateVideoPlayHeadEvtHandler(_videoID, _listID){
                /**
                 @param _videoID: int songid returned from the flash video player that is just begun to play
                 @param _listID: value of playList id that is currently being played
                 @Description: move the speaker icon in the list, and updates the song title and artist name on the header of the video player
                 */
                var classValueString = '';
                /**@comment: CSS updates for highlighting a list item*/
                // $('ul#' + _listID + ' li').each(function() {
                //     classValueString = $(this).attr('class');
                //     if (classValueString.indexOf('Current') >= 0) $(this).removeClass('Current');
                // });
                $('#VideoTopController a.PlayedDownload').hide();
                $('#VideoTopController a.PlayedTooltip').hide();
                if ($('ul#' + _listID + ' li[songid="' + _videoID + '"] div.Buy a').attr('href')) {
                    $('#VideoTopController a.PlayedDownload').attr('href', $('ul#' + _listID + ' li[songid="' + _videoID + '"] div.Buy a').attr('href'));
                    $('#VideoTopController a.PlayedDownload').show();
                }
                $('#VideoTopController a.PlayedTooltip').show();
                $('.PlayListHTMLTemplate li').each(function(){
                    $(this).removeClass('Current')
                });
                
                /**@comment: updates artist name and song title on the header of the video player*/
				
				if ($('ul#' + _listID + ' li[songid="' + _videoID + '"] div.ArtistName').text()) {
					$('#PlayedAuthor').html($('ul#' + _listID + ' li[songid="' + _videoID + '"] div.ArtistName').text());
					$('#PlayedSong').html($('ul#' + _listID + ' li[songid="' + _videoID + '"] div.SongTitle').text());
					
					$('#VideoTopController').get(0).songId = _videoID;
					
					
					/**@comment: CSS updates for highlighting a list item*/
					$('ul#' + _listID + ' li[songid="' + _videoID + '"]').addClass('Current');
					
					/**@comment: CSS updates for displaying a list item in the view*/
					$('ul#' + _listID).stop().scrollTo('li[songid="' + _videoID + '"]', 400);
					
					channelv.Page.VideoPlayListControllerObject.SetCurrentlySelectedVideoInHTML(_videoID);
				}
                if (this.TempAdHocId != "") {
                    movideoplayer.removeFromPlaylistCall(this.TempAdHocId, 'video');
                    this.AdHocId = "";
                    this.TempAdHocId = "";
                }
				if ($("#playList_tabs").height() > 24) {
					var _LI=$('#playList_tabs ul li')
                	if (_LI.eq(1).hasClass('set')) _LI.eq(1).find('a').click();
					if (_LI.eq(2).hasClass('set')) _LI.eq(2).find('a').click();
					if (_LI.eq(3).hasClass('set')) _LI.eq(3).find('a').click();
				}
            }
            
            /*
             function PostUpdatedTrackIndex() {
             var playList, TrackIndexCollection;
             $.ajax({
             type: "POST",
             url: "",
             data: '{"username":"' + txt_UserName + '","password":"' + txt_Password + '","isPersistent":false}',
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             success: function(result) {
             }
             });
             }*/
            //function UpdateClientPlayLists() {}
        
            //function RequestPlayLists() {
            //$.getJSON($.page.ui.url.ajaxEndPointSliderRequest + _sliderPos, function(data) {});
            //}
        
        
        
        }
    });
    
    
})(jQuery);
function doPlayBackVideo(_songid, _playlistId){
    /**
     @param _songid: string songid value to play
     */
    //$.page.assets.VideoPlayListControllerObject.doPlayBack(_songid);
    //channelv.Page.VideoPlayListControllerObject.SetCurrentlyPlayedPlayListInFlash('Top20');
    //$('.PlayListHTMLTemplate li').each(function(){$(this).removeClass('Current')});
    channelv.Page.VideoPlayListControllerObject.SetCurrentlySelectedPlayListInHTML(_playlistId)
    channelv.Page.VideoPlayListControllerObject.doPlayBack(_songid);
}

function doPlayBackVideoOriginal(_songid){
    /**
     @param _songid: string songid value to play
     */
    //$.page.assets.VideoPlayListControllerObject.doPlayBack(_songid);
    //channelv.Page.VideoPlayListControllerObject.SetCurrentlyPlayedPlayListInFlash('Top20');
    //$('.PlayListHTMLTemplate li').each(function(){$(this).removeClass('Current')});
    channelv.Page.VideoPlayListControllerObject.SetCurrentlySelectedPlayListInHTML('Channel [V] Top 20')
    channelv.Page.VideoPlayListControllerObject.doPlayBack(_songid);
}

function doPlayBackUserVideo(_songid){
    /**
     @param _songid: string songid value to play
     */
    //$('.PlayListHTMLTemplate li').each(function(){$(this).removeClass('Current')});
    channelv.Page.VideoPlayListControllerObject.SetCurrentlySelectedPlayListInHTML('playlistUser');
    channelv.Page.VideoPlayListControllerObject.doPlayBack(_songid);
    
}

function doPlayOneVideo(_songid, _ArtistName, _SongTitle, _buyLink){
    /**
     @param _songid: string songid value to play
     */
    $('.PlayListHTMLTemplate li').each(function(){
        $(this).removeClass('Current')
    });
    channelv.Page.VideoPlayListControllerObject.AdHocId = _songid;
    
    channelv.Page.VideoPlayListControllerObject.doPlayOneSong(_songid, _ArtistName, _SongTitle, _buyLink);
    
    
    //$.scrollTo('.sliderMenu',400);
}

function doDeleteTrackFromList(_songid, _node){
    var id = $(_node).parents("ul").eq(0).attr('id');
    channelv.Page.VideoPlayListControllerObject.doDeleteTrack(_songid, _node);
    
    if (id == "playlistUser") {
    
        channelv.Page.VideoPlayListController.updateUserPlaylist();
		
		var hgt = 0;
		$('#playlistUser').css({'visibility':'hidden'}).find('li').each(function(){hgt+=$(this).height();});
		hgt+=10;
		if (hgt<75)hgt=75;
		if (hgt>170)hgt=170;	
		$('#playlistUser').height(hgt+'px').css({'visibility':'visible'});
		fixPlaylistHeight();
		
    }
}

function addFullPlaylist(o){
    var par = $(o).parent();
    var Ttl = $(o).parent().siblings('.plst_TitleCell').eq(0).find('a').text();
    var sngsLi = $(par).next('li').find('ul li.clearfix');
    var _plst = {}
    var Entries = [];
    var ttl = "";
    ttl = Ttl.replace(/'/g, "");
    ttl = ttl.replace(/ /g, "");
    if (!channelv.Page.VideoPlayListControllerObject.isPlayListNameUsed(ttl)) {
        var _l = $('div.PlayListHTMLTemplate > ul').length;
        var htmlStr = "";
        htmlStr += '<div id="lh_' + ttl + '" class="ListHeader LH' + _l + '" onclick="channelv.Page.VideoPlayListControllerObject.SetCurrentlySelectedPlayListInHTML(\'' + ttl + '\');">' + Ttl + '</div>';
        htmlStr += '<ul id="' + ttl + '" class="sortablePlayList addedPlaylist clearfix"></ul>';
        
        $(sngsLi).each(function(i){
            if (!channelv.Page.VideoPlayListControllerObject.IsThisIdInThePlayListCurrentlyPlayed($(this).attr('VideoId'), ttl)) {
                var song = {};
                song.ArtistName = $(this).attr('ArtistName');
                song.SongTitle = $(this).attr('SongTitle');
                song.VideoId = $(this).attr('VideoId');
                song.BuyLink = $(this).attr('BuyLink');
                Entries[i] = song;
            }
        });
        _plst.Entries = Entries;
        _plst.PlaylistId = ttl;
        $('.PlayListHTMLTemplate').eq(0).append(htmlStr);
        channelv.Page.VideoPlayListController.addToClientPlayList(_plst, ttl);
    }
}


function addFullCategoryPlaylist(categoryName){

    $.ajax({
        type: "GET",
        
        url: "/MediaPlayerService.svc/GetLatestPlaylistForCategory?category=" + categoryName,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result){
            var ttl = result.PlaylistId;
            var Ttl = result.PlaylistName;
			
            if (!channelv.Page.VideoPlayListControllerObject.isPlayListNameUsed(ttl)) {
                var _l = $('div.PlayListHTMLTemplate > ul').length;
                var htmlStr = "";
                htmlStr += '<div id="lh_' + ttl + '" class="ListHeader LH' + _l + '" onclick="channelv.Page.VideoPlayListControllerObject.SetCurrentlySelectedPlayListInHTML(\'' + ttl + '\');">' + Ttl + '</div>';
                htmlStr += '<ul id="' + ttl + '" class="sortablePlayList addedPlaylist clearfix"></ul>';
                $('.PlayListHTMLTemplate').eq(0).append(htmlStr);
                channelv.Page.VideoPlayListController.addToClientPlayList(result, ttl);
            }
        }
    });
}

function addFullNamedPlaylist(categoryName){

    $.ajax({
        type: "GET",
        
        url: "/MediaPlayerService.svc/GetPlaylistForName?name=" + categoryName,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result){
            var ttl = result.PlaylistId;
            var Ttl = result.PlaylistName;
            if (!channelv.Page.VideoPlayListControllerObject.isPlayListNameUsed(ttl)) {
                var _l = $('div.PlayListHTMLTemplate > ul').length;
                var htmlStr = "";
                htmlStr += '<div id="lh_' + ttl + '" class="ListHeader LH' + _l + '" onclick="channelv.Page.VideoPlayListControllerObject.SetCurrentlySelectedPlayListInHTML(\'' + ttl + '\');">' + Ttl + '</div>';
                htmlStr += '<ul id="' + ttl + '" class="sortablePlayList addedPlaylist clearfix"></ul>';
                $('.PlayListHTMLTemplate').eq(0).append(htmlStr);
                channelv.Page.VideoPlayListController.addToClientPlayList(result, ttl);
            }
        }
    });
}

function addFullUserPlaylist(){

    $.ajax({
        type: "GET",
        
        url: "/MediaPlayerService.svc/GetUserPlaylist",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result){
            //result.d.WasSent = true;
            fixedResult = new Object();

            $('#lh_playlistUser').text(result.PlaylistName);
            var fEntries = [];
            var inUPlaylist = [];
            if ($('ul#playlistUser li').length > 0) {
                $('ul#playlistUser li').each(function(i){
                    inUPlaylist[i] = $(this).attr('songid');
                });
                
                var k = 0;
                
                for (j = 0; j < result.Entries.length; j++) {
                    var unique = true;
                    for (h = 0; h < inUPlaylist.length; h++) {
                        if (inUPlaylist[h] == result.Entries[j].VideoId) unique = false;
                    }
                    if (unique) {
                        fEntries[k] = result.Entries[j];
                        k++;
                    }
                }
                fixedResult.Entries = fEntries;
                fixedResult.PlaylistId = 'playlistUser';
                channelv.Page.VideoPlayListController.addToClientPlayList(fixedResult, 'playlistUser');
            } else channelv.Page.VideoPlayListController.addToClientPlayList(result, 'playlistUser');
        }
    });
    
    
}


function addSongToPlaylist(_ArtistName,_SongTitle,_VideoId,_BuyLink){
    if (!channelv.Page.VideoPlayListControllerObject.IsThisIdInThePlayListCurrentlyPlayed( _VideoId, 'playlistUser')) {
        var _plst = {}
        var Entries = [];
        var song = {};
        song.ArtistName = _ArtistName;
        song.SongTitle = _SongTitle;
        song.VideoId = _VideoId;
        song.BuyLink = _BuyLink;
        Entries[0] = song;
        _plst.Entries = Entries;
        _plst.PlaylistId = "playlistUser";
        channelv.Page.VideoPlayListController.addToClientPlayList(_plst, _plst.PlaylistId);
        channelv.Page.VideoPlayListController.updateUserPlaylist();
    }
}

function addSingleToPlaylist(o){
    var par = $(o).parent().parent();
    if (!channelv.Page.VideoPlayListControllerObject.IsThisIdInThePlayListCurrentlyPlayed($(par).attr('VideoId'), 'playlistUser')) {
    
        var _plst = {}
        var Entries = [];
        var song = {};
        song.ArtistName = $(par).attr('ArtistName');
        song.SongTitle = $(par).attr('SongTitle');
        song.VideoId = $(par).attr('VideoId');
        song.BuyLink = $(par).attr('BuyLink');
        Entries[0] = song;
        
        _plst.Entries = Entries;
        _plst.PlaylistId = "playlistUser";
        channelv.Page.VideoPlayListController.addToClientPlayList(_plst, _plst.PlaylistId);
        
        channelv.Page.VideoPlayListController.updateUserPlaylist();
        
    }
    //else $.scrollTo('.sliderMenu',400);
}

/* =================================== */
function shrinkExpandPlaylist(_node){
    var _p = $(_node).parent();
    if ($("#playList_tabs").height() < 30) {
        var vcHeight;
        vcHeight = _p.find('tabs').eq(0).height() + $('#playList_tabs').height();
        if ($('#fragment-1').css('display') == 'block') vcHeight = vcHeight + $('#fragment-1').height();
        if ($('#fragment-2').css('display') == 'block') vcHeight = vcHeight + $('#fragment-2').height() + 23;
        if ($('#fragment-3').css('display') == 'block') vcHeight = vcHeight + $('#fragment-3').height();
        if ($('#fragment-4').css('display') == 'block') vcHeight = vcHeight + $('#fragment-4').height();
        $("#playList_tabs").animate({
            height: vcHeight + 'px'
        }, 800);
        $("#playlistCloser").removeClass("set");
    } else {
		$("#playList_tabs").animate({ height: '24px'}, 800);
        $("#playlistCloser").addClass("set");
    }
    
}

function fixPlaylistHeight(_node){

    var vcHeight;
    vcHeight = $('#playList_tabs .tabs').eq(0).height();
    if ($('#fragment-1').css('display') == 'block') vcHeight = vcHeight + $('#fragment-1').height();
    if ($('#fragment-2').css('display') == 'block') vcHeight = vcHeight + $('#fragment-2').height() + 23;
    if ($('#fragment-3').css('display') == 'block') vcHeight = vcHeight + $('#fragment-3').height();
    if ($('#fragment-4').css('display') == 'block') vcHeight = vcHeight + $('#fragment-4').height();
    
    $("#playList_tabs").animate({
        height: vcHeight + 'px'
    }, 400);
}

function socialTooltip(videoId){
    $.ajax({
        type: "GET",
        data: videoId,
        url: "/MediaPlayerService.svc/GetVideoTooltip?videoId=" + videoId,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data){
            $('#vplTooltipContainer').empty();
            $('#vplTooltipContainer').html(data.Content)
            $('#vplTooltipContainer').click(function(event){
                event.stopPropagation();
            });
        }
    });
}

function closeVPTT(){
    $('#vplTooltipContainer').toggle().empty();
}

function openUserPlst(){
	var UsrPlst = $('#playlistUser')
	
	if (!UsrPlst.hasClass('selected')){
	var Hdr =$('div.ListHeader');
	Hdr.each(function(i){
		$(this).removeClass('selected').next().height('0px').css({'display':'none'});
	 });
	}
	 var hgt = 0;
	$('#playlistUser').css({'display':'block','visibility':'hidden'}).find('li').each(function(){hgt+=$(this).height();});
	hgt+=10;
	if (hgt<75)hgt=75;
	if (hgt>170)hgt=170;	
	$('#playlistUser').height(hgt+'px').css({'visibility':'visible'});
	$('#lh_playlistUser').addClass('selected');
	fixPlaylistHeight();
	if($('#playlistCloser').hasClass('set')){$('#playlistCloser').removeClass('set');}
}
function plstAccordeon() {
	 var Hdr =$('div.ListHeader');
	 var Index = Hdr.index(this);
	Hdr.each(function(i){
		
		if (Index==i){
			if ($(this).hasClass('selected')){
				$(this).removeClass('selected').next().height('0px').css({'display':'none'});
			}else{
				var hgt = 0;
				$(this).next().css({'display':'block'}).find('li').each(function(){hgt+=$(this).height();});
				hgt+=10;
				if (hgt<75)hgt=75;
				if (hgt>170)hgt=170;	
				$(this).addClass('selected').next().height(hgt+'px');
			}
		}else{
			$(this).removeClass('selected').next().height('0px').css({'display':'none'});
		}
	});
	fixPlaylistHeight();
 }