// broadband.js
// For use with the Broadband Video application
// Created by Filemobile
//
// version 1.4
// last edited: September 29th 2010

// Called by the JWPlayer when it's completed loading
function playerReady() {
    var player = document.getElementById ( "vp" );

    player.addModelListener ( "STATE", "fmBroadband.playStateChanged" );
}

var fmBroadband = new function () {
    this.currentMediaID = false;

    // String that will be prepended to media IDs when used in the URI
    this.videoHashPrefix = "clip";

    this.playStateChanged = function ( obj ) {
        try {
            if ( obj [ "newstate" ] == "PLAYING" ) {
                var playlist = document.getElementById ( "vp" ).getPlaylist ();

                if ( playlist && ( playlist.length > 0 ) ) {
                    // Since we're not making use of JWPlayer's playlists our currently playing video should
                    // always be the first (and only) item in the playlist.
                    var mediaID = this.extractMediaIDFromFilename ( playlist [ 0 ].file );

                    if ( mediaID != this.currentMediaID ) {
                        this.currentMediaID = mediaID;
                        this.updateNowPlaying ( this.currentMediaID );
                    }
                }
            }
        } catch ( ex ) {
            // No action, simply can't update the display of the currently playing item
        }
    };

    this.updateNowPlaying = function ( mediaID ) {
        this.updateVideoURL ( mediaID );
        this.updateNowPlayingPlaylist ( mediaID );
        this.updateNowPlayingGallery ( mediaID );

        try {
            jsonRequest (
                "media.getFileInfo",
                { "id": mediaID },
                function ( result ) { getFileInfoResult ( result, null, false ); recalcDesc (); },
                function ( exception ) { getException ( exception ); }
            );
        } catch ( ex ) {
            console.log ( "Exception thrown when calling getFileInfo to update the currently playing video", ex );
        }
    };

    this.updateVideoURL = function ( mediaID ) {
        document.location.hash = this.videoHashPrefix + mediaID;

       	$( "clipurl" ).value = document.location.toString ();
    };

    this.updateNowPlayingPlaylist = function ( mediaID ) {
        this.updateNowPlayingTag ( "nowplaying", "playlist", mediaID );
    };

    this.updateNowPlayingGallery = function ( mediaID ) {
        this.updateNowPlayingTag ( "nowplayinggallery", "gallery", mediaID );
    };

    this.updateNowPlayingTag = function ( nowPlayingTagID, containerElement, mediaID ) {
		// remove the old now playing label
		if ( $( nowPlayingTagID ) ) {
			$( nowPlayingTagID ).remove ();
        }

        var currentVideoTitleElement = $$( "#" + containerElement + "-" + mediaID + " .title" ).first ();

        if ( typeof currentVideoTitleElement != "undefined" ) {
            currentVideoTitleElement.update ( "<span id='" + nowPlayingTagID + "'>" + window.nowPlayingMessage + "</span> " + currentVideoTitleElement.innerHTML );
        }
    };

    // This finds the last integer from a filename, we're using this as the video player doesn't have a
    // consistently populated media ID property.
    this.extractMediaIDFromFilename = function ( filename ) {
        return filename.replace ( /^.*?([0-9]+)$/, "$1" );
    };

    // Retrieves the media ID present in the hash of the URL if present otherwise returns null
    this.getHash = function ( url ) {
        var hashMatcher = new RegExp ( "^.*#" + this.videoHashPrefix + "(\\d+)" );

        var mediaID = parseInt ( url.replace ( hashMatcher, "$1" ), 10 );

        if ( mediaID ) {
            return mediaID;
        } else {
            return null;
        }
    }
}

// Video player will call this when a related video thumbnail is clicked. This function must
// exist at the document level to ensure it's visible to Flash via the ExternalInterface.
function relatedVideoClicked ( mediaID ) {
    fmBroadband.updateNowPlaying ( mediaID );
}

// Resizes the playlist so it fills the right side column depending on its siblings
function resizePlaylist() {
	// set the variables
	var parent = $$('div.rightside')[0];
	var c = parent.childElements();
	var height = 0;
	var margins = 0;
	// for each sibling, add thier height and 10px for spacing
	for (i=0;i<c.length;i++) {
		if (c[i].getStyle('display') != 'none' && c[i].id != 'playlist') {
			height += c[i].getHeight();
			margins += 10;
		}
	}
	// create the final height of the playlist
	var finalHeight = 533-height-margins;
	// if the height is too small, make it a good size
	if (finalHeight < 60) {
		finalHeight = '60';
	}
	// set the playlist height
	$('scrollbar_playlist').setStyle({'height' : finalHeight+'px'});
}

// the flash videoplayer calls this function to find the next item to play
function getNextItem() {
	// only send an item if there is a playlist
	if (window.playlist) {
		// set the vars
		var playlist = window.playlist;
		var mid = window.mid;
		var p = playlist.position(mid);
		
		if ( typeof playlist [ p + 1 ] == "undefined" )
			return null;
			
		var nextItem = playlist[p+1].toString();

		return parseInt ( nextItem, 10 );
	}
	// return null if there is nothing to be played
	return null;
}

// converts the video length in seconds to timecode
function lengthToTime(x) {
	// set the vars, d is the duration, t is for time, m is for minutes, s is for seconds. easy eh?
	var d = x;
	var t = 0;
	var m = 0;
	var s = 0;
	// t is for time
	t = d/60;
	// if the video is longer then 60 minutes, add the hours
	if (t >= 60) {
		var h = parseInt(t/60);
		t = (t/60 - h) *60;
		var hOut = h+":";
	} else {
		var hOut = "";
	}
	// set the number of minutes
	m = t.toString();
	if (m != "" && parseInt(m) > 0) {
		m = m.substr(0,m.lastIndexOf("."));
	} else {
		m = "00";
	}
	// set the number of seconds
	s = t.toString();		
	s = s.substr(s.lastIndexOf("."),s.length);
	s = parseInt(s*60);
	// make the seconds and minutes into numbers
	s = parseFloat(s);
	m = parseFloat(m);
	// add a leading zero to minutes if the video is longer then an hour
	if (m < 10 && hOut) {
		m = "0"+m;
	}
	// add a leading zero to the seconds
	if (s < 10) {
		s = "0"+s;
	}
	// return the duration
	return hOut+m+":"+s;
}
// this is used by the video player to find what video to play. It listens for this function to be called on object or embed element;
// for example: document.getElementById('vp').newVideo(mid);
function newVideo(mid) {
	return mid;
}

// after requesting a video, this function places the all the video's info into the top left of the player
function getFileInfoResult(result,playlist, callPlayVideo) {
    if ( typeof callPlayVideo == "undefined" ) {
        callPlayVideo = true;
    }

	// set the vars
	var mid = result.id;
	window.nowPlaying = mid;
	window.mid = mid;
	var title = result.title;
	// if the file is an image, it won't have a duration	
	if (result.filetype == "1") {
		var dur = ""
	} else {
		var dur = lengthToTime(result.length);
	}
	//
	if (result.channel_name) {
		var catTime = result.channel_name+" / "+dur;
	} else {
		var catTime = dur;
	}
	//
	var ugc = '';
	//
	if (result.metadata.ugc == 'true') {
		if (result.user_name.substr(0,8) != 'userless') {
			ugc = ' / uploaded by: '+result.user_name;
		} else {
			ugc = ' / uploaded by: '+result.user_firstname+' '+result.user_lastname;
		}
	}
	// these might be used later so we better make them easier to write
	var desc = result.message;
	var thumb = result.publicUrl;
	var vote = result.votecount;
	var baseurl = window.location.href.substr(0,window.location.href.lastIndexOf('#')-1);

	// place the results into their respective place
	$('videotitle').innerHTML = title;
	$('videocat').innerHTML = catTime + ugc;
	$('scrollbar_desc').innerHTML = desc;
	// adds the video name to the title bar
	if(window.location.hash){
		var pipe = document.title.lastIndexOf("|");
		if (pipe>0) {
			document.title = document.title.substr(0,pipe)+"| "+title;	
		} else {
			document.title = document.title+" | "+title;
		}
	}
	//
	// send the mid to the video player
	try {
		if ((playlist !== true) && callPlayVideo ) {
			document.getElementById('vp').newVideo(mid.toString());
		}
	} catch (ex) {
		//console.log(ex);
	}

    fmBroadband.updateNowPlayingGallery ( mid );

	// set the various links and onclicks for the sharelizer
	//
	//$('s_facebook').href = 'http://www.facebook.com/share.php?u='+baseurl+'/view/'+mid+'&t='+title;
	$('s_facebook').observe('click',function(event){
		//console.log(window.location);
		//console.log(baseurl);
		Sharer.fbShare(mid,title,baseurl+'/view/'+mid);
		return false;
	});
	//
	$('s_digg').href = 'http://digg.com/submit?phase=2&url='+baseurl+'/view/'+mid+'&title='+title;
	$('s_facebook').observe('click',function(event){
		Sharer.click(this,'digg',mid); 
		return false;
	});
	//
	$('s_delicious').href = 'http://del.icio.us/post?url='+baseurl+'/view/'+mid+'&title='+title;
	$('s_delicious').observe('click',function(event){
		Sharer.click(this,'delicious',mid); 
		return false;
	});
	//
	$('s_twitter').href = 'http://twitter.com/?status=Watching: '+escape(title)+' - '+escape(window.location);
	$('s_twitter').observe('click',function(event){
		Sharer.click(this,'twitter',mid); 
		return false;
	});
	//
	document.getElementById('friendmid').value = mid;
}

// Retrieves a media ID from the hash in the current URI if present
function getHash () {
	window.gotHash = true;

    return fmBroadband.getHash ( document.location.toString () );
}

document.observe (
    'dom:loaded', 
    function(){
        function retryGetHash () {
            if ( !window.gotHash ) {
                var mediaID = fmBroadband.getHash ( document.location.toString () );

                if ( mediaID ) {
                    var html = $( "videoplayer" ).innerHTML.replace ( /source\s*:\s*'.*?'/g, "source:'" + mediaID + "'" );

                    $( "videoplayer" ).innerHTML = html;
                    loadVideo ( mediaID );
                }
            }
        }

        retryGetHash();

        // the onclick function for "add to playlist" icon
        function setGallery() {
            $$('#gallery div.media').each(function(s) {
                    var x = $(s).down(0).next(1).descendants();
                    var y = x[x.length-1];
                    y.observe('click',function(event){
                            var mid = $(s).id.substr($(s).id.lastIndexOf("-")+1);
                            var t = s.innerHTML;
                            y.hide();
                            addToPlaylist(t,mid);
                        });
                });
        }

        // if there is hash tag in the URL when the user first visits the page (getting a link to a specific video) load that video

        function loadVideo(mid) {
            if (window.nowPlaying == mid) {
                // the user is trying to play the video that's already playing
            } else {	
                window.nowPlaying = mid;
                getFileInfo(mid);		
                if ($('playlist-'+mid)) {
                    createPlaylist();
                }
            }	
        }

        // used for the playlist cookie. om nom nom
        function createCookie(name,value,days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
            }
            else var expires = "";
            document.cookie = name+"="+value+expires+"; path=/";
        }

        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
            }
            return null;
        }

        function eraseCookie(name) {
            createCookie(name,"",-1);
        }
        // requests media for the playlist
        function getPlaylistMedia( id, uid, returnComments ) {
            var params = {
                "id" : id,
                "uid" : uid,
                "returnComments" : returnComments
            }
	
            jsonRequest('media.getFileInfo', params,
                function(result)     { getPlaylistMediaResult(result); },
                function(exception)  { getException(exception); }
            );
        }
        // used to create the display the playlist
        function getPlaylistMediaResult(r) {
            var out = "";
            out = '<div class="media clearfix" id="playlist-'+r.id+'">'+
				'<a href="#' + fmBroadband.videoHashPrefix + r.id+'" class="left"><img src="'+r.thumbUrl+'/13" alt="thumbnail" class="thumbimg"/><div class="thumbcorner"></div></a>'+
				'<div class="info clearfix">'+
                '<a href="#' + fmBroadband.videoHashPrefix + r.id+'" class="title">'+r.title+'</a>'+
                '<span class="category">'+r.channel_name+'</span>'+
                '<span class="duration">'+lengthToTime(r.length)+'</span>'+
				'</div>'+
				'<div class="action">'+
                '<span class="icon"></span>'+
				'</div>'+
                '</div>';	
            $('addbefore').insert( { before: out });
            createPlaylist(false);
            setPlaylist();
            //
            if($('gallery-'+r.id)) {
                $('gallery-'+r.id).down(0).next(1).down(0).hide();
            }
        }

        if (editorsPlaylist.length > 0) {
            for(i=0;i<editorsPlaylist.length;i++) {
                getPlaylistMedia(editorsPlaylist[i]);
            }
            if (!window.gotHash) {
                loadVideo(editorsPlaylist[0]);
            }
            window.playlist = editorsPlaylist;
        } else {
            if (readCookie('playlist')) {	
                var pArray = readCookie('playlist').split(',');	
                for(i=0;i<pArray.length;i++) {
                    getPlaylistMedia(pArray[i]);
                }
                if (!window.gotHash) {
                    loadVideo(pArray[0]);
                }
                window.playlist = pArray;
            }	
        }

        // the onclick function to load the video and all it's infomation
        function getGalleryVideos() {
            $$('#scrollbar_content a').each(function(s) {
                    $(s).observe('click',function(event){
                            var mediaID = fmBroadband.getHash ( $( s ).href );

                            if ( !mediaID ) {
                                console.log ( "Failed to find a media ID in the gallery item's href, href was \"" + $( s ).href + "\"" );

                                return;
                            }

                            if ($('nowplaying')) {
                                $('nowplaying').remove();
                            }
                            if ($('nowplayingGallery')) {
                                $('nowplayingGallery').remove();
                            }

                            scroll(0,0);
			
                            loadVideo ( mediaID );
                        }); 
                });
            scrollbar.recalculateLayout();
        }

        function fadeOutOverlay() {
            $('light').toggleClassName('toggle');
            // start return the video player to its original position
            new Effect.Move($('videoplayer').down(0), { x: 0, y: 0, duration:0.5, mode: 'absolute' });
            // end return video player to its original position
            new Effect.Fade ( $('dialog_overlay'), { duration: 0.5, from: 0.8, to: 0,
                        'afterFinish': function () {
                        $('dialog_overlay').remove();
                    }
            });	
        }

        // used for theater mode to add the lightbox effect
        function addOverlay() {
            if (!$('dialog_overlay')) {
                $('light').toggleClassName('toggle');
                //var h = document.body.getHeight();
                var h = document.body.clientHeight;
                // For some reason, the overlay doesn't always reach the bottom. Change this number so it does.
                var offset = 20;
                // create the overlay
                var overlay = document.createElement('div');
                overlay.id = 'dialog_overlay';
                //document.body.insert(overlay, document.body);
                document.getElementsByTagName('body')[0].appendChild(overlay);
                //
                $('dialog_overlay').setStyle({ position: 'absolute', top: 0, left: 0, zIndex: 900, width: '100%', backgroundColor: '#000', display: 'block', height: h+offset+"px", opacity: '0' });
                $(overlay).fade({ duration: 0.5, from: 0, to: 0.9 });
                $(overlay).observe('click', function(event) { fadeOutOverlay() });
                // start move video player
                var v = $('videoplayer');
                var vW = $('videoplayer').getWidth();
                var vH = $('videoplayer').getHeight();
                if (typeof window.innerWidth != 'undefined') {
                    var wH = window.innerHeight
                        } else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
                    var wH = document.documentElement.clientHeight
                        } else {
                    var wH = document.getElementsByTagName('body')[0].clientHeight
                        }
                //
                var dW = (960-vW)/2;
                var dH = (wH-vH)/2-30-$('header').getHeight(); // We subtact 30 beacuse of the padding between the top of the page, the header and the wrapper
                new Effect.Move($('videoplayer').down(0), { x: dW, y: dH, duration:0.5, mode: 'absolute' });
                // end move video player
            } else {
                fadeOutOverlay();
            }
        }	

        // json call used by loadvideo() to get the video's info
        function getFileInfo ( id, callPlayVideo ) {
            var params = {
                "id" : id
            }
	
            if ( typeof callPlayVideo == "undefined" ) {
                callPlayVideo = true;
            }
	
            jsonRequest('media.getFileInfo', params,
                function(result)     { getFileInfoResult(result, null, callPlayVideo); recalcDesc(); },
                function(exception)  { getException(exception); }
            );
        }
        // used to find the position of a value in an array
        Array.prototype.position = function (s) {
            var i = 0;
            while (i < this.length && this [i] != s) {i++};
            return i < this.length ? i : undefined;
        }
        // 
        function getPlaylistFileResult(result,mid) {
            var newItem = '<div class="media" id="playlist-'+mid+'">'+result+'</div>';
            $('addbefore').insert( { before: newItem });	
            setPlaylist();
            createPlaylist();
        }

        // if an error has occurred during the ajax calls, log it
        function getException(exception) { console.log(exception); }

        // adds click functions to media items in the playlist
        function setPlaylist() {
            $$('#playlist div.media').each(function(s) {
                    var x = $(s).down(0).next(1).descendants();
                    var y = x[x.length-1];
                    y.observe('click',function(event){
                            var mid = $(s).id.substr($(s).id.lastIndexOf("-")+1);
                            if ($('gallery-'+mid)) {
                                var a = $('gallery-'+mid).down(0).next(1).descendants();
                                var b = a[a.length-1];
                                b.show();
                                $('gallery-'+mid).down(0).next(1).show().fade({ duration: 0.5, from: 0, to: 1 });
                            }
                            this.hide();
                            $(s).remove();
                            createPlaylist();
                            recalcP();
                            recalcP();
                        });
                    $(s).down(0).observe('click',function(event){
                            var mediaID = fmBroadband.getHash ( this.href );

                            if ( mediaID ) {
                                loadVideo ( mediaID );
                            } else {
                                console.log ( "Failed to find a mediaID in playlist item's href, href was \"" + this.href + "\"" );
                            }
                        });
                    $(s).down(0).next(0).down(0).observe('click',function(event){
                            var mediaID = fmBroadband.getHash ( this.href );

                            if ( mediaID ) {
                                loadVideo ( mediaID );
                            } else {
                                console.log ( "Failed to find a mediaID in playlist item's href, href was \"" + this.href + "\"" );
                            }
                        });
                });		
        }

        // copies the media items to the playlist
        function createPlaylist(updatePlaylist) {
            var playlist = [];
            $$('#playlist div.media').each(function(s) {
                    playlist = playlist.concat($(s).id.substr($(s).id.lastIndexOf("-")+1));
                });	
	
            window.playlist = playlist;

            if (playlist.length <= 0) {
                $('noplaylist').show();
            } else {
                $('noplaylist').hide();
            }
		
            if ($('nowplaying')) {
                $('nowplaying').remove();
            }	

            if ( window.nowPlaying ) {
                fmBroadband.updateNowPlayingPlaylist ( window.nowPlaying );
            }
	
            // if the item in the gallery is currently playing, we have to remove it's "nowplayingGallery" element
            // or it will double up "'+window.nowPlayingMessage+'" in the playlist.
            if($$('#playlist #nowplayingGallery')[0]) {
                //console.log($$('#playlist #nowplayingGallery')[0]);
                $$('#playlist #nowplayingGallery')[0].remove();
            }
	
            recalcP();

            if (!updatePlaylist) {
                createCookie('playlist',playlist,3);
            }

        }

        function addToPlaylist(s,mid) {
            getPlaylistFileResult(s,mid);
            //num = $('playlist').down(0).next(0).down(1).nextSiblings().length;
        }

        function showLoader(divid) {
            var out = '<img src="'+window.loadingPath+'" id="loading" alt="Loading..." />';
            $(divid).innerHTML = out;
        }


        // create all the scrollbars
        var scrollbar = new Control.ScrollBar('scrollbar_content','scrollbar_track');
        var scrollbarPlaylist = new Control.ScrollBar('scrollbar_playlist','scrollbar_track_playlist');
        var scrollbarCategories = new Control.ScrollBar('scrollbar_categories','scrollbar_track_categories');
        var scrollbarSeasons = new Control.ScrollBar('scrollbar_seasons','scrollbar_track_seasons');
        var scrollbarEpisodes = new Control.ScrollBar('scrollbar_episodes','scrollbar_track_episodes');
        var scrollbarDesc = new Control.ScrollBar('scrollbar_desc','scrollbar_track_desc');

        // reset the size of the scrollbars
        scrollbar.recalculateLayout();
        scrollbarPlaylist.recalculateLayout();
        scrollbarCategories.recalculateLayout();
        scrollbarSeasons.recalculateLayout();
        scrollbarEpisodes.recalculateLayout();
        scrollbarDesc.recalculateLayout();

        function recalcC() {
            scrollbarCategories.recalculateLayout();
            scrollbarCategories.recalculateLayout();
        }

        function recalcS() {
            scrollbarSeasons.recalculateLayout();
            scrollbarSeasons.recalculateLayout();
        }

        function recalcE() {
            scrollbarEpisodes.recalculateLayout();
            scrollbarEpisodes.recalculateLayout();
        }

        function recalcP() {
            scrollbarPlaylist.recalculateLayout();
            scrollbarPlaylist.recalculateLayout();
        }

        function recalcClips() {
            scrollbar.recalculateLayout();
            scrollbar.recalculateLayout();
        }

        function recalcCat() {
            scrollbarCategories.recalculateLayout();
            scrollbarCategories.recalculateLayout();
        }

        function recalcDesc() {
            scrollbarDesc.recalculateLayout();
            scrollbarDesc.recalculateLayout();
        }



        // make sure the content at the top of the box is being displayed.
        scrollbar.scrollTo('top');
        scrollbarPlaylist.scrollTo('top');
        scrollbarCategories.scrollTo('top');
        scrollbarSeasons.scrollTo('top');
        scrollbarEpisodes.scrollTo('top');
        scrollbarDesc.scrollTo('top');

        $('clearplaylist').observe('click', function(event){
                var j = $('addbefore').previousSiblings().length;
	
                for (i=0;i<j;i++) {
                    var mid = $('addbefore').previous(0).id.substr($('addbefore').previous(0).id.lastIndexOf("-")+1);
                    $('addbefore').previous(0).remove();
                    if ($('gallery-'+mid)) {
                        $('gallery-'+mid).down(0).next(1).down(0).show();
                    }
                }
	
                eraseCookie('playlist');
	
                createPlaylist();		
                scrollbarPlaylist.recalculateLayout();
                scrollbarPlaylist.recalculateLayout();		
            });



        // controls the classes reponsibe for changing the layout of the gallery and playlist
        $('p-list').observe('click',function(event){
                $('p-detailed').className = "";
                $('p-tile').className = "";
                $('p-list').className = "active";
                //
                $('playlist_container').className = $('playlist_container').className.replace('detailed','list').replace('tile','list');
                //
                scrollbarPlaylist.recalculateLayout();
                scrollbarPlaylist.recalculateLayout();
                scrollbarPlaylist.scrollTo('top');
            }); 

        $('p-detailed').observe('click',function(event){ 
                $('p-list').className = "";
                $('p-tile').className = "";
                $('p-detailed').className = "active";
                //
                $('playlist_container').className = $('playlist_container').className.replace('list','detailed').replace('tile','detailed');
                //
                scrollbarPlaylist.recalculateLayout();
                scrollbarPlaylist.recalculateLayout();
                scrollbarPlaylist.scrollTo('top');
            }); 

        $('p-tile').observe('click',function(event){ 
                $('p-list').className = "";
                $('p-detailed').className = "";
                $('p-tile').className = "active";
                //
                $('playlist_container').className = $('playlist_container').className.replace('list','tile').replace('detailed','tile');
                //
                scrollbarPlaylist.recalculateLayout();
                scrollbarPlaylist.recalculateLayout();
                scrollbarPlaylist.scrollTo('top');
            });

        $('g-list').observe('click',function(event){
                scrollbar.scrollTo('top');
                $('g-detailed').removeClassName('active');
                $('g-tile').removeClassName('active');
                $('g-list').className = "active";
                //
                $('gallery_container').className = $('gallery_container').className.replace('detailed','list').replace('tile','list');
                //
                scrollbar.recalculateLayout();
                scrollbar.recalculateLayout();
                scrollbar.scrollTo('top');
            }); 

        $('g-detailed').observe('click',function(event){
                scrollbar.scrollTo('top');
                $('g-list').removeClassName('active');
                $('g-tile').removeClassName('active');
                $('g-detailed').className = "active";
                //
                $('gallery_container').className = $('gallery_container').className.replace('list','detailed').replace('tile','detailed');
                //
                scrollbar.recalculateLayout();
                scrollbar.recalculateLayout();
                scrollbar.scrollTo('top');
            }); 

        $('g-tile').observe('click',function(event){
                scrollbar.scrollTo('top');
                $('g-list').removeClassName('active');
                $('g-detailed').removeClassName('active');
                $('g-tile').className = "active";
                //
                $('gallery_container').className = $('gallery_container').className.replace('list','tile').replace('detailed','tile');
                //
                scrollbar.recalculateLayout();
                scrollbar.recalculateLayout();
                scrollbar.scrollTo('top');
            });  

        $('light').observe('click', function(event){
                addOverlay();
            });	

        getGalleryVideos();

        createPlaylist();

        recalcP();

        setPlaylist();

        setGallery();

        function getChannelTreeResult(result) {
            // json the results
            var json = { "result" : result };
            // make the channel varialbe global so we can use it elsewhere
            window.channels = json;
            // start the output
            var out = "<ul>";
            // if the seasons and episodes columns exist, display them
            if ($('scrollbar_seasons') && $('scrollbar_episodes')) {
                $('scrollbar_seasons').innerHTML = "";
                $('scrollbar_episodes').innerHTML = "";
                recalcS();
                recalcE();
            }
            // add most recent and mosst viewed sorting options to the top of the left menu
            out += '<li class="selected"><a id="c_recent">Most Recent</a></li>';
            out += '<li><a id="c_hits">Most Viewed</a></li>';
            //
            recalcClips();
            // add the list of channels to the output
            for (i=0;i<result.length;i++) {
                if (result[i].visibility === "SHOWN") {
                    // send getSubChannel(); the position of this subchannel in the json
                    out += '<li><a id="a_'+i+'">'+result[i].name+'</a></li>';
                }
            }
            // finish the output
            out += "</ul>";
            // print the output
            $('scrollbar_categories').innerHTML = out;
            scrollbarCategories.recalculateLayout();
            // add the click functions
            $$('#scrollbar_categories a').each(function(s) {
                    $(s).observe('click',function(event){
                            // if its the most recent link, add the select class and get the sorted media 
                            if (s.id == "c_recent") {
                                $$('#scrollbar_categories li.selected').each(function(s) { $(s).removeClassName("selected"); });	 $('scrollbar_seasons').hide(); $('scrollbar_episodes').hide(); $('scrollbar_container').setStyle({width: '80%'}); recalcE(); recalcClips(); recalcCat();
                                getChannelMedia(0,'Most Recent','recent','upload DESC');
                                // if its the most viewed link, add the select class and get the sorted media
                            } else if (s.id == "c_hits") {
                                $$('#scrollbar_categories li.selected').each(function(s) { $(s).removeClassName("selected"); });	 $('scrollbar_seasons').hide(); $('scrollbar_episodes').hide(); $('scrollbar_container').setStyle({width: '80%'}); recalcE(); recalcClips(); recalcCat();
                                getChannelMedia(0,'Most Viewed','hits','hits DESC');
                                // get the subchannels
                            } else {
                                var i = $(s).id.substr($(s).id.lastIndexOf("_")+1);
                                getSubChannel(i);
                            }
                        }); 
                });
	
            recalcCat();
        }

        function channelTree() {
            var params = { "vhost" : selectedVHost, "order" : "shortname ASC" };
            jsonRequest('channels.getChannelTree', params,
                function(result)     { getChannelTreeResult(result); },
                function(exception)  { getException(exception); }
            );	
        }

        channelTree();

        function getFilesResult(result,b) {
            // if we have media in this channel, display them
            if (result.data.length > 0) {
                // set the output
                var out = "";
                var dur = "";
                // loop for all the media items returned
                for(i=0;i<result.data.length;i++) {
                    // set vars
                    var r = result.data[i];			
                    var showHideIcon = "";
                    // if the media item is in the playlist, hide the "add to playlist" button
                    if (window.playlist.join().indexOf(r.id)>=0) {
                        showHideIcon = ' hide"';
                    } else {
                        showHideIcon = "";
                    }
                    // if the duration is 0.00, such as an image or text, do nothing, otherwise, format it using lengthToTime();					
                    if (r.duration == "0.00") {
                        dur = "";
                    } else {
                        dur = lengthToTime(r.length);
                    }
                    //
                    var nowplaying = "";		
                    if (r.id == window.nowPlaying) {
                        nowplaying = '<span id="nowplayingGallery">'+window.nowPlayingMessage+' </span>';
                    }
                    //
                    // set the output				
                    out += '<div class="media clearfix" id="gallery-'+r.id+'">'+
                        '<a href="#' + fmBroadband.videoHashPrefix + r.id+'" class="left"><img src="'+r.publicUrl+'/13" alt="thumbnail" class="thumbimg"/><div class="thumbcorner"></div></a>'+
                        '<div class="info clearfix">'+
                        '<a href="#' + fmBroadband.videoHashPrefix + r.id+'" class="title">'+nowplaying+r.title+'</a>'+
                        '<span class="category">'+b+'</span>'+
                        '<span class="duration">'+dur+'</span>'+
                        '</div>'+
                        '<div class="action'+showHideIcon+'">'+
                        '<span class="icon"></span>'+
                        '</div>'+
                        '</div>';
						
                }
                // after all the media has been processed, output the result	
                $('scrollbar_content').innerHTML = out;
                // add the onclick function for the "add to playlist" button
                setGallery();
                // add the onclick function for to load the video into the player
                getGalleryVideos();
                // if there is no media directly in this channel, say so
            } else {
                $('scrollbar_content').innerHTML = window.noMediaMessage;  
            }
            recalcClips();
	
        }

        function getChannelMedia(channelid,channelname,elementid,sortby) {
            // set the vars
            if (!channelname || channelname === "") {
                channelname = " ";
            }
            if (!sortby || sortby === "") {
                sortby = "upload DESC";
            }
            // remove the selected highlight from the last column
            $$('#scrollbar_episodes li.selected').each(function(s) {
                    $(s).removeClassName("selected");
                });	
            // add the selected highlight to the correct list item in the last column
            if ($("c_"+elementid)) {
                $("c_"+elementid).up(0).addClassName("selected");
            }
            // set the json parameters
            var params = {
                "vhost" :       selectedVHost,
                "filters" :     {"channel" : channelid, "includeChildren": 1, "moderationStatus": 1, "filetype": "2" },
                "start" :       0,
                "limit" :       100,
                "fields" :      ["id","title","publicUrl","thumbUrl","duration","length","channel"],
                "sort" :        sortby
            };
            // place the loading animation
            $('scrollbar_content').innerHTML = '<div class="loading"><img src="'+window.loadingPath+'" id="loading" alt="Loading..." /></div>';
            // get the media
            jsonRequest('media.getFiles', params,
                function(result)     { getFilesResult(result,channelname); },
                function(exception)  { getFilesException(exception); },
                true
            );
        }

        function getMost() {
            b = " ";
            // set the json parameters
            var params = {
                "vhost" :       selectedVHost,
                "filters" :     {"includeChildren": 1, "moderationStatus": 1, "filetype": "2" },
                "sort"  :       "upload DESC",
                "start" :       0,
                "limit" :       25,
                "fields" :      ["id","title","publicUrl","thumbUrl","duration","length"]
            };
            // place the loading animation
            $('scrollbar_content').innerHTML = '<div class="loading"><img src="'+window.loadingPath+'" id="loading" alt="Loading..." /></div>';
            // get the media
            jsonRequest('media.getFiles', params,
                function(result)     { getFilesResult(result,b); },
                function(exception)  { getFilesException(exception); },
                true
            );
        }


        function getSubChannel(a) {
            // set the vars
            var c = window.channels.result[a].children;
            var out = "";
            // clear the selected highlight from the list
            $$('#scrollbar_categories li.selected').each(function(s) {
                    $(s).removeClassName("selected");
                });	
            // add the selected highlight to the currently selected channel list item
            $("a_"+a).up(0).addClassName("selected");
            // clear the seasons and episodes columns if they exist
            if ($('scrollbar_seasons') && $('scrollbar_episodes')) {
                $('scrollbar_episodes').innerHTML = "";
                $('scrollbar_content').innerHTML = "";
                recalcE();
                recalcClips();
            }
            //
            if ($('scrollbar_seasons') && $('scrollbar_episodes')) {
                $('scrollbar_seasons').hide();
                $('scrollbar_episodes').hide();
                $('scrollbar_container').setStyle({width: '80%'});
                recalcE();
                recalcClips();
            }
            // if there are no sub channels or there are no seasons and episodes colmuns, load the thumbsnails
            if (!c || c == "" || !$('scrollbar_seasons') && !$('scrollbar_episodes')) {
                getChannelMedia(window.channels.result[a].id,window.channels.result[a].name,null,window.channels.result[a].description);
                // if there are sub channels, load the next column's list
            } else {
                if ($('scrollbar_seasons')) {
                    $('scrollbar_seasons').show();
                }
                // start the output
                out = "<ul>";
                // add the list items to the output
                for (i=0;i<c.length;i++) {
                    if (c[i].visibility === "SHOWN") {
                        // send getLastChanne;(); the position of this subchannel and it's parent's position in the json
                        out += '<li><a id="b_'+i+'" title="'+a+'">'+c[i].name+'</a></li>';
                    }						
                }
                // end the output
                out += "</ul>";
		
                getChannelMedia(window.channels.result[a].id,window.channels.result[a].name,null,window.channels.result[a].description);
			
                if ($('scrollbar_episodes')) {
                    $('scrollbar_episodes').hide();
                    $('scrollbar_container').setStyle({width: '60%'});
                }
			
            }
	
            // if the seasons column exists, print the output
            if ($('scrollbar_seasons')) {
                $('scrollbar_seasons').innerHTML = out;
                recalcS();
                //
                $$('#scrollbar_seasons a').each(function(s) {
                        $(s).observe('click',function(event){
                                var i = $(s).id.substr($(s).id.lastIndexOf("_")+1);
                                getLastChannel($(s).title,i);
                            }); 
                    });	
            }
	
        }

        function getLastChannel(a,b) {
            // set the vars
            var c = window.channels.result[a].children[b].children;
            var out = "";
            // clear the selected highlight from the list
            $$('#scrollbar_seasons li.selected').each(function(s) {
                    $(s).removeClassName("selected");
                });	

            if ($('scrollbar_episodes')) {
                $('scrollbar_episodes').hide();
                $('scrollbar_container').setStyle({width: '60%'});
            }

            // add the selected highlight to the currently selected channel list item
            $("b_"+b).up(0).addClassName("selected");
            // clear the media content column
            $('scrollbar_content').innerHTML = "";
            // if there are no subchannels, display the media
            //console.log(window.channels.result[a].children[b].id);
            //
            if (!c || c == "") {
                getChannelMedia(window.channels.result[a].children[b].id,window.channels.result[a].children[b].name,null,window.channels.result[a].children[b].description);
                // if there are subchannels, display final list
            } else {
									
                if ($('scrollbar_episodes')) {
                    $('scrollbar_episodes').show();
                    $('scrollbar_container').setStyle({width: '40%'});
                }
		
                // start the output
                out = "<ul>";
                for (i=0;i<c.length;i++) {
                    if (c[i].visibility === "SHOWN") {
                        // send the function to display the media this channel id, the channel name and the list item id number
                        out += '<li><a title="'+c[i].id+' | '+c[i].name+' | '+c[i].description+'" id="c_'+i+'">'+c[i].name+'</a></li>';
                    }				
                }
                // close the list
                out += "</ul>";
		
                getChannelMedia(window.channels.result[a].children[b].id,window.channels.result[a].children[b].name,null,window.channels.result[a].children[b].description);
		
            }
            // output it all
            $('scrollbar_episodes').innerHTML = out;
            // set the onclick
            $$('#scrollbar_episodes a').each(function(s) {
                    $(s).observe('click',function(event){
                            var i = $(s).id.substr($(s).id.lastIndexOf("_")+1);
                            var id = $(s).title.substr(0,$(s).title.indexOf(" | "));
                            var name = $(s).title.substr($(s).title.indexOf(" | ")+3);
                            var sort = $(s).title.substr($(s).title.lastIndexOf(" | ")+3);
			
                            getChannelMedia(id,name,i,sort);
                        }); 
                });
        }

        // set the default gallery to only show the categories and media columns
        $('scrollbar_seasons').hide();
        $('scrollbar_episodes').hide();
        $('scrollbar_container').setStyle({width: '80%'});
    }
);

/* validating send to a friend */

AppInit.addEvent (
	function() {
		// grab the default colour for all the labels
	    $$( 'label' ).each ( function ( label ) {
                label.defaultColor = label.getStyle ( 'color' );
            });
	}
);

// handles validation on the 'Email to a friend' form
function handleValidation(element,message) {
	// get all the labels		
	var labels = element.form.getElementsByTagName('label');
	// find out which label is the one with incorrect field value	
	for(var i=0;i<labels.length;i++) {
		// if this is the correct label, make it red and grab its contents
		if (labels[i].htmlFor==element.id) {
			labels[i].style.color = '#cc0000';
			var lab = labels[i].innerHTML;
            // if this is not the label, make sure its the correct colour
            // if someone had a validation error, fixes it, then has another, this will revert the label to the correct colour
		} else if (labels[i].defaultColor) {
			labels[i].style.color = labels[i].defaultColor;
            // if this is not the label and a default colour wasn't found, use black.
		} else {
			labels[i].style.color = '#000';
		}
	}
	// set the message to have the label value in quotes before the error
	message = "'"+lab+"'"+message.substr(message.indexOf(" "));
	// output the error
	$$('div.validationmessage')[1].innerHTML = message;
}
// clear the label colour
function clearError(e) {
	// if you want to have the labels return to normal after the user selects form element that has a validation error on it
	// add onfocus="clearError(this)" or onchange="clearError(this)" to each of these elements.
	// this only works when the formtype is set to default or table
	//
	// find the label
	var d = e.up(0).previous(0).down(0);
	// is the label red?
	if (d.style.color == "#cc0000" || d.style.color == "rgb(204, 0, 0)") {
		// yeah it is? ok, make it black
		d.style.color = "#000";
	}
}
// ajaxing the send to a friend form
function ajaxform(x,y) {
	x = $(x).up(y);
	// set the vars
	var vars  = Form.serializeElements($(x).getElements());
	// send the from using ajax
	var url = '/action/tellafriend';
	//
	new Ajax.Request(url, {
            method: 'post',
                postBody: vars,
                onSuccess: function(transport) {
                // hide the form and show the message that the email was sent
                x.hide();
                x.next(0).show();
            }
	});
}

