// JScript source code
// Declared globally to look up the list of available sites.
    var globalMemberSites;
    // Declared globally to keep track of what page we are on.
    var globalOnPage = 0;
    var galleryHTML= "";
    // get the logged in user
    var globalUserKeyString;
	
	getLoggedInUser();
    
	// Create list of galleries
    function getLoggedInUser() {
        // passing in null tells the DAAPI to give us the currently logged in user, if any
        var blankUserKey = new UserKey(null);
        talkToServer(blankUserKey);
    }
	
    function clean(s) {
      return s.replace(/"/g, ''); 
    }
	
	// Set up divs which will later be filled with HTML;
    function createDivs () {
        var html = "";
        html += "";
       //html += "<div id='galleryRecommend'><div>";
	  // html += "<div class='sectionHead'>Video - </div>";
        html += "<div class='player'>";
        html += "<!--div id='playingTitle' class='subTitle'>loading...</div--><br style='clear:both' />";
        html += "<div id='videoPlayerBox'></div>";
        html += "</div>";
		html += "<div id='videoDetails'>loading...</div>";
        //html += "<!--Comments--><div class='sectionHead'>Comments</div>"; 
        //html += "<div id='videoCommentsBox'>document.getElementByIdCommentsLoop</div><br style='clear:both;' /><div class='sectionHead'>Add A Comment</div><div id='addCommentsBox'></div><!--end dynamic statement-->"; 
        
		// use the document.getElementById shortcut from prototype.js
		document.getElementById('dynamicInjection').innerHTML = html;
		
		html="";
		html += "<div class='siteRightSection'><div class='sectionHead' id='selectedGalleryTitle'></div>";
		html += "<div id='galleryDetails' style='display: none;'></div></div>"; 
		html += "<div class='siteRightSection'><div class='videoThumbs'><div class='filmThumbs' id='videoListBox'></div></div><br style='clear:both;' /></div>";
        html += "<div class='siteRightSection' style='display: none;'><div id='uploadToGallery' style='display: none;'></div><br style='clear:both;' /></div><div class='siteRightSection'><div class='videoThumbs' style='overflow:hidden;'><br /><div id='publicGallerySideBox'></div></div><br style='clear:both;' /></div>";
		/* html += "<br style='clear:both;' /></div><div class='siteRightSection'><div class='videoThumbs' style='overflow:hidden;'><br /><div id='publicGallerySideBox'></div></div><br style='clear:both;' /></div>"; */
		html += "<!--Comments--><!--<div class='sectionHead'>Add A Comment</div><div id='addCommentsBox'></div><div class='sectionHead'>Comments</div>-->";
        //html += "<div id='videoCommentsBox'>document.getElementByIdCommentsLoop</div><br style='clear:both;' /><!--end dynamic statement-->";
		html += "<div id='videoCommentsBox'></div><br style='clear:both;' /><!--end dynamic statement-->";
		document.getElementById('dynamicInjection2').innerHTML = html;
        //reset globalOnPage
        globalOnPage = 1;
    }

    // If set to 0 will conflict with DAAPI calls to pork.js.
    var uploadFormCounter = 10000;

    // Hides a given object by id.
    function hideObject(objectID) {
        document.getElementById(objectID).style.display = "none";
    }
    // Shows a given object by id.
    function showObject(objectID) {
        document.getElementById(objectID).style.display = "block";
    }
    // Empties a given object by id.
    function emptyObject(objectID) {
        document.getElementById(objectID).innerHTML = html;
    }

    
    // Displays a list of public galleries based on a publicGalleryPage object.
	// Called at load time.
	function displayPublicGalleryPage(publicGalleryPage) {
			var html = "";
			for (var i = 0; i < publicGalleryPage.Galleries.length; i++) {
				var gallery = publicGalleryPage.Galleries[i];
				
				html += "<div class='galWrap'><div class='galThumb'><a href='/videos/gallery/?plckGalleryID=" + gallery.GalleryKey.Key + "'><img src='" + gallery.GalleryPromo.Image.RecentSlide + "' /></a></div>";
				html += "<div class='galDetails'><div class='galTitle'>";
				html += "<a href='/videos/gallery/?plckGalleryID=" + gallery.GalleryKey.Key + "'>";
				html += gallery.Title;
				html += "</a></div>";
				html += "<div class='galDesc'>"+ gallery.Description +"</div>";
				//html += "<div class='galRec'><b>Tags:</b> "+ gallery.Tags +"</div>";
				//html += "<div class='galTags'><b>Recommendations</b> "+ gallery.NumberOfRecommendations +"</div>"; 
				html += "</div></div>";
							
			}
			// use the document.getElementById shortcut from prototype.js
			document.getElementById('publicGalleryPageBox').innerHTML = html;
			galleryHTML = html;
		}

    // Displays a gallery based on a given gallery object.
    // Called in response to GalleryKey sent to server.
    function displayGallery(gallery) {
        document.getElementById('publicGallerySideBox').innerHTML = galleryHTML;
        
        var html = "";
        //Newcode
        
        //display gallery title
		var html = gallery.Title;
		document.getElementById('playingTitle').innerHTML = html;
		html = "";
        //html += "More "+gallery.Title ;
		html += "View More Video";
        html += '<input type="hidden" id="galleryType" value="' + gallery.GalleryType.Name + '" class="formInput" />';
        html += '<input type="hidden" id="mediaType" value="' + gallery.MediaType.Name + '" class="formInput" />';
        // use the document.getElementById shortcut from prototype.js
        document.getElementById('selectedGalleryTitle').innerHTML = html;
        html="";
        html += "<div class='galleryDesc'><span id='galleryNumberOfVideos'></span>  &nbsp;" + gallery.Description + "</div>";
        // use the document.getElementById shortcut from prototype.js
        document.getElementById('galleryDetails').innerHTML = html;
        /*
	   	html="";
        html += "<a href='#uploadspot' onclick=\"showDiv(event, 'uploadContent',440);\" class='littleButton'><img src='/img/video/addVideos.jpg' /></a>";
        html += "</p><div id='submitVideo' style='display:none'></div>";
        document.getElementById('uploadToGallery').innerHTML = html; */
        
        // Hidden upload box
        /*
		html = "";
        html += "<p><strong>Submit a video to this gallery</strong></p>";
        html += "<div id='videoUpload'></div>";
        html += "<p><input type='button' value='Clear file queue' onclick='displaySWFUploader(\"" + gallery.GalleryKey.Key + "\", globalUserKeyString)' />";
        html += "<input type='button' value='Done!' onclick='hideObject(\"submitVideo\");getVideoList(\"" + gallery.GalleryKey.Key + "\", globalOnPage);displaySWFUploader(\"" + gallery.GalleryKey.Key + "\", globalUserKeyString)' /></p>";*/
        
        // use the document.getElementById shortcut from prototype.js
        //document.getElementById('submitVideo').innerHTML = html;
        
        // now that everything is displayed, put in our uploader
        //displaySWFUploader(gallery.GalleryKey.Key, globalUserKeyString);

        getVideoList(gallery.GalleryKey.Key, globalOnPage);
    }
    
    // Create SWF uploader initialization variable.
    var swfu;

    // Display the SWF uploader.
	/*
    function displaySWFUploader(galleryKeyString, userKeyString) {

        // List of supported file extensions for use in OS file system dialog.
        var fileTypes = "*.mpg;*.mpeg;*.mp4;*.mpg4;*.mpeg4;*.vob;*.3gp;*.avi;*.asf;*.wmv;*.mov;*.flv";

        // Create SWFUpload object.
        swfu = new SWFUpload({
            // basic settings
            upload_target_url: videoUploadUrl,
            post_params: { "galleryKey": galleryKeyString, "userKey": userKeyString },
            
            // file upload settings
            file_size_limit: "102400", // 100 MB
            file_types: fileTypes,
            file_types_description: "All Video Files",
            file_upload_limit: "0",
            begin_upload_on_queue: false,
            use_server_data_event: true,
            validate_files: false,
            
            // event handler settings
            file_queued_handler : fileQueued,
            file_progress_handler : fileProgress,
            file_cancelled_handler : fileCancelled,
            file_complete_handler : fileComplete,
            queue_complete_handler : queueComplete,
            //queue_stopped_handler : queueStopped,
            //dialog_cancelled_handler : fileDialogCancelled,
            error_handler : uploadError,

            // flash Settings
            flash_url : "/swf/swfupload.swf",

            // UI Settings
            ui_container_id : "swfUploaderUI",
            degraded_container_id : "SWFUploadDegradeTarget",

            // Debug Settings
            debug: false
	        });
	        
	    swfu.addSetting("upload_target", "divFileProgressContainer");

        // Initialize html string var.
        var html = "";
        
        // create the upload form
        html += "<div id='SWFUploadTarget' style='width:383px;display:block'>";
        html += "<form>";
        html += "<button id='btnBrowse' type='button' onclick='swfu.browse(); this.blur();'>Browse Videos</button>";
        html += "<button id='btnUpload' type='button' onclick='swfu.startUpload(); this.blur();'>Start Upload</button>";
        html += "<ul id='listOfFiles' style='padding-top:5px;'></ul>";
        html += "<div id='swfUploaderUI' style='padding:0px;'></div>";
        html += "</form>";
       
        // create the progress container
        html += "<div id='divFileProgressContainer' style='padding:5px; clear:both;'></div>";
     
        // create the degrade container
        html += "<div id='SWFUploadDegradeTarget'>Attempting to load Flash version 9 uploader...</div>";
        html += "<div id='approvalMessage' style='display:none;'></div>";
        html += "</div>";
        // write to video upload div.
        document.getElementById('videoUpload').innerHTML = html;
    }
	*/
	
	// given a string, chop it off after a certain length
    // and add a "..." to the end.
    function displayTitlePretty(titleString) {
        return titleString.substring(0, 15) + "...";
    }
    // Display a list of videos based on a VideoPage object.
    // Called in response to VideoPage sent to server.
    function displayVideoList(videoPage) {
        //console.dir(videoPage);
		globalOnPage = videoPage.OnPage;
		var firstPage = 1;
        var nextPage = Number(videoPage.OnPage) + 1;
        var prevPage = Number(videoPage.OnPage) - 1;
        var lastPage = Math.ceil(videoPage.NumberOfVideos/videoPage.NumberPerPage);

        // Set the number of videos in the gallery
        document.getElementById('galleryNumberOfVideos').innerHTML = " ("+videoPage.NumberOfVideos + " videos)" ;

        // Populate video list
        html = "";

        //html += "<div style='float:left'>";
        
        // iterate through, displaying each video
        for (var i = 0; i < videoPage.Videos.length; i++) {
			
            var video = videoPage.Videos[i];
			//console.dir(video.VideoState.State);
			
            html += "<div class='thumbWrap'>";
            html += "<div class='thumb'>";
            if (video.Author.IsBlocked == 'True' && video.Author.UserKey.Key != globalUserKeyString) {
                html += "<img src='/img/blocked.jpg' />";
                html += "</div>";
                html += "<div class='moretitle'><a href='#' onclick='javascript:alert(\"The user that submitted this content has been blocked.\")'>Blocked</a></div>";
            }
            else {
                switch (video.VideoState.State) {
                case 'Processing':
                    html += "<img src='/img/pending.jpg' /></div>";
                    html += "<div class='moreTitle'>" + displayTitlePretty(video.Title) + "<br />";
                    html += video.VideoState.State + "</div>";
                    break;
                case 'Error':
                    html += "<img src='/img/error.jpg' /></div>";
                    html += "<div class='moreTitle'>" + displayTitlePretty(video.Title) + "<br />";
                    html += video.VideoState.State + "</div>";
                    break;
                case 'Completed':
                    html += "<a href='#' title='" + video.Title + "' onclick='getVideo(\"" + video.VideoKey.Key + "\")'>";
                    html += "<img src='" + video.VideoThumbnail + "'></a></div>";
                    html += "<div class='moreTitle'><a href='#' title='" + video.Title + "' onclick='getVideo(\"" + video.VideoKey.Key + "\")'>" + video.Title + "</a><br /></div>";
                    break;
                default:
                    html += "<a href='#' title='" + video.Title + "' onclick='getVideo(\"" + video.VideoKey.Key + "\")'>";
                    html += "<img src='/img/loading.jpg' /></a></div>";
                    html += "<div class='moreTitle'><a href='#' title='" + video.Title + "' onclick='getVideo(\"" + video.VideoKey.Key + "\")'>" + video.Title + "</a><br /></div>";
                }
                
               
                
            }
            html += "</div>";//end thumbwrap
			
			if (((i + 1) % 5) == 0){
				html+="<br clear='all' />";	
			}
        }
        html += "<div style='clear:both'></div>";
        
        html += "<p style='text-align:right'>";
        if (prevPage >= firstPage) {
            html += "<a href='#' title='Go to page " + prevPage + "' onclick='getVideoList(\"" + videoPage.GalleryKey.Key + "\", " + prevPage +")' style='float:left'><img src='/img/video/back.jpg' /></a>";
        }
        if (nextPage <= lastPage) {
            html += "<a href='#' title='Go to page " + nextPage + "' onclick='getVideoList(\"" + videoPage.GalleryKey.Key + "\", " + nextPage +")'><img src='/img/video/more.jpg' /></a>";
        }
        html += "</p>";

        html += "</div>";

        html += "<div style='clear:both'></div>";

        // use the document.getElementById shortcut from prototype.js
        document.getElementById('videoListBox').innerHTML = html;

        if (document.getElementById('videoPlayerBox').innerHTML == "" && videoPage.Videos.length > 0) {
            getVideo(videoPage.Videos[0].VideoKey.Key);
        }
    }
    
    // Display a video player based on a Video object.
    
	
	// Called in response to the server sending back a video object.
    function displayVideoPlayer(video) {
        html = "";
        if (video.VideoState.State == 'Completed') {
            if (video.Author.IsBlocked == 'True' && video.Author.UserKey.Key != globalUserKeyString) {
                // use the $ shortcut from prototype.js
                document.getElementById('videoPlayerBox').innerHTML = "<div class='videoMissing'><div>User blocked.</div></div>"
            } else {
                var so = new SWFObject("http://samples.pluck.com/ver1.0/content/swf/mediaplayer.swf", "video", "460", "272", "9", "#000000");
                so.useExpressInstall('/content/swf/expressinstall.swf');
                so.addVariable('file', video.VideoUrl);
                so.addVariable('autostart', 'true');
                so.addVariable('width', '460');
                so.addVariable('height', '272');
                so.addVariable('allowfullscreen', 'true');
                so.addVariable('allowscriptaccess', 'always');
                so.write('videoPlayerBox');
            }
        } else {
            // use the $ shortcut from prototype.js
            document.getElementById('videoPlayerBox').innerHTML = "<div class='videoMissing'><div>Video not available.</div></div>"
        }
    }
    
    // Display a single video based on a given Video object.
    // Called in response to the server sending back a video object.
    function displayVideo(video) {
		//console.dir(video);
       	//var html = video.Title;
        //var html = gallery.Title;
		//document.getElementById('playingTitle').innerHTML = html;
        var html= "";
        // Populate video info

        // Video Title
        // Number of Recommendations
        //html += "<div style='float:left; width:300px; padding-top:10px; line-height:18px;'>"
        // Video Description
        // Video author
        //html += "<b>Author</b> - " + video.Author.DisplayName + "";
        //html += "<p><b>Description</b> - " + video.Description + "</p>";
        // Video Tags
        //html += "<p><b>Tags</b> - " + video.Tags + "</p> ";
        

        // Video site of origin
        /*
		if (globalMemberSites != null) {
            for (var i=0; i<globalMemberSites.length; i++) { //>
                if (globalMemberSites[i].MemberSiteKey.Key == video.SiteOfOrigin) {
                    html += "<p><strong>Site of origin</strong>: " + globalMemberSites[i].MemberSiteName + "</p>";
                }
            }
        }
		*/
        //html +="</div>";
		html+="<div style='padding-top:10px; text-align:center;'>"
        html += "<div class='recommendation' style='padding-right:20px;'>";
        if (video.CurrentUserHasRecommended == 'True') {
            html += "<span class='videoRecommended'>" + video.NumberOfRecommendations + " recommendations</span>";
        } else {
        html += "<a href='#' id='videoRecommendLink' class='SiteLife_Recommend' onclick='recommendVideo(\"" + video.VideoKey.Key + "\");' />Recommend</a>";
        }
        html += " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        
        // Report Abuse
        //html += "<div class='reportAbuse' style='padding-top:10px; padding-left:20px;'>";
        if (video.CurrentUserHasReportedAbuse == 'True') {
            html += "<span>" + "Reported abuse</span>";
        } else {
        html += "<a href='#' onclick=\"showDiv(event, \'videoReportAbuseBox\', 180);\" />Report Abuse</a>";
        }
        html += "</div>";
        // Report abuse
        html += "<div id='videoReportAbuseBox' ><div style='text-align:right; padding-right:5px;'> <a href='#none' style='color:#ffffff;' onclick=\"hideObject('videoReportAbuseBox');\"><strong>X</strong></a></div>";
        html += "<p><strong>Type of Abuse</strong><br />";
        html += "<select id='abuseReportReason'>";
        html += "<option value='Obscenity/vulgarity' selected='selected'>Obscenity/vulgarity</option>";
        html += "<option value='Hate speech'>Hate speech</option>";
        html += "<option value='Personal attack'>Personal attack</option>";
        html += "<option value='Advertising/spam'>Advertising/spam</option>";
        html += "<option value='Copyright/plagiarism'>Copyright/plagiarism</option>";
        html += "<option value='Other'>Other</option>";
        html += "</select>";
        html += "</p>"
        html += "<p><strong>Comment (optional)</strong>";
        html += "<textarea rows='4' id='abuseReportDesc' style='width:90%'></textarea>";
        html += "</p>"
        html += "<p style='text-align:right; padding-right:10px;'><input type='button' value='Submit Report' ";
        html += "onclick='hideObject(\"videoReportAbuseBox\");";
        html += "reportAbuseVideo(\"" + video.VideoKey.Key + "\");";
        html += "alert(\"Thank you. Your report has been submitted.\");";
        html += "' /></p>";
        html += "</div>";

        html += "</div><br style='clear:both;' />";
        // use the document.getElementById shortcut from prototype.js
		//html="";//fix this to see details
        document.getElementById('videoDetails').innerHTML = html;
		/*
		html="<div><b>Author Information:</b> "; 
		html+="<div class='authThumb'><a href='/personas/index.htm?newspaperUserId="+video.Author.UserKey.Key+"'><img src='"+video.Author.AvatarPhotoUrl+"' /></a></div>";
		html+="<div class='authDetail' ><b><a href='/personas/index.htm?newspaperUserId="+video.Author.UserKey.Key+"'>"+video.Author.DisplayName+"</a></b>";
		html+="<div><b>Friends: </b>"+video.Author.NumberOfFriends+"</div><div><b>Last Update: </b>"+video.Author.LastUpdated+"</div></div></div>";
		*/
		html = "";
		html+="<div class='vidDetailTitle'><b>Title:</b> "+video.Title+"</div>";
		html+="<div><b>Description:</b> "+video.Description+"</div>";
		/*
		html+="<div><b>Tags:</b> "+video.Tags+"</div>";
		html+="<div><b>Recommendations:</b> "+video.NumberOfRecommendations+"</div>";
		if (video.VideoState.State == 'Completed') {
            if (video.Author.IsBlocked == 'True' && video.Author.UserKey.Key != globalUserKeyString) {
                html += "<div class='videoMissing'><div>User blocked.</div></div>"
            } else {
				html+="<div><b>Player Code:</b><br /><textarea id='embedCode'>";
                html+="<object type=\"application/x-shockwave-flash\" allowscriptaccess=\"never\" allownetworking=\"internal\" data=\"http://samples.pluck.com/ver1.0/content/swf/mediaplayer.swf\" height=\"375\" width=\"500\">";
				html+="<param name=\"flashvars\" value=\"&file="+ video.VideoUrl +"&width=500&amp;height=375&amp;autostart=true\">";
				html += "<embed src='http://samples.pluck.com/ver1.0/content/swf/mediaplayer.swf'";
                html += "width='500' height='375'";
                html += "allowfullscreen='false'";
                html += "allowscriptaccess='never'";
                html += "flashvars='&file=" + video.VideoUrl + "&width=500&height=375&autostart=true' /></object>";
               html += "</textarea></div>";
				}
        } else {
            html += "<div class='videoMissing'><div>Video not available.</div></div>"
        } */
		
		
		document.getElementById('authInfo').innerHTML=html;
    }
    
    // Displays a list of video comments based on a comment page response.
    // Called in response to CommentPage sent to server.

    function displayVideoComments(commentPage) {
    
        // Populate comment list
        var html = "";
        
		html += "<div class='vidCommentInputWrap'><textarea rows='2' id='videoComment'></textarea><br /><br />";
        html += "<input type='button' value='Add Comment' onclick='addCommentToVideo(\"" + commentPage.ArticleKey.Key + "\")' /></div><br />";
		
		html = "";
		document.getElementById('addCommentsBox').innerHTML = html;
		html="";
        // iterate through, displaying each comment
        for (var i = 0; i < commentPage.Comments.length; i++) {
            var comment = commentPage.Comments[i];
            html += "<div class='videoCommentWrap'>";
            html += "<div class='videoCommentThumb'>";
            html += "<img src='" + comment.Author.AvatarPhotoUrl + "' alt= " + comment.Author.DisplayName + " /></div>"
            html += "<div style='float:left; width;366px; padding:5px 0px 5px 10px;'><b>" + comment.Author.DisplayName + "</b> wrote:<br /><span style='color:#999999;font-size:9px;'>"+ comment.PostedAtTime +"</span>";
            html += "<div style='padding-top:5px;'>" + comment.CommentBody + "</div></div>";
            html += "<br style='clear:both;' /></div>";
			
			// Reports abuse functionality
			
			html+="<div style='padding-top:10px; text-align:center;'>"
			html += "<div class='recommendation' style='width: 450px;'>"; 
			if (comment.CurrentUserHasRecommended == 'True') {
				html += "<span class='commentRecommended'>" + comment.NumberOfRecommendations + " recommendations</span>";
			} else {
			html += "<a href='#' id='commentRecommendLink' style='display: inline; float: left; margin-right: 20px; margin-left: 5px; padding-left: 20px;' class='SiteLife_Recommend' onclick='recommendComment(\"" + comment.CommentKey.Key + "\");' />Recommend</a>";
			}
			html += " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
			
			// Report Abuse
			html += "<div class='reportAbuse' style='display: inline; float: left;'>";
			if (comment.CurrentUserHasReportedAbuse == 'True') {
				html += "<span>" + "Reported abuse</span>";
			} else {
			html += "<a href='#' onclick=\"showDiv(event, \'commentReportAbuseBox\', 180);\" />Report Abuse</a>";
			}
			html += "</div>";
			
			// Comments report abuse
			html += "<div id='commentReportAbuseBox' style='display: none;'><div style='text-align:right; padding-right:5px;'> <a href='#none' style='color:#ffffff;' onclick=\"hideObject('commentReportAbuseBox');\"><strong>X</strong></a></div>";
			html += "<p><strong>Type of Abuse</strong><br />";
			html += "<select id='abuseCommentReportReason'>";
			html += "<option value='Obscenity/vulgarity' selected='selected'>Obscenity/vulgarity</option>";
			html += "<option value='Hate speech'>Hate speech</option>";
			html += "<option value='Personal attack'>Personal attack</option>";
			html += "<option value='Advertising/spam'>Advertising/spam</option>";
			html += "<option value='Copyright/plagiarism'>Copyright/plagiarism</option>";
			html += "<option value='Other'>Other</option>";
			html += "</select>";
			html += "</p>"
			html += "<p><strong>Comment (optional)</strong>";
			html += "<textarea rows='4' id='abuseCommentReportDesc' style='width:90%'></textarea>";
			html += "</p>"
			html += "<p style='text-align:right; padding-right:10px;'><input type='button' value='Submit Report' ";
			html += "onclick='hideObject(\"videoReportAbuseBox\");";
			html += "reportAbuseComment(\"" + comment.CommentKey.Key + "\");"; 
			html += "alert(\"Thank you. Your report has been submitted.\");";
			html += "' /></p>";
			html += "</div>";
	
			html += "</div></div><br style='clear:both;' />";
			// use the document.getElementById shortcut from prototype.js
			//html="";//fix this to see details
			}
			
		html = "";
        // use the document.getElementById shortcut from prototype.js

		html = '<script type="text/javascript" language="javascript"> var articleId = "' + galleryKey + '"; gSiteLife.Comments ("ExternalResource", articleId, 20, "TimeStampDescending"); </script>';
		document.getElementById('videoCommentsBox').innerHTML = html;
    }

    // Requests a new gallery based on the null passed in for the gallery key.
    // Coded to create a public video gallery.
    // Gallery will belong to logged in user.
    function createGallery() {
        var createGallery = new UpdateGalleryAction(
            null,       // null gallery key
            new GalleryType("Public"), 
            new MediaType("Video"), 
            "Untitled Gallery", 
            "", 
            "", 
            new Section("undefined"), 
            null);
        talkToServer(createGallery);
    }
    
    // Requests an update to a Video object based on a gallery key string.
    function updateGallery(galleryKeyString) {
        var galleryKey = new GalleryKey(galleryKeyString);
        // retrieve the values from the inputs
        var title = clean(document.getElementById('galleryTitle').value);
        var desc = clean(document.getElementById('galleryDesc').value);
        var tags = clean(document.getElementById('galleryTags').value);
        var galleryType = clean(document.getElementById('galleryType').value);
        var mediaType = clean(document.getElementById('mediaType').value);
        var section = clean(document.getElementById('gallerySection').value);
        var update = new UpdateGalleryAction(
            galleryKey, 
            new GalleryType(galleryType),
            new MediaType(mediaType),
            title, 
            desc, 
            tags, 
            new Section(section));
        talkToServer(update);
        talkToServer(galleryKey);
    }
    
    // Requests an update to a Video object based on a video key string.
    function updateVideo(videoKeyString) {
        var videoKey = new VideoKey(videoKeyString);
        // retrieve the values from the inputs
        var title = document.getElementById('videoTitle').value;
        var desc = document.getElementById('videoDesc').value;
        var tags = document.getElementById('videoTags').value;
        var update = new UpdateVideoAction(
            videoKey, 
            title, 
            desc, 
            tags);
        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(update);
        requestBatch.AddToRequest(videoKey);
        requestBatch.BeginRequest(serverUrl, updateVideoCallBack);
    }
    
    // Requests a PublicGalleryPage. Coded to video type for this example.
    function getPublicGalleryPage() {
        var mediaType = new MediaType("Video");
        var publicGalleryPage = new PublicGalleryPage(10, 1, mediaType);
        talkToServer(publicGalleryPage);
    }

    // Requests a GalleryKey based on a gallery key string.
    function getGallery(keyString) {
        var publicGallery = new GalleryKey(keyString);
		talkToServer(publicGallery);
		//uploadInitialize(keyString,'fs','videos section','samples',true);
	}

    // Recommends a gallery based on a gallery key string.
    function recommendGallery(keyString) {
        var galleryKey = new GalleryKey(keyString);
        var recommendAction = new RecommendAction(galleryKey);
        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(recommendAction);
        requestBatch.AddToRequest(galleryKey);
        requestBatch.BeginRequest(serverUrl, recommendGalleryCallBack);
    }
    
    // Recommends a video based on a video key string.
    function recommendVideo(keyString) {
        var videoKey = new VideoKey(keyString);
        var recommendAction = new RecommendAction(videoKey);
        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(recommendAction);
        requestBatch.AddToRequest(videoKey);
        requestBatch.BeginRequest(serverUrl, recommendVideoCallBack);
    }
	
	// Recommends a video based on a video key string.
    function recommendComment(keyString) {
        var commentKey = new CommentKey(keyString);
        var recommendAction = new RecommendAction(commentKey);
        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(recommendAction);
        requestBatch.AddToRequest(commentKey);
        requestBatch.BeginRequest(serverUrl, recommendCommentCallBack);
    }
    
    // Reports abuse on a video based on a video key string.
    function reportAbuseVideo(keyString) {
        var videoKey = new VideoKey(keyString);
        var abuseReportReason = document.getElementById('abuseReportReason').value;
        var abuseReportDesc = document.getElementById('abuseReportDesc').value;
        var reportAbuseAction = new ReportAbuseAction(videoKey, abuseReportReason, abuseReportDesc);
        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(reportAbuseAction);
        requestBatch.AddToRequest(videoKey);
        requestBatch.BeginRequest(serverUrl, reportAbuseCallBack);
    }
	
	function reportAbuseComment(keyString) {
        var commentKey = new CommentKey(keyString);
        var abuseReportReason = document.getElementById('abuseCommentReportReason').value;
        var abuseReportDesc = document.getElementById('abuseCommentReportDesc').value;
        var reportAbuseAction = new ReportAbuseAction(commentKey, abuseReportReason, abuseReportDesc);
        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(reportAbuseAction);
        requestBatch.AddToRequest(commentKey);
        requestBatch.BeginRequest(serverUrl, reportAbuseCallBack);
    }
    
    // Adds a comment to a video based on a video key string.
    function addCommentToVideo(keyString) {
        var videoKey = new VideoKey(keyString);
        var videoComment = document.getElementById('videoComment').value;
        var commentAction = new CommentAction(videoKey, "Sample URL", "Title", videoComment);
        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(commentAction);
        requestBatch.AddToRequest(videoKey);
        requestBatch.BeginRequest(serverUrl, addCommentToVideoCallBack);
    }
    
    // Requests a CommentPage based on a video key string.
    function getVideoComments(keyString) {
        var videoKey = new VideoKey(keyString);
        var commentPage = new CommentPage(videoKey, 10, 1, "TimeStampDescending");
        talkToServer(commentPage);
    }
    
    // Requests a VideoPage based on a gallery key string and a page number.
    function getVideoList(keyString, onPage) {
		var sort = "TimeStampAscending"; 
		
        var galleryKey = new GalleryKey(keyString);
        var videoPage = new VideoPage(galleryKey, 9, onPage, sort);
		//VideoPage(galleryKey, numberPerPage, onPage, sort)
        talkToServer(videoPage);
    }
    
    // Requests a VideoKey based on a video key string.
    function getVideo(keyString) {
        var videoKey = new VideoKey(keyString);
        talkToServer(videoKey);
    }
            
    // Displays an error message based on the contents of responseBatch.
    // Called by many functions (specifically callbacks) if an error has occurred.
    function handleErrors(responseBatch) {
        var s = '';
        for (var i = 0; i < responseBatch.Messages.length; i++) {
            s = s + responseBatch.Messages[i].Message + '\n\n';
        }
        alert(s);
    }
    // Takes in a DAAPI request and submits it to the SiteLife server.
    // Called by many functions to put a request through to the SiteLife server.
    function talkToServer(request) {
        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(request);
        requestBatch.BeginRequest(serverUrl, customCallBack);
    }
    
    function recommendVideoCallBack(responseBatch) {
        if (responseBatch.Responses.length == 0) {
            if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
            handleErrors(responseBatch);
            return;
        }
        for (var i = 0; i < responseBatch.Responses.length; i++) {
            displayVideo(responseBatch.Responses[i].Video)
        }
    }
    
    function addCommentToVideoCallBack(responseBatch){
        if (responseBatch.Responses.length == 0) {
            if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
            handleErrors(responseBatch);
            return;
        }
        for (var i = 0; i < responseBatch.Responses.length; i++) {
            getVideoComments(responseBatch.Responses[i].Video.VideoKey.Key);                                                            
        }
    }
                                                            
    function reportAbuseCallBack(responseBatch){
        if (responseBatch.Responses.length == 0) {
            if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
            handleErrors(responseBatch);
            return;
        }
        for (var i = 0; i < responseBatch.Responses.length; i++) {
            displayVideo(responseBatch.Responses[i].Video);
        }
    }

    function recommendGalleryCallBack(responseBatch){
        if (responseBatch.Responses.length == 0) {
            if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
            handleErrors(responseBatch);
            return;
        }
        for (var i = 0; i < responseBatch.Responses.length; i++) {
            displayGallery(responseBatch.Responses[i].Gallery)
        }
    }
    
    function updateVideoCallBack(responseBatch){
        if (responseBatch.Responses.length == 0) {
            if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
            handleErrors(responseBatch);
            return;
        }
        for (var i = 0; i < responseBatch.Responses.length; i++) {
            displayVideo(responseBatch.Responses[i].Video)
        }
    }
                                                            
    // Provides requested objects from the SiteLife server.
    // Called by talkToServer() as a callback when making a request to the SiteLife server.
    function customCallBack(responseBatch) {
        if (responseBatch.Responses.length == 0) {
            if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
            handleErrors(responseBatch);
            return;
        }
        if (responseBatch.MemberSites != null) { // is this site portfolio enabled?
            if (responseBatch.MemberSites.length != 0) { // does the response include portfolio-related content?
                globalMemberSites = responseBatch.MemberSites;
            }
        }
        for (var i = 0; i < responseBatch.Responses.length; i++) {
            var response = responseBatch.Responses[i];
            dispatchResponse(response);
        }
    }  
                                                           
                                                            
    // Peforms an action based on what kind of response came back from the SiteLife server.
    // Called by customCallBack() once a request to the SiteLife server has completed.
    function dispatchResponse(response) {
        if (response.User != null) {
            globalUserKeyString = response.User.UserKey.Key;
           // document.getElementById('userBox').innerHTML = "<p>You are logged in as <b>" + response.User.DisplayName + "</b>.</p>";
        } else if (response.PublicGalleryPage != null) {
            displayPublicGalleryPage(response.PublicGalleryPage);
        } else if (response.Gallery != null) {
            displayGallery(response.Gallery);
        } else if (response.VideoPage != null) {
            displayVideoList(response.VideoPage);
        } else if (response.Video != null) {
			//console.dir(response.Video);
            displayVideoPlayer(response.Video);
			
			if(document.getElementById('selectedGalleryTitle').innerHTML==""){
				getGallery(response.Video.GalleryKey.Key);
			}
			if (response.Video.Author.IsBlocked == 'True') {
                document.getElementById('videoBox').innerHTML = "";
                document.getElementById('videoCommentsBox').innerHTML = "";
            } else {
                displayVideo(response.Video);
                getVideoComments(response.Video.VideoKey.Key);
            }
        } else if (response.CommentPage != null) {
            displayVideoComments(response.CommentPage);
        }
    }
    
    // override DirectAccessErrorHandler to see errors
    function DirectAccessErrorHandler(msg, ex){
        alert(msg + " " + ex);
    }
	// fetch a named request parameter from the page URL
	function getParam(parameterName){
		var key = parameterName + "=";
		var parameters = document.location.search.substring(1).split("&");
		for (var i = 0; i < parameters.length; i++)
		{
			if (parameters[i].indexOf(key) == 0)
				return parameters[i].substring(key.length);
		}
		return null;
	}
	
	// Taking from login.js
	function showDiv(evt, id, offset){

	    posx = mouseX(evt) - offset;    
	    posy = mouseY(evt) - 10;
	
		//normalize to make sure we at least appear on the screen
	    if(posx < 0) posx = 10;
	    if(posy < 0) posy = 10;
    
	    document.getElementById(id).style.left = posx + "px";
		document.getElementById(id).style.top = posy + "px";
		document.getElementById(id).style.display = "block";
	}
	
	function hideDiv(id){ 
 		document.getElementById(id).style.display = "none";
	}

	