// 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 globalUser;
	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'>&nbsp;</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'></div></div>";
		html += "<div class='videoThumbs'><div class='filmThumbs' id='videoListBox'></div><br style='clear:both;' /></div>";
        html += "<div class='siteRightSection'><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>";
		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='/multimedia/video/video_ugc_gallery/?plckGalleryID=" + gallery.GalleryKey.Key + "'><img border='0' src='" + gallery.GalleryPromo.Image.RecentSlide + "' /></a></div>";
				html += "<div class='galDetails'><div class='galTitle'>";
				html += "<a href='/multimedia/video/video_ugc_gallery/?plckGalleryID=" + gallery.GalleryKey.Key + "'>";
				html += gallery.Title;
				html += "</a></div>";
				html += "<div class='galDesc'>"+ gallery.Description +"</div>";
				html += "<div class='galView'><a href='/multimedia/video/video_ugc_gallery/?plckGalleryID=" + gallery.GalleryKey.Key + "'>View Gallery</a></div>";
				html += "<div class='galUpload'><a href='/multimedia/video/video_ugc_upload/?plckGalleryID=" + gallery.GalleryKey.Key + "'>Upload Your Video</a></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
        html += "More "+gallery.Title ;
        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="";
		if (globalUser.UserTier != 'Anonymous') {
			html += "<a href='javascript:void(0);' class='littleButton'><img border='0' class='addVideos' src='http://media.irishcentral.com/designimages/addVideos.jpg' id='UploadYourVideosNow' onclick=\"showDiv(event, 'uploadContent',440);\"/></a>";
		}
		else {
			html += "<div id='mustlogin'>You must <a href='/login'>login</a> to upload vidoes</div>";
			}
        html += "</p><div id='submitVideo' style='display:none'></div>";
        document.getElementById('uploadToGallery').innerHTML = html;
    
        getVideoList(gallery.GalleryKey.Key, globalOnPage);
    }
// 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 != globalUser.UserKey.Key) {
                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 border='0' src='" + video.VideoThumbnail + "'></a></div>";
                    html += "<div class='moreTitle'><a href='#' title='" + video.Title + "' onclick='getVideo(\"" + video.VideoKey.Key + "\")'>" + displayTitlePretty(video.Title) + "</a><br /></div>";
                    break;
                default:
                    html += "<a href='#' title='" + video.Title + "' onclick='getVideo(\"" + video.VideoKey.Key + "\")'>";
                    html += "<img border='0' src='/img/loading.jpg' /></a></div>";
                    html += "<div class='moreTitle'><a href='#' title='" + video.Title + "' onclick='getVideo(\"" + video.VideoKey.Key + "\")'>" + displayTitlePretty(video.Title) + "</a><br /></div>";
                }
                
               
                
            }
            html += "</div>";//end thumbwrap
        }
        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 border='0' src='/img/video/back.jpg' /></a>";
        }
        if (nextPage <= lastPage) {
            html += "<a href='#' title='Go to page " + nextPage + "' onclick='getVideoList(\"" + videoPage.GalleryKey.Key + "\", " + nextPage +")'>More ...</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 != globalUser.UserKey.Key) {
                // use the $ shortcut from prototype.js
                document.getElementById('videoPlayerBox').innerHTML = "<div class='videoMissing'><div>User blocked.</div></div>"
            } else {
/*
                var so = new SWFObject("http://media.irishcentral.com/designvideo/mediaplayer.swf", "video", "500", "375", "9", "#000000");
                so.useExpressInstall('/content/swf/expressinstall.swf');
                so.addVariable('file', video.VideoUrl);
                so.addVariable('autostart', 'true');
                so.addVariable('width', '500');
                so.addVariable('height', '375');
                so.addVariable('allowfullscreen', 'false');
                so.addVariable('allowscriptaccess', 'always');
                so.addParam('wmode', 'transparent');
                so.write('videoPlayerBox');
*/
                var flashvars = {
                  width: '500',
                  height: '375',
                  displaywidth: '500',
                  displayheight: '375',

                  file: video.VideoUrl,
                  //overstretch: 'true', // expands to fit h & v "true" -will stretch them proportionally to fill the display
                  overstretch: 'false', // expands to fit h or v "false" -will stretch them to fit
                  //overstretch: 'fit', // expands to fit h & v "fit" -will stretch them disproportionally to fit both height and width
                  //overstretch: 'none', // displays native size "none" -will show all items in their original dimensions
                  autostart: 'true',
                  shuffle: 'false',
                  repeat: 'list',
                  showstop: 'true',
                  showicons: 'true',
                  showdigits: 'true',
                  thumbsinplaylist: 'true',
                  //logo: 'http://my.domain.com/path/logo.png',
                  enablejs: 'true',
                  javascriptid: 'mpl',
                  searchbar: 'false',
                  backcolor: '0xFFFFFF', // face of buttons
                  frontcolor: '0x404040', // button symbols & playlist text
                  lightcolor: '0x808080', // highlighted playlist item
                  screencolor: '0x000000' // screen background color
                };
                var params = {
                  allowfullscreen: 'true',
                  wmode: 'transparent',
                  autostart: 'true'
                };
                var attributes = {
                  id: "videoPlayerBox",
                  name: "videoPlayerBox"
                };
                swfobject.embedSWF("http://media.irishcentral.com/designvideo/mediaplayer.swf", "videoPlayerBox", "500", "375", "9.0.0","expressInstall.swf", flashvars, params, attributes);

            }
        } 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;
         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='javascript:void(0);' 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='/services/my_profile?UID="+video.Author.UserKey.Key+"'><img src='"+video.Author.AvatarPhotoUrl+"' /></a></div>";
		html+="<div class='authDetail' ><b><a href='/services/my_profile?UID="+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+="<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 (globalUser.UserTier == "Editor") {
			html += "<div><a href=\"http://sitelife.irishcentral.com/ver1.0/CMW/Videos/VideoDetail.rails?galleryKey=" + video.GalleryKey.Key + "&videoKey=" + video.VideoKey.Key + "\">Edit in Workbench</a></div>";

			html += "<div><b>Video Thumbnail:</b><br />";
			html += "<input name='ThumbnailLink' value='"+video.VideoThumbnail+"' type='text' id='ThumbnailLink' width='style:300px'/>";
			if (video.VideoState.State == 'Completed') {
				if (video.Author.IsBlocked == 'True' && video.Author.UserKey.Key != globalUser.UserKey.Key) {
					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://media.irishcentral.com/designvideo/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://media.irishcentral.com/designvideo/mediaplayer.swf' ";
					html += "width='500' height='375' ";
					html += "allowfullscreen='true' ";
					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 />";
		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>";
        }
        // use the document.getElementById shortcut from prototype.js
        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);
    }
    
    // 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);
    }
    
    // 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 galleryKey = new GalleryKey(keyString);
        var videoPage = new VideoPage(galleryKey, 9, onPage);
        talkToServer(videoPage);
    }
    
    // Requests a VideoKey based on a video key string.
    function getVideo(keyString) {
        var videoKey = new VideoKey(keyString);
        talkToServer(videoKey);
    }

    // Requests a VideoKey based on a video key string.
    function getJustVideo(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;
		   globalUser = response.User;
           // 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;
	}
	
 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";
 }
	



