﻿var privilegeLevel = 0; // anonymous == 0, member == 1, profile owner == 2
var anonymous = 0;
var member = 1;
var profileOwner = 2;
var visitorName = "Anonymous";
var subnav_displayed = false;
var current_sub = ""; // represents current subsection
var current_section = ""; // represents current section
var current_page = 1; // represents page of current content
var entry_max = 10;   // maximum entries per page.

var userName = "";
var lastUser = "";
var profTransit = false;

var vid_player_url1 = "http://www.youtube.com/v/";
var vid_player_id   = "";
var vid_player_url2 = "?enablejsapi=1&playerapiid=ytplayer&rel=0&fs=1";
var player_loaded = false;

var thumb_url1 = "http://img.youtube.com/vi/";
var thumb_url2 = "/default.jpg";

var shared_page = 0;   // Pages indicating which group of entries to grab.
var unshared_page = 0;

var current_vidUploader = "";
var current_numVids = 0;

// Youtube related vars
// --------------------
var ytLoggedIn = false;
var ytAuth = "";

var ytAuthorized = false;

// ShareEntryDiv buffers
var unshare_entry_div = document.createElement('div');
unshare_entry_div.className = "share_entries";

var share_entry_div = document.createElement('div');
share_entry_div.className = "share_entries";


var full_buffer_build = true;

var shareFade = false;
var unshareNumVids = 0;

var numUnsharePages = 0;
var unshareTabArray;

var unshareTabTransit = false;

var unshareArray = new Array(); // array of entries the user has unshared
var shareArray = new Array();   // array of entries the user has shared
var shareBufferSize = 16;     // Number of entries to send to the server at a time.
                                // Should there be over a <shareBufferSize> video changes,
                                // a separate post to server-side will be made
                                // for each <shareBufferSize> changes until they're all sent.

var unshare_drag_array = new Array(); // Holds entries dragged from unshare section.
var share_drag_array = new Array();   // entries dragged from share section.

var drag_clear = false;
var drop_clear = false;
var drag_type = 0;

var total_vids_shared = 0;
var total_share_pages = 0;

var shareFade2 = false;
var shareTransit = false;
var shareTabArray = new Array();
var shareNavLoaded = false;
var globEntries = null;

var vid_entry_loaded = false;
var no_player = false;

var id_pool = new Array();

var max_thumb_page = 7;
var thumb_page = 0;



function thumb_ui_goPrev()
{
    if (thumb_page > 0)
    {
        thumb_page -= 1;
        var t_in = document.getElementById('ThumbPagingEntry');
        t_in.value = "" + (thumb_page + 1);
        goto_thumb_page();
    }
}
function thumb_ui_goNext()
{
    if (thumb_page < (Math.ceil(globEntries.length/max_thumb_page) - 1))
    {
        thumb_page += 1;
        var t_in = document.getElementById('ThumbPagingEntry');
        t_in.value = "" + (thumb_page + 1);
        goto_thumb_page();
    }
}
function thumb_page_goto()
{
    var maxPage = Math.ceil(globEntries.length / max_thumb_page);
    var t_in = document.getElementById('ThumbPagingEntry');
    
    var val = parseInt("" + t_in.value);
    
    if ((t_in.value == "")||(!val)||(val < 1) || (val > maxPage))
    {
        t_in.value = "" + (thumb_page + 1);
    }
    else
    {
        thumb_page = val - 1;
        goto_thumb_page();
    }
}
function build_thumb_nav()
{
    // lets build the goto box
    var gotoBox = document.getElementById('VidGotoPane');
    // Need to add the arrows, the field, the slash, and the span for total pages
    var iHtml = "";
    iHtml += "<div class='thumb_page_arrowL' onclick='thumb_ui_goPrev()'>&lt;</div>";
    iHtml += "<div id='ThumbGotoContainer' class='thumb_goto_container'>";
    iHtml += "&nbsp;<span style='float: left; margin-left: 12px; margin-right: 3px; margin-top: 2px'>Go To</span> <input id='ThumbPagingEntry' class='thumb_page_field' type='text' />";
    iHtml += " <span style='float: left; margin-top: 2px'>&nbsp;/&nbsp;</span><div id='ThumbPagingTotal' style='float: left; margin-top: 2px'>" + Math.ceil(globEntries.length / max_thumb_page) + "</div>";
    iHtml += "</div>";
    iHtml += "<div class='thumb_page_arrowR' onclick='thumb_ui_goNext()'>&gt;</div>";
    $(gotoBox).html(iHtml);
    var t_in = document.getElementById('ThumbPagingEntry');
    t_in.value = "" + (thumb_page + 1);
}
function prof_logout()
{
    if (current_section == "video_share")
    {
        sectionSwap("video", "fade");
    }
}
function goto_thumb_page()
{
    var thumb_column = document.getElementById("VidThumbPane");
    $(thumb_column).html(""); // clear previous thumbs
    var startEm = (thumb_page*max_thumb_page);
    var endEm = startEm + max_thumb_page;
    var node = null;
    clearIdPool();
    var thumbBuff = document.createElement('div');
    thumbBuff.className = "vid_thumb_pane";
    for(var i = startEm; (i < endEm)&&(i < globEntries.length);i++)
    {
        node = globEntries[i];
        var thumb_container = document.createElement('div');
        var thumb_id = node.getAttribute("video_id");
        var nodeID = node.getAttribute("video_id");
        var entryEntry = new vidEntry(thumb_id, node.getAttribute("video_title"), node.getAttribute("poster"), nodeID);
        id_pool.push(entryEntry);
        var iHtml = "";
        iHtml += "<div class='video_image' onclick='switch_video(\"" + thumb_id + "\",\"" + nodeID + "\")'><img src='" + thumb_url1 + thumb_id + thumb_url2 + "' alt='' class='video_image'></img></div>";
        iHtml += "<div class='video_label' title='" + node.getAttribute("video_title") + "' onclick='switch_video(\"" + thumb_id + "\",\"" + nodeID + "\")'>" + node.getAttribute("video_title") + "</div>";
        thumb_container.innerHTML = iHtml;
        thumbBuff.appendChild(thumb_container);
    }
    thumbBuff.style.display = "none";
    $(thumb_column).append(thumbBuff);
    $(thumbBuff).fadeIn(400);
}
function thumb_tab_goto(t_page)
{ 

}
function load_thumbs()
{
    thumb_page = 0;
    goto_thumb_page();
}
function cleanVid_Section()
{
    
    var topTop = document.getElementById("VideoTitle");
    var embed = document.getElementById("embed_player");
    var botBot = document.getElementById("VideoComments");
    var thumbs = document.getElementById("VideoThumbs");

    if (topTop == null)
        return;
    $(topTop).html("No videos have been shared yet...");
    $(botBot).html("");
    $(thumbs).html("");
    var divDiv = document.createElement("div");
    divDiv.setAttribute("id", "VideoPlayer");

    //no_player = true;
    
    if (embed != null)
    {
        $(embed).remove();
        $(topTop.parentNode).append(divDiv);
    }
    
    
    if(current_section == "video")
        $('#VideoCol').css("display", "none");
    
    
}
function vidEntry(id, vidTitle, poster, entId)
{
    this.VideoID = id;
    this.Title = vidTitle;
    this.Uploader = poster;
    this.ID = entId;
    
    return true;
}
function clearIdPool()
{
    while (id_pool.length > 0)
        id_pool.pop();
}

function clearArray(arg)
{
    while (arg.length > 0)
    {
        arg.pop();
    }
}
function zForwardShare() 
{
    for (var i = 0; i < pageShare.size(); i++)
    {
        pageShare.S_Entry[i].ShareTag.style.zIndex = 5;
    }
}
function zBackShare()
{
    for (var i = 0; i < pageShare.size(); i++)
    {
        pageShare.S_Entry[i].ShareTag.style.zIndex = 1;
    }
}
function zForwardUnshare()
{
    for (var i = 0; i < pageUnshare.size(); i++)
    {
        pageUnshare.S_Entry[i].ShareTag.style.zIndex = 5;
    }
}
function zBackUnshare()
{
    for (var i = 0; i < pageUnshare.size(); i++)
    {
        pageUnshare.S_Entry[i].ShareTag.style.zIndex = 1;
    }
}
function setup_drags(entry_obj,arg)
{
    if (!drag_clear)
    {
        unshare_drag_array = new Array();
        share_drag_array = new Array();
    }
    if (arg == null)
    {
        unshare_drag_array.push(entry_obj);
        entry_obj.ShareTag.style.opacity = .5;
    }
    else
    {
        share_drag_array.push(entry_obj);
        entry_obj.ShareTag.style.opacity = .5;
    }
    drag_clear = true;
    drop_clear = false;
}

function clear_dts_artifacts() // drag-to-select artifact cleaner
{
    var i = 0;
    
    var divs = document.getElementsByTagName('div');
    for (i = 0; i < divs.length; i++)
    {
        if ((divs[i].className == "jquery-drag-to-select active") || (divs[i].className == "jquery-drag-to-select"))
        {
            divs[i].parentNode.removeChild(divs[i]);
            //i--;
        }
    }
}
function wrap_bindup(arg)
{
    if ((arg == null)||(arg == false))
    {
        var shareZone = document.getElementById('UnsharedEntries');
        $(shareZone).dragToSelect({ selectables: '.DnD_Select', onHide: function()
        {
        }
        });
    }
    else
    {
        var shareZone = document.getElementById('SharedEntries');
        $(shareZone).dragToSelect({ selectables: '.DnD_Select', onHide: function()
        {
        }
        }, "ui-multidraggable2");
    }
}

function cloneShareEntry(entry, shareType,enabled)
{
    var result = new ShareEntry(entry.VideoID, entry.Title, entry.Uploader, shareType,enabled);
    return result;
}
// ### CLASS ShareEntry ###
function ShareEntry(videoID,videoTitle, uploader, shareType,enabled) // constructor
{
    // Data fields     ----
    this.VideoID = videoID;
    this.Uploader = uploader;
    this.Title = convert_apostraphes(videoTitle);
    this.Type = shareType;
    this.ThumbUrl = "";

    // This constructor should also handle the initial enabled/disabled state
    // of video divs inside of the container.  Disabled will use partial
    // opacity to make it clear that the video is already shared.
    // The thing is, there's no easy way that I say to filter videos on a
    // on the query basis from off of youtube based on what videos I already
    // have listed as 'shared'.  Performance problems will escalate exponentially
    // according to how many videos the user has uploaded. A user with a massive
    // number of uploads would incur super long waits in the range of minutes
    // everytime they hit the share UI.  So to defeat this, I can only check on
    // a page by page basis as to whether a Video is already shared.  And it's
    // only sensible that the shared videos still show up, but are clearly
    // not draggable and already used - hence the disabled look.
    var shareZone = document.getElementById('UnsharedEntries');
    var unshareZone = document.getElementById('SharedEntries');
    if (this.Title == null)
        this.Title = "";
    if (this.VideoID != null)
        this.ThumbUrl = thumb_url1 + this.VideoID + thumb_url2;
    // end Data fields ----
    // Construct html for display in video share UI.
    var s_entry_div = document.createElement('div');
    s_entry_div.setAttribute('vidID',this.VideoID);
    if ((enabled == null) || (enabled == true))
        s_entry_div.className = "share_ui_thumb_container DnD_Select";
    else
        s_entry_div.className = "share_ui_thumb_container";
    s_entry_div.videoID = this.VideoID;
    // Top section will be the thumb
    var iHtml = "<div class='share_ui_thumb_subcon'>";
    iHtml += "<div class='share_ui_thumb'><img src='" + this.ThumbUrl + "' class='share_ui_thumb' alt=''/></div>";
    // Bottom: title.  ToolTip it to aleviate the issue with long title names.
       iHtml += "<div class='share_ui_thumb_title' title='" + this.Title + "'>" + this.Title + "</div>";
       iHtml += "</div>";
    $(s_entry_div).html(iHtml);
    
    // Html field      ----
    this.ShareTag = s_entry_div;
    var selfRef = this;
    if ((shareType == null)||(shareType == false))
    {
        if ((enabled == null) || (enabled == true))
        {
            $(this.ShareTag).multidraggable({ helper: "clone", revert: true, start: function() { $(shareZone).unbind(); clear_dts_artifacts(); setup_drags(selfRef); drag_type = 1; },
            stop: function() { wrap_bindup(); drag_clear = false; s_entry_div.style.opacity = 1.0; }
            });
            $(this.ShareTag).mousedown(function() { $(shareZone).unbind(); zForwardUnshare(); });
            $(this.ShareTag).mouseup(function() { wrap_bindup(); zBackUnshare(); });
        }
        else
        {
            // need to make the tag disabled looking.
            this.ShareTag.style.opacity = 0.5;
        }
    }
    else
    {
        if ((enabled == null) || (enabled == true))
        {
            $(this.ShareTag).multidraggable2({ helper: "clone", revert: true, start: function() { $(unshareZone).unbind(); clear_dts_artifacts(); setup_drags(selfRef, true); drag_type = 2; },
                stop: function() { wrap_bindup(); drag_clear = false; s_entry_div.style.opacity = 1.0; }
            });
            $(this.ShareTag).mousedown(function() { $(unshareZone).unbind(); zForwardShare(); });
            $(this.ShareTag).mouseup(function()   { wrap_bindup(true); zBackShare(); });
        }
        else
        {
            this.ShareTag.style.opacity = 0.5;
        }
    }
    return true; // return valid state
}

// ### CLASS ShareCollection ###
function ShareCollection()
{
    // Field for storing an array of ShareEntry objects
    this.S_Entry = new Array();

    // Methods
    this.clear = function()
    {
        var count = this.S_Entry.length;
        while (count > 0)
        {
            try
            {
                $(this.S_Entry[this.S_Entry.length - 1].ShareTag).unbind();
            }
            catch (err) { }
            this.S_Entry.pop();
            count -= 1;
        }
    };
    this.add = function(ent)
    {
        this.S_Entry.push(ent);
    };
    this.size = function() { return this.S_Entry.length; };
    
    return true;
}


var curShare = new ShareCollection(); // Current listing shared
var pageShare = new ShareCollection();


var curUnshare = new ShareCollection(); // Current listing unshared
var pageUnshare = new ShareCollection();


var max_share_entries = 12;

function section_swap(ctrl,swapStyle)
{
    
    if ((swapStyle == null) || (swapStyle == "fade"))
    {
        if (current_section == ctrl)
            return; // already on this section.
        var curSecRef = document.getElementById(current_section+"_body");
        //alert(ctrl+"_body");
        // Using instant fadein for control swap.

        var parent = curSecRef.parentNode;
        var temp = document.getElementById(ctrl + "_body");
        parent.removeChild(temp);
        parent.appendChild(temp);
        curSecRef.style.display = "none";
        current_section = ctrl;
        prof_preload(userName);
        $(temp).fadeIn(400, function()
        {
            player_loaded = false;
            load_vid_player();
        });
    }
    else if(swapStyle == "slide")
    {
        if (current_section == ctrl)
            return; // already on this section.
        if (profTransit)
            return;
        //alert(current_section+"_body");
        var curSecRef = document.getElementById(current_section + "_body");

        // Using instant fadein for control swap.

        var parent = curSecRef.parentNode;
        var temp = document.getElementById(ctrl + "_body");
        parent.removeChild(temp);
        parent.appendChild(temp);
        temp.style.display = "block";
        //curSecRef.style.display = "none";
        current_section = ctrl;
        profTransit = true;
        prof_preload(userName,null,true);

        $(curSecRef).animate({ marginLeft: "-" + $(curSecRef).width() }, 400, function()
        {
            profTransit = false;
            curSecRef.style.display = "none";
            curSecRef.style.marginLeft = "0px";
            if (current_section == "video")
            {
                player_loaded = false;
                load_vid_player();
            }
        });
    }
}
function sub_swap(ctrl)
{

}
function status_submit()
{
    var status_tag = document.getElementById('StatusEntry');
    $.ajax({
        type: "POST",
        url: "ProfileManager.asmx/setStatus",
        contentType: "application/json; charset=utf-8",
        data: "{'username':'" + userName + "'," +
               "'content':'" + convert_apostraphes( status_tag.value )+ "'" +
        "}",
        dataType: "json",
        success: (function(msg)
        {
            //alert(msg.d);
            prof_preload(userName);
        }),
        error: AjaxFailed
    });
}
/*
function textareaSize()
{
    var textarea = document.getElementById('StatusEntry');
    var adjustedHeight = textarea.clientHeight;

    
    adjustedHeight = Math.max(textarea.scrollHeight, adjustedHeight);
    if (adjustedHeight > textarea.clientHeight)
        textarea.style.height = adjustedHeight + "px";
    if (textarea.scrollHeight < textarea.clientHeight)
        textarea.style.height = textarea.scrollHeight + "px";
    
    
    
}*/
function build_status_field()
{
    var status_input = document.createElement('div');
    status_input.className = "status_entry_div";
    // we know this control needs an entry field and a submit button.
    var iHtml = "";
    iHtml += "<div class='status_entry_container'><textarea id='StatusEntry' class='status_entry'></textarea></div>\n"
    iHtml += "<div class='status_submit_div'><div class='status_submit' onclick='status_submit()' >Submit</div></div>\n";
    status_input.innerHTML = iHtml;
    //$('#StatusEntry').elastic();
    return status_input;
}
function prof_preload(username,section_option,transition)
{
    //player_loaded = false;
    clearIdPool();
    userName = logUser;
    var avatar = document.getElementById("prof_avatar_img");
    
    if(!(current_section == "video_share"))
    {
        bring_back_header(); // make sure those columns are visible, etc.
    }
    if (username != null)
    {
        userName = username;
    }
    if (userName != "")
        lastUser = userName;
    else
        userName = lastUser;
    if (userName == "")
    {
        userName = readCookie("ProfileTarget");
        if (userName != "")
            lastUser = userName;
    }


    avatar.src = "./Profiles/" + userName + "Profile/Images/Avatar.png";
    if (section_option == null)
    {
        if (current_section == "video")
        {
            avatar.style.display = "none";
        }
        else
        {
            avatar.style.display = "block";
        }
    }
    else if (section_option == "video")
    {
        avatar.style.display = "none";
    }
    else
    {
        avatar.style.display = "block";
    }
    //alert(avatar.src);
    if (section_option != null)
        current_section = section_option;
    if (current_section == "")
        current_section = "wall";

    if (current_section == "video")
    {
        var colCol = document.getElementById('VideoCol');
        colCol.style.display = "block";
    }
    else
    {
        var colCol = document.getElementById('VideoCol');
        colCol.style.display = "none";
    }
    $.ajax({
        type: "POST",
        url: "ProfileManager.asmx/getContent",
        contentType: "application/json; charset=utf-8",
        data: "{'username':'" + userName + "'," +
               "'xmlName':'" + current_section + "'," +
               "'getTop':'" + true + "'" +
        "}",
        dataType: "json",
        success: (function(msg)
        {
            // So now we build the page using the data we've got.
            var result = msg.d[0].split("\n");
            var result2 = msg.d[1].split("\n");
            var i = 0;

            var status = document.getElementById("prof_status");
            var status_edit = document.getElementById("prof_status_edit");
            status_edit.innerHTML = "";
            var contents = "";
            for (i = 0; i < result.length; i++)
            {
                //alert(result[i]);
                if (i == 0)
                {
                    if (result[i] == "") // anonymous user
                    {
                        privilegeLevel = anonymous;
                        visitorName = "Anonymous";
                    }
                    else if (result[i] == userName) // profile owner
                    {
                        privilegeLevel = profileOwner;
                        visitorName = result[i];
                    }
                    else
                    {
                        privilegeLevel = member;
                        visitorName = result[i];
                    }
                    if (result.length < 3)
                        status.innerHTML = userName;
                    //alert(visitorName + "\nAccess Level: "+privilegeLevel);
                }
                else if (i == 1)
                {

                    /*
                    if (result[i] == "")
                    {
                    avatar.src = "./Default_Images/DefaultAvatar.png";
                    }
                    else
                    {
                    avatar.src = "./Profiles/" + userName + "Profile/Images/" + result[i];
                    }
                    */
                }
                else if (i == 2)
                {
                    if (result[i] == "")
                    {
                        status.innerHTML = userName;
                    }
                    else
                    {
                        status.innerHTML = userName + ": " + result[i];
                    }
                }
                else if (i > 2)
                {
                    status.innerHTML += "\n" + result[i];
                }
            }
            for (i = 0; i < result2.length; i++)
                contents += result2[i] + "\n";
            // Here we'll use the xml dom to work with the string
            var parser = null;
            var xmlDoc = null;
            var j = 0;
            if (window.DOMParser)
            {
                parser = new DOMParser();
                xmlDoc = parser.parseFromString(contents, "text/xml");
            }
            else // Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(contents);
            }

            //alert(xmlDoc.childNodes[0].nodeName);
            var rootContent = (((current_section != "video_share") && (current_section != "video_upload")) ? ((xmlDoc.childNodes[0].nodeName == "content") ? xmlDoc.childNodes[0] : xmlDoc.childNodes[1]).childNodes : null);
            //alert(xmlDoc.childNodes[1].nodeName);
            // Clear the subnav tabs!
            clear_sub_tabs();
            if (transition == null)
                hide_sections();
            var sub_tab;
            var sub_nav = document.getElementById("sub_nav");
            var had_sub = false;
            // for the time being, we now assume that section at preload is
            // main, and subsection is wall that is active.  and of course, page 1.

            var section_ref = null;
            section_ref = document.getElementById(current_section + "_body");
            if (transition == null)
                section_ref.style.display = "block";
            if (current_section != "video")
                section_ref.innerHTML = "";
            else
            {
                // for the video, we only need to clear the sections
                // like thumbs column, title, descriptions, and comments.
                // We do not want to clear the video player.  It doesn't
                // look good to have to reload it every time.

                // We'll definitely want to clear the video posting div if there is one.
                var vid_inputer = document.getElementById("VideoEntryContainer");
                if (vid_inputer != null)
                    vid_inputer.innerHTML = "";
            }
            var entries = null;

            if (privilegeLevel == profileOwner)
            {
                status_edit.appendChild(build_status_field());
                $('#StatusEntry').elastic();
            }

            // First and foremost, an entry box needs to be generated
            // for posting content if this is the wall.
            if ((current_section == "wall") && (privilegeLevel > 0))
            {
                section_ref.innerHTML = "";
                section_ref.appendChild(build_post_field());
                $('#PostEntry').elastic();
                //alert(current_section);
            }
            else if (current_section == "video")
            {   // only video owner gets video entry field.
                build_video_field(section_ref);
                //if (appChild != null)
                //    section_ref.appendChild(appChild);
                $('#VideoDetailEntry').elastic();
            }
            //alert(rootContent.length);
            if (!(current_section == "video_share"))
            {
                for (i = 0; i < rootContent.length; i++)
                {
                    if (rootContent[i].nodeName == "subsection")
                    {
                        had_sub = true;
                        // If the subsection nav bar isn't yet displayed...
                        // display it.
                        if (current_section == "")
                            current_section = rootContent[i].getAttribute('name');
                        if (!subnav_displayed)
                        {
                            sub_nav.style.display = "block";
                            subnav_displayed = true;
                            // add the tab
                            sub_tab = document.createElement('div');
                            sub_tab.setAttribute('class', 'sub_nav_tab');
                            sub_tab.innerHTML = "" + rootContent[i].getAttribute('name');
                            sub_nav.appendChild(sub_tab);
                        }
                        else
                        {
                            // add the tab
                            sub_tab = document.createElement('div');
                            sub_tab.setAttribute('class', 'sub_nav_tab');
                            sub_tab.innerHTML = "" + rootContent[i].getAttribute('name');
                            sub_nav.appendChild(sub_tab);
                        }
                        // Now let's grab the content of this subsection if this subsection
                        // name matches the current subsection name.
                        // We need to only grab the entries from (current_page-1 * max entries
                        // to current_page *max_entries -1)
                        if (current_sub == rootContent[i].getAttribute('name'))
                        {
                            section_ref = document.getElementById(current_section + "_body");
                            section_ref.style.display = "block";
                            // Build the section with it's entry posts.
                            entries = rootContent[i].getElementsByTagName("Entry");
                            $(section_ref).html("");
                            for (j = 0; j < entries.length; j++)
                            {
                                // perhaps we can delegate the task of building
                                // the elements and stuff to a separate function call.
                                // All it should need is the content and the section and
                                // subsection name.

                                section_ref.appendChild(build_entry(current_section, current_sub, entries[j]));

                            }
                        }
                    }
                }
                if (had_sub == false) // no subsections, no tab.
                {
                    sub_nav.style.display = "none";
                    //section_ref = document.getElementById(current_section + "_body");
                    //section_ref.style.display = "block";
                    // Build the section with it's entry posts.
                    //alert(rootContent.length);
                    if (rootContent.length >= 1)
                    {
                        entries = rootContent[0].parentNode.getElementsByTagName("Entry");
                        globEntries = entries;
                        //alert(entries[0].firstChild.nodeValue);

                        //entries = xmlDoc.firstChild.getElementsByTagName("Entry");
                        var appChild = null;
                        for (j = 0; j < entries.length; j++)
                        {
                            // perhaps we can delegate the task of building
                            // the elements and stuff to a separate function call.
                            // All it should need is the content and the section and
                            // subsection name.
                            

                            appChild = build_entry(current_section, "", entries[j], ((j == 0) ? null : true));

                            //if(current_section=="video")
                            //    alert((appChild != null));
                            if (appChild != null)
                                section_ref.appendChild(appChild);
                            if ((j == 0) && (current_section == "video"))
                            {
                                //build_video_thumb(current_section, "", entries[j]);
                                break; // We only need to load the video_entry.
                            }
                        }
                        //if (current_section == "video")
                        //    load_vid_player();
                    }
                    if ((entries.length <= 0)&&(current_section == "video"))
                    {
                        cleanVid_Section();
                    }
                    else if (current_section == "video")
                    {
                        build_thumb_nav();
                        load_thumbs();
                    }
                }
            }
            else
            {
                build_video_share();
            }
            //alert(buildUp);
            //alert(msg.d);
            //alert((msg.d == "") ? "entry successful" : "entry failed: \n\n" + msg.d);
        }),
        error: AjaxFailed
    });
}
function clear_sub_tabs()
{
    document.getElementById("sub_nav").innerHTML = "";
}
function hide_sections()
{
    document.getElementById("wall_body").style.display = "none";
    document.getElementById("bio_body").style.display = "none";
    document.getElementById("photo_body").style.display = "none";
    document.getElementById("video_body").style.display = "none";

}
function del_entry(entryID)
{
    //alert(entryID);
    $.ajax({
        type: "POST",
        url: "ProfileManager.asmx/deleteEntry",
        contentType: "application/json; charset=utf-8",
        data: "{'username':'" + userName + "'," +
               "'xmlName':'wall.syc',"+
               "'id':'" + entryID + "'" +
        "}",
        dataType: "json",
        success: (function(msg)
        {
            //alert(msg.d);
            prof_preload(userName);
        }),
        error: AjaxFailed
    });
    prof_preload(userName);
}
function del_video_entry(entryID)
{
    //alert(entryID);
    $.ajax({
        type: "POST",
        url: "ProfileManager.asmx/deleteEntry",
        contentType: "application/json; charset=utf-8",
        data: "{'username':'" + userName + "'," +
               "'xmlName':'video.syc'," +
               "'id':'" + entryID + "'" +
        "}",
        dataType: "json",
        success: (function(msg)
        {
            //alert(msg.d);
            prof_preload(userName);
        }),
        error: AjaxFailed
    });
    prof_preload(userName);
}
function del_comment(entryID,commentID)
{
    $.ajax({
        type: "POST",
        url: "ProfileManager.asmx/deleteComment",
        contentType: "application/json; charset=utf-8",
        data: "{'username':'" + userName + "'," +
               "'xmlName':'wall.syc'," +
               "'id':'" + entryID + "'," +
               "'commentId':'" + commentID + "'" +
        "}",
        dataType: "json",
        success: (function(msg)
        {
            //alert(msg.d);
            prof_preload(userName);
        }),
        error: AjaxFailed
    });
    prof_preload(userName);
}
function del_video_comment(entryID, commentID)
{
    $.ajax({
        type: "POST",
        url: "ProfileManager.asmx/deleteComment",
        contentType: "application/json; charset=utf-8",
        data: "{'username':'" + userName + "'," +
               "'xmlName':'video.syc'," +
               "'id':'" + entryID + "'," +
               "'commentId':'" + commentID + "'" +
        "}",
        dataType: "json",
        success: (function(msg)
        {
            //alert(msg.d);
            prof_preload(userName);
        }),
        error: AjaxFailed
    });
    prof_preload(userName);
}
function add_comment(entryID)
{
    
    var post_tag = document.getElementById("CommentEntry" + entryID);
    //alert(post_tag.value);
    $.ajax({
        type: "POST",
        url: "ProfileManager.asmx/addComment",
        contentType: "application/json; charset=utf-8",
        data: "{'username':'" + userName + "'," +
               "'xmlName':'" + "wall.syc'," +
               "'poster':'" + visitorName + "'," +
               "'subsection':''," +
               "'id':'"+entryID+"',"+
               "'content':'" + convert_apostraphes(post_tag.value) + "'" +
        "}",
        dataType: "json",
        success: (function(msg)
        {
            //alert(msg.d);
            prof_preload(userName);
        }),
        error: AjaxFailed
    });
}
function add_video_comment(entryID)
{
    var post_tag = document.getElementById("VidCommentEntry" + entryID);
    //alert(visitorName);
    //alert(post_tag.value);
    $.ajax({
        type: "POST",
        url: "ProfileManager.asmx/addComment",
        contentType: "application/json; charset=utf-8",
        data: "{'username':'" + userName + "'," +
               "'xmlName':'" + "video.syc'," +
               "'poster':'" + visitorName + "'," +
               "'subsection':''," +
               "'id':'" + entryID + "'," +
               "'content':'" + convert_apostraphes(post_tag.value) + "'" +
        "}",
        dataType: "json",
        success: (function(msg)
        {
            //alert(msg.d);
            prof_preload(userName);
        }),
        error: AjaxFailed
    });
}
function build_entry(section_name,sub_name,node,optionDetail)
{
    // here we build a div with the necessary content for this section.
    // depending on the privilegeLevel of the visitor, we'll decide whether
    // to provide a textbox for entering new content to the page.
    if (section_name == 'wall')
    {
        return build_wall_entry(section_name, sub_name, node);
    }
    else if (section_name == 'video')
    {
        //alert(optionDetail);
        if (optionDetail == null)
        {
            if (!vid_entry_loaded)
            {
                vid_entry_loaded = true;
                return build_video_entry(section_name, sub_name, node);
            }
            else
                reload_video_entry(section_name, sub_name, node);
            
        }
        else
        {
            build_video_thumb(section_name, sub_name, node);
            return null;
        }
    }

    return document.createElement('div');
}
function parseVideoID(urlString)
{
    var i = 0;
    var pastV = false;
    var result = "";
    for (i = 0; i < urlString.length; i++)
    {
        if (!pastV)
        {
            if (urlString.charAt(i) == 'v')
            {
                i += 1;
                pastV = true;
            }
        }
        else
        {
            if ((urlString.charAt(i) != '&') && (urlString.charAt(i) != '?'))
            {
                result += urlString.charAt(i);
            }
            else
                break;
        }
    }
    return result;
}
function vidIdGrab()
{
    vid_player_id = id_pool[0].VideoID;
    if (vid_player_id == null)
        vid_player_id = "";
}
function load_vid_player()
{
    //alert("tried it");
    try
    {
        if (!player_loaded)
        {
            vidIdGrab();
            if (vid_player_id == "")
            {

                return; // can't load the player without a video id.
            }
            var s_width = $('#video_body').width();
            var s_height = parseInt(parseFloat(s_width) * 0.61);
            //alert(vid_player_url1 + vid_player_id + vid_player_url2);
            
            var params = { allowScriptAccess: "always",
                allowFullScreen: "true",
                wmode: "opaque"
            };
            var atts = { id: "embed_player" };
            swfobject.switchOffAutoHideShow();
            swfobject.embedSWF(vid_player_url1 + vid_player_id + vid_player_url2,
                       "VideoPlayer", ""+s_width, ""+s_height, "8", null, null, params, atts);
            player_loaded = true;
            var player = document.getElementById('embed_player');
            player.style.width = s_width;
            player.style.height = s_height;
            //player.cueVideoById(vid_player_id, 0, "default");
            
        }
        else
        {
            var player = document.getElementById('embed_player');
            //alert(vid_player_id);
            player.cueVideoById(vid_player_id, 0, "default");
        }
    }
    catch (err)
    {
        //alert(err);
    }
    return "stuff";
}
function reload_video_comments(node, data)
{
    var vid_comments_tag = document.getElementById("VideoComments");
    //var vid_thumbs_tag = document.getElementById("VideoThumbs");
    $(vid_comments_tag).html("");
    var iHtml = "";
    var i = 1;
    var nodeChildren = node.childNodes;
    var subNodeID = 0;
    var nodeID = node.getAttribute("video_id");
    
    var nodeVal = "";
    var visitorName = logUser;
    if (visitorName == "")
        visitorName = "Anonymous";
    
    for (i = 0; i < nodeChildren.length; i++)
    {
        subNodeID = nodeChildren[i].getAttribute("id");
        nodeVal = "";
        if (nodeChildren[i].firstChild.firstChild != null)
            nodeVal = nodeChildren[i].firstChild.firstChild.nodeValue;

        iHtml += "<div class='entry_div_video_comment'>" +
                 "<div class='entry_div_avatar_container'><img src='./Profiles/" + nodeChildren[i].getAttribute("poster") + "Profile/Images/Avatar.png' alt='' class='entry_div_avatar'></img></div>" +
                 "<div class='entry_div_comment_content'><span>" + nodeChildren[i].getAttribute("poster") + ": " + nodeVal + "</span></div>" +
                 "</div>" +
                 "<div class='float_slayer'></div>";
        if ((privilegeLevel >= 2) || (visitorName == nodeChildren[i].getAttribute("poster")))
        {
            iHtml += "<div class='delete_button' onclick='del_video_comment(\"" + nodeID + "\"," + subNodeID + ")'>delete</div>" +
                     "<div class='float_slayer'></div>";
        }
    }
    if (privilegeLevel > 0)
    {
        iHtml += "<div class='entry_div_video_comment'>" +
                 "<div class='entry_div_avatar_container'><img src='./Profiles/" + userName + "Profile/Images/Avatar.png' alt='' class='entry_div_avatar'></img></div>" +
                 "<div class='entry_div_comment_content'><textarea id='VidCommentEntry" + nodeID + "' class='comment_entry'></textarea></div>" +
                 "</div>" +
                 "<div class='float_slayer'></div>";
        iHtml += "<div class='delete_button' onclick='add_video_comment(\"" + nodeID + "\")'>Submit</div>" +
                 "<div class='float_slayer'></div>";
    }
    $(vid_comments_tag).html(iHtml);
}
function switch_video(vid_id,nodeID)
{
    var player = document.getElementById('embed_player');
    player.cueVideoById(vid_id, 0, "default");
    var titleDiv = document.getElementById('VideoTitle');
    var vidEnt = null;
    //alert(id_pool.length);
    for (var i = 0; i < id_pool.length; i++)
    {
        if (id_pool[i].VideoID == vid_id)
        {
            vidEnt = id_pool[i];
            break;
        }
    }
    $(titleDiv).html(vidEnt.Title);
    var curNode = null;
    for (var i = 0; i < globEntries.length; i++)
    {
        if (globEntries[i].getAttribute('video_id') == vidEnt.VideoID)
        {
            curNode = globEntries[i];
            break;
        }
    }
    reload_video_comments(curNode,vidEnt);
    //if(privilegeLevel == 2)
    //    document.getElementById('VideoDelete').onclick = (function() { del_video_entry(nodeID); });
}
function build_video_thumb(section_name, sub_name, node)
{
    var thumb_column = document.getElementById("VideoThumbs");
    var thumb_container = document.createElement('div');
    var thumb_id = node.getAttribute("video_id");
    var nodeID = node.getAttribute("video_id");
    var entryEntry = new vidEntry(thumb_id, node.getAttribute("video_title"), node.getAttribute("poster"), nodeID);
    id_pool.push(entryEntry);
    var iHtml = "";
    iHtml += "<div class='video_image' onclick='switch_video(\"" + thumb_id + "\",\"" + nodeID + "\")'><img src='" + thumb_url1 + thumb_id + thumb_url2 + "' alt='' class='video_image'></img></div>";
    iHtml += "<div class='video_label' title='" + node.getAttribute("video_title") + "' onclick='switch_video(\"" + thumb_id + "\",\"" + nodeID + "\")'>" + node.getAttribute("video_title") + "</div>";
    thumb_container.innerHTML = iHtml;
    thumb_column.appendChild(thumb_container);
}
function reload_video_entry(section_name, sub_name, node)
{
    // Need to reset title, description, reload video, and reload comments.

    // The title...
    var vidTitle = node.getAttribute("video_title");
    var vid_title_tag = document.getElementById("VideoTitle");
    $(vid_title_tag).html((vidTitle == null)?"":vidTitle);
    
    // Description
    var vid_detail_tag = document.getElementById("VideoDetails");
    var vidDetails = "";
    if (node != null)
    if (node.firstChild != null)
    if (node.firstChild.firstChild != null)
        vidDetails = node.firstChild.firstChild.nodeValue;
    vid_detail_tag.innerHTML = (vidDetails == null)?"":vidDetails;
    
    // Comments section
    var vid_comments_tag = document.getElementById("VideoComments");
    var vid_thumbs_tag = document.getElementById("VideoThumbs");
    vid_thumbs_tag.innerHTML = "";
    var iHtml = "";
    var i = 0;
    var nodeChildren = node.childNodes;
    var subNodeID = 0;
    var nodeID = node.getAttribute("video_id");
    var nodeVal = "";

    for (i = 0; i < nodeChildren.length; i++)
    {
        subNodeID = nodeChildren[i].getAttribute("id");
        nodeVal = "";
        if (nodeChildren[i].firstChild.firstChild != null)
            nodeVal = nodeChildren[i].firstChild.firstChild.nodeValue;

        iHtml += "<div class='entry_div_video_comment'>" +
                 "<div class='entry_div_avatar_container'><img src='./Profiles/" + nodeChildren[i].getAttribute("poster") + "Profile/Images/Avatar.png' alt='' class='entry_div_avatar'></img></div>" +
                 "<div class='entry_div_comment_content'><span>" + nodeChildren[i].getAttribute("poster") + ": " + nodeVal + "</span></div>" +
                 "</div>" +
                 "<div class='float_slayer'></div>";
        if ((privilegeLevel >= 2) || (visitorName == nodeChildren[i].getAttribute("poster")))
        {
            iHtml += "<div class='delete_button' onclick='del_video_comment(\"" + nodeID + "\"," + subNodeID + ")'>delete</div>" +
                     "<div class='float_slayer'></div>";
        }
    }
    if (privilegeLevel > 0)
    {
        iHtml += "<div class='entry_div_video_comment'>" +
                 "<div class='entry_div_avatar_container'><img src='./Profiles/" + userName + "Profile/Images/Avatar.png' alt='' class='entry_div_avatar'></img></div>" +
                 "<div class='entry_div_comment_content'><textarea id='VidCommentEntry" + nodeID + "' class='comment_entry'></textarea></div>" +
                 "</div>" +
                 "<div class='float_slayer'></div>";
        iHtml += "<div class='delete_button' onclick='add_video_comment(\"" + nodeID + "\")'>Submit</div>" +
                 "<div class='float_slayer'></div>";
    }
    vid_comments_tag.innerHTML = iHtml;
}
function build_video_entry(section_name, sub_name, node)
{
    // Need to create a youtube embedded player instance with the url
    // indicated by the entry.  This shall be indicated by an attribute
    // called 'url' or something like that.  There shall be a section right
    // below the video where the person posting the video could have some
    // comment explaining the video or whatever they want.
    // Then an area beneath it shall be dedicated to listing the comments made
    // on the video by any site member.
    // There are three youtube video image thumbs per video, and 0 is a full size one.
    // http://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
    // Simply need to parse out the video id code out of urls to get at
    // the image url.  Attribute 'thumb' will contain the number of the thumb,
    // in the range of 1 to 3 inclusive.  Restricting the usage of the full
    // size pic to save on load times.
    // Video id's by themselves are specified in the 'VidID' attribute.

    var entry_div = document.createElement('div');
    entry_div.className = "video_watch_div";

    var s_width = $('#video_body').width();
    var s_height = parseInt(parseFloat(s_width) * 0.61);
    /* Structure of Video entry:
    *       TopSection:
                Video block
                description block same width directly below video.
            BottomSection:
                Comment section (fullwidth minus right column width
                Right Column
                    Video thumbs list.
    */
    //if (true)
    //    return entry_div;
    var vidTitle = node.getAttribute("video_title");
    vid_player_id = node.getAttribute("video_id");
    var entryEntry = new vidEntry(vid_player_id, vidTitle, node.getAttribute("poster"), node.getAttribute("video_id"));
    id_pool.push(entryEntry);
    //alert(vi);
    if (vidTitle == null)
        vidTitle = "";
    var vidDetails = "";
    //if (node.firstChild.firstChild != null)
    //    vidDetails = node.firstChild.firstChild.nodeValue;

    var nodeID = node.getAttribute("video_id");
    
    var vidPlayerHtml = "";
    var iHtml = "";
    iHtml += "<div class='video_container'>";
        iHtml += "<div class='video_top'>";
            iHtml += "<div id='VideoTitle' class='video_title'>" + vidTitle + "</div>";
            iHtml += "<div id='VideoPlayer' class='video_player'></div>";
            iHtml += "<div id='VideoDetails' class='video_description'>" + vidDetails + "</div>";
            if ((privilegeLevel >= 2) || (visitorName == node.getAttribute("poster")))
            {
                //iHtml += "<div id='VideoDelete' class='delete_button' onclick='del_video_entry(" + nodeID + ")'>delete</div>";
                //iHtml += "<div class='float_slayer'></div>";
            }
        iHtml += "</div>";
        iHtml += "<div class='video_bottom'>";
            iHtml += "<div id='VideoComments' class='video_comments'>";
    var i = 0;
    var nodeChildren = node.childNodes;
    var subNodeID = 0;
    var nodeVal = "";

    for (i = 0; i < nodeChildren.length; i++)
    {
        subNodeID = nodeChildren[i].getAttribute("id");
        nodeVal = "";
        if (nodeChildren[i].firstChild.firstChild != null)
            nodeVal = nodeChildren[i].firstChild.firstChild.nodeValue;

        iHtml += "<div class='entry_div_video_comment'>" +
                 "<div class='entry_div_avatar_container'><img src='./Profiles/" + nodeChildren[i].getAttribute("poster") + "Profile/Images/Avatar.png' alt='' class='entry_div_avatar'></img></div>" +
                 "<div class='entry_div_comment_content'><span>" + nodeChildren[i].getAttribute("poster") + ": " + nodeVal + "</span></div>" +
                 "</div>" +
                 "<div class='float_slayer'></div>";
        if ((privilegeLevel >= 2) || (visitorName == nodeChildren[i].getAttribute("poster")))
        {
            iHtml += "<div class='delete_button' onclick='del_video_comment(\"" + nodeID + "\"," + subNodeID + ")'>delete</div>" +
                     "<div class='float_slayer'></div>";
        }
    }
    if (privilegeLevel > 0)
    {
        iHtml += "<div class='entry_div_video_comment'>" +
                 "<div class='entry_div_avatar_container'><img src='./Profiles/" + userName + "Profile/Images/Avatar.png' alt='' class='entry_div_avatar'></img></div>" +
                 "<div class='entry_div_comment_content'><textarea id='VidCommentEntry" + nodeID + "' class='comment_entry'></textarea></div>" +
                 "</div>" +
                 "<div class='float_slayer'></div>";
        iHtml += "<div class='delete_button' onclick='add_video_comment(\"" + nodeID + "\")'>Submit</div>" +
                 "<div class='float_slayer'></div>";
    }
            iHtml += "</div>";
            iHtml += "<div id='VideoThumbs' class='video_thumbs'>";
            
            iHtml += "</div>";
        iHtml += "</div>";
    iHtml += "</div>";
    //$(entry_div).html(iHtml);
    entry_div.innerHTML = iHtml;
    return entry_div;
}
function build_wall_entry(section_name,sub_name,node)
{
    if (sub_name == "") // no sub section?  then we go by the section name
    {
        //var section_ref = document.getElementById(section_name + "_body");
        var entry_div = document.createElement('div');
        entry_div.className = "entry_div";
        // Set up the poster's avatar and entry message.
        //alert(node.firstChild.nodeValue);
        var nodeID = node.getAttribute("id");
        var nodeVal = "";
        if (node.firstChild.firstChild != null)
            nodeVal = node.firstChild.firstChild.nodeValue;
        entry_div.innerHTML += "<div class='entry_div_avatar_container'><img src='./Profiles/" + node.getAttribute("poster") + "Profile/Images/Avatar.png' alt='' class='entry_div_avatar'></img></div>";
        entry_div.innerHTML += "<div class='entry_div_content'>" + node.getAttribute("poster")+": "+ nodeVal + "</div";
        entry_div.innerHTML += "<div class='float_slayer'></div>";
        if ((privilegeLevel >= 2) || (visitorName == node.getAttribute("poster")))
        {
            entry_div.innerHTML += "<div class='delete_button' onclick='del_entry(" + nodeID + ")'>delete</div>";
            entry_div.innerHTML += "<div class='float_slayer'></div>";
        }
        var i = 1;
        var nodeChildren = node.childNodes;
        var subNodeID = 0;
        
        
        for (i = 1; i < nodeChildren.length; i++)
        {
            subNodeID = nodeChildren[i].getAttribute("id");
            nodeVal = "";
            if (nodeChildren[i].firstChild.firstChild != null)
                nodeVal = nodeChildren[i].firstChild.firstChild.nodeValue;
            
            entry_div.innerHTML += "<div class='entry_div_comment'>" +
                                   "<div class='entry_div_avatar_container'><img src='./Profiles/" + nodeChildren[i].getAttribute("poster") + "Profile/Images/Avatar.png' alt='' class='entry_div_avatar'></img></div>" +
                                   "<div class='entry_div_comment_content'><span>" + nodeChildren[i].getAttribute("poster") + ": " + nodeVal + "</span></div>" +
                                   "</div>" +
                                   "<div class='float_slayer'></div>";
            if ((privilegeLevel >= 2) || (visitorName == nodeChildren[i].getAttribute("poster")))
            {
                entry_div.innerHTML += "<div class='delete_button' onclick='del_comment(\"" + nodeID + "\",\"" + subNodeID + "\")'>delete</div>" +
                                       "<div class='float_slayer'></div>";
            }
        }
        if (privilegeLevel > 0)
        {
            entry_div.innerHTML += "<div class='entry_div_comment'>" +
                                   "<div class='entry_div_avatar_container'><img src='./Profiles/" + userName + "Profile/Images/Avatar.png' alt='' class='entry_div_avatar'></img></div>" +
                                   "<div class='entry_div_comment_content'><textarea id='CommentEntry"+nodeID+"' class='comment_entry'></textarea></div>"+
                                   "</div>"+
                                   "<div class='float_slayer'></div>";
            entry_div.innerHTML += "<div class='delete_button' onclick='add_comment(\""+nodeID+"\")'>Submit</div>" +
                                   "<div class='float_slayer'></div>";
        }
        return entry_div;
    }
    else
    { 
    
    }
}
function submit_wall_post()
{
    var post_tag = document.getElementById("PostEntry");
    $.ajax({
        type: "POST",
        url: "ProfileManager.asmx/addEntry",
        contentType: "application/json; charset=utf-8",
        data: "{'username':'" + userName + "'," +
               "'xmlName':'" + "wall.syc'," +
               "'poster':'"+ visitorName+"',"+
               "'subsection':''," +
               "'content':'" + convert_apostraphes(post_tag.value) + "'" +
        "}",
        dataType: "json",
        success: (function(msg)
        {
            //alert(msg.d);
            prof_preload(userName);
        }),
        error: AjaxFailed
    });
}
function submit_video_post()
{
    var url_tag = document.getElementById("VideoUrlEntry");
    var detail_tag = document.getElementById("VideoDetailEntry");
    var title_tag = document.getElementById("VideoTitleEntry");
    $.ajax({
        type: "POST",
        url: "ProfileManager.asmx/addVideoEntry",
        contentType: "application/json; charset=utf-8",
        data: "{'username':'" + userName + "'," +
               "'xmlName':'" + "video.syc'," +
               "'poster':'" + visitorName + "'," +
               "'subsection':''," +
               "'title':'" + convert_apostraphes(title_tag.value) + "'," +
               "'url':'" + convert_apostraphes(url_tag.value) + "'," +
               "'description':'" + convert_apostraphes(detail_tag.value) + "'" +
        "}",
        dataType: "json",
        success: (function(msg)
        {
            //alert(msg.d);
            prof_preload(userName);
        }),
        error: AjaxFailed
    });
}
function build_post_field()
{
    // Here we build something... pretty much identical to the status entry field.
    var post_input = document.createElement('div');
    post_input.className = "status_entry_div";
    // we know this control needs an entry field and a submit button.
    var iHtml = "";
    iHtml += "<div class='status_entry_container'><textarea id='PostEntry' class='status_entry'></textarea></div>\n"
    iHtml += "<div class='status_submit_div'><div class='status_submit' onclick='submit_wall_post()'>Submit</div></div>\n";
    
    post_input.innerHTML = iHtml;
    return post_input;
}
function build_video_field(section_reference) 
{
    var vid_input = document.getElementById("VideoEntryContainer");
    
    if (vid_input == null)
    {
        vid_input = document.createElement('div');
        vid_input.className = "video_entry_div";
        vid_input.id = "VideoEntryContainer";
        section_reference.appendChild(vid_input);
    }
    vid_input.style.borderStyle = "none";
    if (privilegeLevel == 2)
    {
        
        // we know this control needs an entry field and a submit button.
        var iHtml = "";
        // Link to the video sharing page.
        iHtml += "<div class='share_link' onclick='section_swap(\"video_share\",\"fade\")'>Share More Videos</div>";
        /*
        iHtml += "<div class='status_entry_container'>"
        iHtml += "<div class='video_text'>Video Title:</div><div class='video_url_wrap'><input id='VideoTitleEntry' type='text' class='video_url_entry'/></div>"
        iHtml += "<div class='video_text'>Video URL:</div><div class='video_url_wrap'><input id='VideoUrlEntry' type='text' class='video_url_entry'/></div>"
        iHtml += "<div class='video_text'>Video Description:</div><textarea id='VideoDetailEntry' class='status_entry'></textarea></div>\n"
        iHtml += "<div class='video_submit_div'><div class='status_submit' onclick='submit_video_post()'  >Submit</div></div>\n";
        */
        $(vid_input).html(iHtml);
        vid_input.style.display = 'block';
    }
    else
    {
        $(vid_input).html("");
        vid_input.style.display = 'none';
    }
    //return vid_input;
}
function prof_reload()
{
    // Every page load needs to write to a cookie indicating that this is
    // the current page in use on this site.
    createCookie("Page", "profile", 10);
    createCookie("ProfileTarget", userName, 10);
    if (current_section == "video")
    {
        player_loaded = false;
        load_vid_player();
    }
}
function yt_client_login(yt_u, yt_p)
{
    /*
    $.ajax({
        type: "POST",
        url: "https://www.google.com/youtube/accounts/ClientLogin",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        data: "{'Email':'" + yt_u + "'," +
               "'Passwd':'" + yt_p + "'," +
               "'service':'youtube'," +
               "'source':'ShareYourCulture'" +
        "}",
        //dataType: "json", we'll use jquery's intelligent guess for now.
        success: (function(msg)
        {
            alert(msg.d);
            //prof_preload(userName);
        }),
        error: AjaxFailed
    });
    */
}
function yt_log_submit()
{
    //alert("yt_submit");
    var yt_username = document.getElementById('ytUserField').value;
    var yt_password = document.getElementById('ytPassField').value;

    if (ytAuthorized)
        yt_client_login(yt_username, yt_password);
    else
    { 
        
    }

}
function auth_load()
{
    //var auth_obj = document.getElementById('AuthFrame');
    //alert(''+auth_obj.src);
}
function get_encoded_token_url()
{
    var loc_url = window.location.href;
    var target = "DnDSelection.aspx";
    var i = 0;
    var stripped_url = "";
    var firstSlash = false;
    for (i = (loc_url.length - 1); i >= 0; i--)
    {
        if (!firstSlash)
        {
            if (loc_url.charAt(i) == "/")
            {
                firstSlash = true;
                stripped_url = "/";
            }
        }
        else
        {
            stripped_url = "" + loc_url.charAt(i) + stripped_url;
        }
    }
    
    
    var enc_result = "";
    for (i = 0; i < stripped_url.length; i++)
    {
        if (stripped_url.charAt(i) == '/')
        {
            enc_result += "%2F";
        }
        else if (stripped_url.charAt(i) == ':')
        {
            enc_result += "%3A";
        }
        else
        {
            enc_result += stripped_url.charAt(i);
        }
    }
    return enc_result+target;
}
function auth_sub_redirect()
{
    //alert('testing');
    //alert(escape(window.location));
    var rd_page = "https://www.google.com/accounts/AuthSubRequest?" +
                     "next=" + escape(window.location) +
                     "&scope=http%3A%2F%2Fgdata.youtube.com" +
                     "&session=1" +
                     "&secure=0";
    window.location = rd_page;

}
function fix_msg(msg)
{
    var result = "";
    var i = 6;
    for (i = 6; i < (msg.length - 2); i++)
    {
        if (!((msg.charAt(i) == '\\') && (msg.charAt(i + 1) == 'n')))
            result += msg.charAt(i);
        else
        {
            result += "\n";
            i += 1;
        }
    }
    return result;
}
function build_auth_prompt(shareBody)
{
    var iHtml = "";
    iHtml += "<div class='yt_log_container'>";
    iHtml += "<div class='yt_log_title'>Youtube User Login</div><br />";
    iHtml += "In order to access your youtube videos and post them from our site," +
            " you must login to authorize ShareYourCulture to access your youtube account. " +
            "<br />Click the 'Authorize ShareYourCulture' button below if you wish to authorize.";
    iHtml += "<div class='share_link' onclick='auth_sub_redirect()'>Authorize ShareYourCulture</div>";
    iHtml += "</div>";
    $(shareBody).html(iHtml);
}
function goto_unshare_page()
{
    unshareGoto = document.getElementById('UnsharedPagingEntry');
    var val = parseInt("" + unshareGoto.value);
    if ((unshareGoto.value == "")||(val == NaN) || (val < 1) || (val > numUnsharePages))
    {
        unshareGoto.value = ""+(unshared_page+1);
        return;
    }
    var script_zone = document.getElementById('script_zone');
    $(script_zone).html(""); // clear the old feed
    unshared_page = (val - 1);
    shareFade = true;
    var share_url = "http://gdata.youtube.com/feeds/users/" + current_vidUploader +
        "/uploads?alt=json-in-script&max-results=" + max_share_entries + "&callback=unshareFeed";
    share_url += "&start-index=" + ((max_share_entries * unshared_page) + 1);

    var share_script = document.createElement('script');
    share_script.setAttribute('type', 'text/javascript');
    share_script.setAttribute('src', share_url);
    $(script_zone).append(share_script); // inject that script into the DOM.

    pageGoto();
}
function goto_share_page()
{
    
    unshareGoto = document.getElementById('SharedPagingEntry');
    var val = parseInt("" + unshareGoto.value);
    if ((unshareGoto.value == "") || (val == NaN) || (val < 1) || (val > total_share_pages))
    {
        unshareGoto.value = "" + (shared_page + 1);
        return;
    }
    shared_page = (val - 1);
    shareFade2 = true;

    pageShareGoto();
    build_shared(shared_page, share_entry_div, current_vidUploader);
}
function setup_unshare_nav()
{
    //var shareTabs = document.getElementById('SharedNumTabs');
    var unshareTabs = document.getElementById('UnsharedTabBuffer');
    // Build up to five initial tabs.
    numUnsharePages = parseInt(""+(unshareNumVids / max_share_entries)) +
                    (((unshareNumVids % max_share_entries)>0)?1:0);
    document.getElementById('UnsharedPagingTotal').innerHTML = "" + numUnsharePages;
    document.getElementById('UnsharedPagingEntry').value = '1';

    pageGoto();
}
function shareTabGoto(num)
{
    if (shareTransit)
        return; // Transition already in progress.
    
    shareFade2 = true;
    //build_shared(shared_page, share_entry_div, current_vidUploader);

    var centerPage = shared_page + 1;
    var firstTab = shareTabArray[0];
    var lastTab = shareTabArray[shareTabArray.length - 1];
    // Now we determine how much of an increase/decrease in current page
    // is incurred here.
    var diff = centerPage - num;
    var tabBuff = document.getElementById('SharedTabBuffer');
    var resHTML = "";
    var tempDiv = "";


    var curTab = document.getElementById('ShareTab' + centerPage);
    curTab.className = "share_tab_div";
    curTab.onclick = function() { shareTabGoto(centerPage) };

    var grabTab = document.getElementById('ShareTab' + num);
    grabTab.className = "share_curtab_div";
    grabTab.onclick = "";
    var tempResHtml = "";
    //alert(diff);
    
    if (diff > 0)
    {
        // going backward
        // diff tells us how many pages we must shift back.
        // We now need to see how much of that difference can come from
        // tab shifting.
        var shiftNum = firstTab - 1;
        if ((total_share_pages - centerPage) < 4)
        {
            diff -= 3 - (total_share_pages - centerPage);
        }
        //alert("total_share_pages: "+total_share_pages+" centerpage: "+centerPage);
        //alert(firstTab);
        if (diff < 0)
            diff = 0;
        if (shiftNum > diff)
        {
            shiftNum = diff; // We only need to shift the difference
        }
        // Now we want to cut the difference from the centerpage and the
        // appropriate endpoint from shiftNum


        // else we only need to shift the remaining tabs over..
        // Now we need to do the following:
        // Make a duplicate string containing the resulting innerHTML
        // Make a div containing the divs that are shifting in.
        // animate marginLeft going from shiftDiv negative to 0.
        // at completion of animation, set innerHTML to equal the result
        // to get rid of shifted out divs as well as the holder div.

        // step one, the container div. skip if no remaining shifts
        //alert(shiftNum);
        shareTabArray = new Array();
        if (shiftNum > 0)
        {

            tempDiv = "<div id='ShareTempTab' style='float: left; overflow: hidden; width: " + (shiftNum * 38) + "px; height: 25px; margin-left: -" + (shiftNum * 38) + "px'>";
            for (var i = shiftNum; i > 0; i--)
            {
                shareTabArray.push((firstTab - i));
                tempDiv += "<div id='ShareTab" + (firstTab - i) + "' class='share_tab_div' onclick='shareTabGoto(" + (firstTab - i) + ")'>" + (firstTab - i) + "</div>";
                tempResHtml += "<div id='ShareTab" + (firstTab - i) + "' class='share_tab_div' onclick='shareTabGoto(" + (firstTab - i) + ")'>" + (firstTab - i) + "</div>";
            }
            tempDiv += "</div>";
        }
        // Now build the rest of resHTML to contain the tabs that won't go out of view.
        for (var i = 0; i < (7 - shiftNum)&&((firstTab + i) <= total_share_pages); i++)
        {
            shareTabArray.push((firstTab + i));
            if ((firstTab + i) != num)
            {
                resHTML += "<div id='ShareTab" + (firstTab + i) + "' class='share_tab_div' onclick='shareTabGoto(" + (firstTab + i) + ")'>" + (firstTab + i) + "</div>";
            }
            else
            {
                resHTML += "<div id='ShareTab" + (firstTab + i) + "' class='share_curtab_div'>" + (firstTab + i) + "</div>";
            }
        }
        resHTML = tempResHtml + resHTML;
        if (shiftNum > 0)
        {
            // Switch the buffer's class for it's wide version.
            tabBuff.className = "share_tab_buffer";
            $(tabBuff).html(tempDiv + $(tabBuff).html());
            tempDiv = document.getElementById('ShareTempTab');
            shareTabTransit = true;
            $(tempDiv).animate({ marginLeft: "0" }, 450, function()
            {
                shareTabTransit = false;
                $(tabBuff).html(resHTML);
                tabBuff.className = "share_tab_buffer_norm";
            });
        }
        else
        {
            $(tabBuff).html(resHTML);
        }
        //alert(shareTabArray);

    }
    else
    {
        diff *= -1;
        var shiftNum = total_share_pages - lastTab;
        var maxTabsTemp = shareTabArray.length;
        //alert(firstTab);
        if (centerPage < 4)
        {
            diff -= 4 - centerPage;
        }
        if (shiftNum > diff)
        {
            shiftNum = diff; // We only need to shift the difference
        }
        if (shiftNum < 0)
            shiftNum = 0;
        //alert(shiftNum);
        var dupHtml = "";
        // Build duplicate html
        // Within the duplicate, we need the wrapper div around the part to hide,
        // if there is a part to hide.
        if (shiftNum > 0)
        {
            tempDiv = "<div id='ShareTempTab' style='float: left; overflow: hidden; width: " + (shiftNum * 38) + "px; height: 25px; margin-left: 0px'>";
            for (var i = 0; i < shiftNum; i++)
            {
                //unshareTabArray.push((firstTab - i));
                tempDiv += "<div id='ShareTab" + (firstTab + i) + "' class='share_tab_div' onclick='shareTabGoto(" + (firstTab + i) + ")'>" + (firstTab + i) + "</div>";
                //tempResHtml += "<div id='UnshareTab" + (firstTab + i) + "' class='share_tab_div' onclick='unshareTabGoto(" + (firstTab - i) + ")'>" + (firstTab - i) + "</div>";
            }
            tempDiv += "</div>";
            dupHtml += tempDiv;
        }
        // Add the 7 tabs to result
        var tempArr = new Array();
        for (var i = 0; i < maxTabsTemp; i++)
        {
            tempArr.push((shareTabArray[i] + shiftNum));
            if ((shareTabArray[i] + shiftNum) == num)
            {
                resHTML += "<div id='ShareTab" + (shareTabArray[i] + shiftNum) + "' class='share_curtab_div'>" + (shareTabArray[i] + shiftNum) + "</div>";
                dupHtml += "<div id='ShareTab" + (shareTabArray[i] + shiftNum) + "' class='share_curtab_div'>" + (shareTabArray[i] + shiftNum) + "</div>";
            }
            else
            {
                resHTML += "<div id='ShareTab" + (shareTabArray[i] + shiftNum) + "' class='share_tab_div' onclick='shareTabGoto(" + (shareTabArray[i] + shiftNum) + ")'>" + (shareTabArray[i] + shiftNum) + "</div>";
                dupHtml += "<div id='ShareTab" + (shareTabArray[i] + shiftNum) + "' class='share_tab_div' onclick='shareTabGoto(" + (shareTabArray[i] + shiftNum) + ")'>" + (shareTabArray[i] + shiftNum) + "</div>";
            }
        }
        shareTabArray = tempArr;
        if (shiftNum > 0)
        {
            // Switch the buffer's class for it's wide version.
            tabBuff.className = "share_tab_buffer";
            $(tabBuff).html(dupHtml);
            tempDiv = document.getElementById('ShareTempTab');
            shareTabTransit = true;
            $(tempDiv).animate({ marginLeft: "-" + (shiftNum * 38) }, 450, function()
            {
                shareTabTransit = false;
                $(tabBuff).html(resHTML);
                tabBuff.className = "share_tab_buffer_norm";
            });
        }
        else
        {
            $(tabBuff).html(resHTML);
        }
        // going forward
        // To go forward... we must make the margin left on the divs to move backwards
        // adjust to hide them on the left.  To do this, we must perform an initial
        // instantaneous duplicate replace meant on the nav bar with the following
        // difference: the divs to slide n' hide are to all be wrapped inside of
        // a wrapper div.  That wrapper div then finds its marginLeft animated to
        // negative its width.  Again we make a resulting html and then replace the
        // animated copy with the result.

    }
    shared_page = num - 1;
    build_shared(shared_page, share_entry_div, current_vidUploader);
}
function unshareTabGoto(num,stopFeedGrab)
{
    // We need to know the current tabs on screen, the current page, and the
    // number of pages that are being skipped.
    if (unshareTabTransit)
        return; // A transition is currently taking place.
    var centerPage = unshared_page + 1;
    var firstTab   = unshareTabArray[0];
    var lastTab    = unshareTabArray[unshareTabArray.length - 1];
    // Now we determine how much of an increase/decrease in current page
    // is incurred here.
    var diff    = centerPage - num;
    var tabBuff = document.getElementById('UnsharedTabBuffer');
    var resHTML = "";
    var tempDiv = "";

    
    var curTab = document.getElementById('UnshareTab' + centerPage);
    curTab.className = "share_tab_div";
    curTab.onclick = function() { unshareTabGoto(centerPage) };

    var grabTab = document.getElementById('UnshareTab' + num);
    grabTab.className = "share_curtab_div";
    grabTab.onclick = "";
    var tempResHtml = "";
    //alert(diff);
    if (diff > 0)
    {
        // going backward
        // diff tells us how many pages we must shift back.
        // We now need to see how much of that difference can come from
        // tab shifting.
        var shiftNum = firstTab - 1;
        if((numUnsharePages - centerPage) < 4)
        {
            diff -= 3 - (numUnsharePages - centerPage);
        }
        
        //alert(firstTab);
        if (shiftNum > diff)
        {
            shiftNum = diff; // We only need to shift the difference
        }
        // Now we want to cut the difference from the centerpage and the
        // appropriate endpoint from shiftNum
        
        
        // else we only need to shift the remaining tabs over..
        // Now we need to do the following:
        // Make a duplicate string containing the resulting innerHTML
        // Make a div containing the divs that are shifting in.
        // animate marginLeft going from shiftDiv negative to 0.
        // at completion of animation, set innerHTML to equal the result
        // to get rid of shifted out divs as well as the holder div.

        // step one, the container div. skip if no remaining shifts
        //alert(shiftNum);
        unshareTabArray = new Array();
        if (shiftNum > 0)
        {
            
            tempDiv = "<div id='UnshareTempTab' style='float: left; overflow: hidden; width: " + (shiftNum * 38) + "px; height: 25px; margin-left: -" + (shiftNum * 38) + "px'>";
            for (var i = shiftNum; i > 0; i--)
            {
                unshareTabArray.push((firstTab - i));
                tempDiv += "<div id='UnshareTab" + (firstTab - i) + "' class='share_tab_div' onclick='unshareTabGoto(" + (firstTab - i) + ")'>" + (firstTab - i) + "</div>";
                tempResHtml += "<div id='UnshareTab" + (firstTab - i) + "' class='share_tab_div' onclick='unshareTabGoto(" + (firstTab - i) + ")'>" + (firstTab - i) + "</div>";
            }
            tempDiv += "</div>";
        }
        // Now build the rest of resHTML to contain the tabs that won't go out of view.
        for (var i = 0; i < (7 - shiftNum); i++)
        {
            unshareTabArray.push((firstTab + i));
            if ((firstTab + i) != num)
            {
                resHTML += "<div id='UnshareTab" + (firstTab + i) + "' class='share_tab_div' onclick='unshareTabGoto(" + (firstTab + i) + ")'>" + (firstTab + i) + "</div>";
            }
            else
            {
                resHTML += "<div id='UnshareTab" + (firstTab + i) + "' class='share_curtab_div'>" + (firstTab + i) + "</div>";
            }
        }
        resHTML = tempResHtml + resHTML;
        if (shiftNum > 0)
        {
            // Switch the buffer's class for it's wide version.
            tabBuff.className = "share_tab_buffer";
            $(tabBuff).html(tempDiv + $(tabBuff).html());
            tempDiv = document.getElementById('UnshareTempTab');
            unshareTabTransit = true;
            $(tempDiv).animate({ marginLeft: "0" }, 450, function()
            {
                unshareTabTransit = false;
                $(tabBuff).html(resHTML);
                tabBuff.className = "share_tab_buffer_norm";
            });
        }
        else
        {
            $(tabBuff).html(resHTML);
        }
        //alert(unshareTabArray);
        
    }
    else
    {
        diff *= -1;
        var shiftNum = numUnsharePages - lastTab;
        var maxTabsTemp = unshareTabArray.length;
        //alert(firstTab);
        if (centerPage < 4)
        {
            diff -= 4 - centerPage;
        }
        if (shiftNum > diff)
        {
            shiftNum = diff; // We only need to shift the difference
        }
        if (shiftNum < 0)
            shiftNum = 0;
        //alert(shiftNum);
        var dupHtml = "";
        // Build duplicate html
        // Within the duplicate, we need the wrapper div around the part to hide,
        // if there is a part to hide.
        if (shiftNum > 0)
        {
            tempDiv = "<div id='UnshareTempTab' style='float: left; overflow: hidden; width: " + (shiftNum * 38) + "px; height: 25px; margin-left: 0px'>";
            for (var i = 0; i < shiftNum; i++)
            {
                //unshareTabArray.push((firstTab - i));
                tempDiv += "<div id='UnshareTab" + (firstTab + i) + "' class='share_tab_div' onclick='unshareTabGoto(" + (firstTab + i) + ")'>" + (firstTab + i) + "</div>";
                //tempResHtml += "<div id='UnshareTab" + (firstTab + i) + "' class='share_tab_div' onclick='unshareTabGoto(" + (firstTab - i) + ")'>" + (firstTab - i) + "</div>";
            }
            tempDiv += "</div>";
            dupHtml += tempDiv;
        }
        // Add the 7 tabs to result
        var tempArr = new Array();
        for (var i = 0; i < maxTabsTemp; i++)
        {
            tempArr.push((unshareTabArray[i] + shiftNum));
            if ((unshareTabArray[i] + shiftNum) == num)
            {
                resHTML += "<div id='UnshareTab" + (unshareTabArray[i] + shiftNum) + "' class='share_curtab_div'>" + (unshareTabArray[i] + shiftNum) + "</div>";
                dupHtml += "<div id='UnshareTab" + (unshareTabArray[i] + shiftNum) + "' class='share_curtab_div'>" + (unshareTabArray[i] + shiftNum) + "</div>";
            }
            else
            {
                resHTML += "<div id='UnshareTab" + (unshareTabArray[i] + shiftNum) + "' class='share_tab_div' onclick='unshareTabGoto(" + (unshareTabArray[i] + shiftNum) + ")'>" + (unshareTabArray[i] + shiftNum) + "</div>";
                dupHtml += "<div id='UnshareTab" + (unshareTabArray[i] + shiftNum) + "' class='share_tab_div' onclick='unshareTabGoto(" + (unshareTabArray[i] + shiftNum) + ")'>" + (unshareTabArray[i] + shiftNum) + "</div>";
            }
        }
        unshareTabArray = tempArr;
        if (shiftNum > 0)
        {
            // Switch the buffer's class for it's wide version.
            tabBuff.className = "share_tab_buffer";
            $(tabBuff).html(dupHtml);
            tempDiv = document.getElementById('UnshareTempTab');
            unshareTabTransit = true;
            $(tempDiv).animate({ marginLeft: "-" + (shiftNum * 38) }, 450, function()
            {
                unshareTabTransit = false;
                $(tabBuff).html(resHTML);
                tabBuff.className = "share_tab_buffer_norm";
            });
        }
        else
        {
            $(tabBuff).html(resHTML);
        }
        // going forward
        // To go forward... we must make the margin left on the divs to move backwards
        // adjust to hide them on the left.  To do this, we must perform an initial
        // instantaneous duplicate replace meant on the nav bar with the following
        // difference: the divs to slide n' hide are to all be wrapped inside of
        // a wrapper div.  That wrapper div then finds its marginLeft animated to
        // negative its width.  Again we make a resulting html and then replace the
        // animated copy with the result.

    }
    unshared_page = num - 1;
    if ((stopFeedGrab == null)||(!stopFeedGrab))
    {
        
        var script_zone = document.getElementById('script_zone');
        $(script_zone).html(""); // clear the old feed
        shareFade = true;
        var share_url = "http://gdata.youtube.com/feeds/users/" + current_vidUploader +
        "/uploads?alt=json-in-script&max-results=" + max_share_entries + "&callback=unshareFeed";
        share_url += "&start-index=" + ((max_share_entries * unshared_page) + 1);

        var share_script = document.createElement('script');
        share_script.setAttribute('type', 'text/javascript');
        share_script.setAttribute('src', share_url);
        $(script_zone).append(share_script); // inject that script into the DOM.
        pageIncrement();
    }
}
function pageGoto()
{
    document.getElementById('UnsharedPagingEntry').value = "" + (unshared_page + 1);
    // Now we build the tabs.  To do so, we make an array and we
    // first add the current page, then we backPage add, then we front page add,
    // until we have 5 tabs.  If we cannot add back, then we don't count the attempt,
    // and same goes for add front.  If add back and add front both fail, tabs are
    // finished.

    var frontFail = false;
    var backFail = false;
    
    var tabCount = 1;
    var centerPage = unshared_page + 1;
    var frontCount = 1;
    var backCount = 1;
    var tempDiv;
    var iHtml = "";
    iHtml += "<div id='UnshareTab" + centerPage+ "' class='share_curtab_div' >" + centerPage + "</div>";
    unshareTabArray = new Array();
    unshareTabArray.push(centerPage);
    while (tabCount < 7)
    {
        if (frontFail && backFail)
            break;
        if (!frontFail)
        {
            if ((centerPage + frontCount) > numUnsharePages)
            {
                frontFail = true;
            }
            else
            {

                iHtml += "<div id='UnshareTab" + (centerPage + frontCount) + "' class='share_tab_div' onclick='unshareTabGoto(" + (centerPage + frontCount) + ")'>" + (centerPage + frontCount) + "</div>";
                unshareTabArray.push((centerPage + frontCount));
                frontCount += 1;
                tabCount += 1;
                
            }
        }
        if (tabCount > 6)
            break;
        if (!backFail)
        {
            if ((centerPage - backCount) < 1)
            {
                backFail = true;
            }
            else
            {
                iHtml = "<div id='UnshareTab" + (centerPage - backCount) + "' class='share_tab_div' onclick='unshareTabGoto(" + (centerPage - backCount) + ")'>" + (centerPage - backCount) + "</div>" + iHtml;
                unshareTabArray.unshift((centerPage - backCount));
                backCount += 1;
                tabCount += 1;
                
            }
        }
    }
    var tabDiv = document.getElementById('UnsharedTabBuffer');
    tabDiv.style.display = 'none';
    $(tabDiv).html(iHtml);
    
    $(tabDiv).fadeIn(400);
}
function pageShareGoto()
{
    document.getElementById('SharedPagingEntry').value = "" + (shared_page + 1);
    // Now we build the tabs.  To do so, we make an array and we
    // first add the current page, then we backPage add, then we front page add,
    // until we have 5 tabs.  If we cannot add back, then we don't count the attempt,
    // and same goes for add front.  If add back and add front both fail, tabs are
    // finished.

    var frontFail = false;
    var backFail = false;

    var tabCount = 1;
    var centerPage = shared_page + 1;
    var frontCount = 1;
    var backCount = 1;
    var tempDiv;
    var iHtml = "";
    
    iHtml += "<div id='ShareTab" + centerPage + "' class='share_curtab_div' >" + centerPage + "</div>";
    shareTabArray = new Array();
    shareTabArray.push(centerPage);
    while (tabCount < 7)
    {
        if (frontFail && backFail)
            break;
        if (!frontFail)
        {
            if ((centerPage + frontCount) > total_share_pages)
            {
                frontFail = true;
            }
            else
            {

                iHtml += "<div id='ShareTab" + (centerPage + frontCount) + "' class='share_tab_div' onclick='shareTabGoto(" + (centerPage + frontCount) + ")'>" + (centerPage + frontCount) + "</div>";
                shareTabArray.push((centerPage + frontCount));
                frontCount += 1;
                tabCount += 1;

            }
        }
        if (tabCount > 6)
            break;
        if (!backFail)
        {
            if ((centerPage - backCount) < 1)
            {
                backFail = true;
            }
            else
            {
                iHtml = "<div id='ShareTab" + (centerPage - backCount) + "' class='share_tab_div' onclick='shareTabGoto(" + (centerPage - backCount) + ")'>" + (centerPage - backCount) + "</div>" + iHtml;
                shareTabArray.unshift((centerPage - backCount));
                backCount += 1;
                tabCount += 1;

            }
        }
    }
    var tabDiv = document.getElementById('SharedTabBuffer');
    tabDiv.style.display = 'none';
    $(tabDiv).html(iHtml);

    $(tabDiv).fadeIn(400);
}
function pageIncrement()
{
    document.getElementById('UnsharedPagingEntry').value = ""+(unshared_page+1);
}
function pageDecrement()
{
    document.getElementById('UnsharedPagingEntry').value = "" + (unshared_page+1);
}
function clean_unshare_divs()
{
    
}
function clean_share_divs()
{

}
function share_ui_shiftBack()
{
    if (shared_page <= 0)
        return;
    
    shareTabGoto(shared_page, true);
}
function share_ui_shiftNext()
{
    
    if ((shared_page + 1) >= total_share_pages)
        return;
    
    shareTabGoto(shared_page + 2, true);
}
function s_ui_shiftBack()
{
    if (unshared_page <= 0)
        return;
    var script_zone = document.getElementById('script_zone');
    $(script_zone).html(""); // clear the old feed
    unshareTabGoto(unshared_page,true);
    shareFade = true;
    var share_url = "http://gdata.youtube.com/feeds/users/" + current_vidUploader +
        "/uploads?alt=json-in-script&max-results=" + max_share_entries + "&callback=unshareFeed";
    share_url += "&start-index=" + ((max_share_entries * unshared_page) + 1);

    var share_script = document.createElement('script');
    share_script.setAttribute('type', 'text/javascript');
    share_script.setAttribute('src', share_url);
    $(script_zone).append(share_script); // inject that script into the DOM.
    pageDecrement();
}
function s_ui_shiftNext()
{
    if ((unshared_page + 1) >= numUnsharePages)
        return;
    var script_zone = document.getElementById('script_zone');
    $(script_zone).html(""); // clear the old feed
    //unshared_page += 1;
    unshareTabGoto(unshared_page + 2, true);
    shareFade = true;
    var share_url = "http://gdata.youtube.com/feeds/users/" + current_vidUploader +
        "/uploads?alt=json-in-script&max-results=" + max_share_entries + "&callback=unshareFeed";
    share_url += "&start-index=" + ((max_share_entries * unshared_page) + 1);

    var share_script = document.createElement('script');
    share_script.setAttribute('type', 'text/javascript');
    share_script.setAttribute('src', share_url);
    $(script_zone).append(share_script); // inject that script into the DOM.
    pageIncrement();
}
function share_ui_goPrev()
{
    // If we're not on the first page.
    if (shared_page > 0)
    {
        share_ui_shiftBack(); // Shift to the back buffer.
    }
}
function share_ui_goNext()
{
    
    if ((shared_page + 1) < total_share_pages)
    {
        share_ui_shiftNext();
    }
}
function s_ui_goPrev()
{
    // If we're not on the first page.
    if (unshared_page > 0)
    {
        s_ui_shiftBack(); // Shift to the back buffer.
    }
}
function s_ui_goNext()
{
    if ((max_share_entries * (unshared_page + 1)) < current_numVids)
    {
        s_ui_shiftNext();
    }
}
function s_ui_goTo(pageNumber)
{ 

}
function pull_vID(id_url)
{
    var result = "";
    for (var i = (id_url.length - 1); i >= 0;  i--)
    {
        if (id_url.charAt(i) == '/')
            break;
        result = id_url.charAt(i) + result;
    }
    return result;
}

function arrContains(value, arr)
{
    //var result = false;
    if (value == '\n')
        return false;
    for (var i = 0; i < arr.length; i++)
    {
        if (arr[i] == value)
        {
            return true;
        }
    }

    return false;
}
function checkShareCollection(value)
{
    if (value == '\n')
        return false;
    for (var i = 0; i < curShare.size(); i++)
    {
        if (curShare.S_Entry[i].VideoID == value)
        {
            return true;
        }
    }
    return false;
}
function checkUnshareCollection(value)
{
    if (value == '\n')
        return false;
    for (var i = 0; i < curUnshare.size(); i++)
    {
        if (curUnshare.S_Entry[i].VideoID == value)
        {
            return true;
        }
    }
    return false;
}
function unshareFeed(feedRoot)
{
    
    var feed = feedRoot.feed;
    var title = "";
    var unshare_id = "";
    var entries = feed.entry || [];

    // build the curUnshare ShareCollection
    var shareZone = document.getElementById('UnsharedEntries');
    $(shareZone).html("");
    $(shareZone).unbind();
    unshare_entry_div = document.createElement('div');
    unshare_entry_div.className = "shared_entries";
    pageUnshare.clear(); // Clear previous contents.
    var idList = "";
    for (var i = 0; i < entries.length; ++i)
    {
        idList += pull_vID(entries[i].id.$t)+"\n";
    }

    // Need to hit the server up for that list of disabled entries (already shared).
    $.ajax({
        type: "POST",
        url: "YT_Proxy.asmx/checkEntryStatus",
        contentType: "application/json; charset=utf-8",
        data: "{'username':'" + userName + "'," +
                "'videoIDs':'" + idList + "'" +
        "}",
        //dataType: "json", we'll use jquery's intelligent guess for now.
        success: (function(msg)
        {
            var clean_msg = fix_msg(msg);
            var msg_array = clean_msg.split('\n');
            var tempEnable = true;
            for (var i = 0; i < entries.length; ++i)
            {
                unshare_id = pull_vID(entries[i].id.$t);
                title = entries[i].title.$t;
                tempEnable = ((!((arrContains(unshare_id, msg_array)) || (checkShareCollection(unshare_id)))) || (checkUnshareCollection(unshare_id)));
                var entry = new ShareEntry(unshare_id, title, current_vidUploader, false, tempEnable);
                pageUnshare.add(entry);
                // go ahead and append this entry's div to the appropriate entry container.
                $(unshare_entry_div).append(entry.ShareTag); // appended.
                //titles += +"\n";
            }
            //alert(titles);
            if (shareFade)
            {
                unshare_entry_div.style.display = "none";
                $(shareZone).append(unshare_entry_div);
                $(shareZone).dragToSelect({ selectables: '.DnD_Select', onHide: function() { } });
                $(unshare_entry_div).fadeIn(400);
            }
            else
            {
                $(shareZone).append(unshare_entry_div);
                $(shareZone).dragToSelect({ selectables: '.DnD_Select', onHide: function() { } });
            }
            shareFade = false;
            var script_zone = document.getElementById('script_zone');
            $(script_zone).html(""); // clear that feed, we've finished with it.
        }),
        error: AjaxFailed
    });
    
    
    
    /*
    // Get the next feed only if there is a next feed.
    var startIndex = max_share_entries * (unshared_page+1);
    if (startIndex < current_numVids) // There are still videos left.
    {
        // fill the next buffer.
        var next_url = "http://gdata.youtube.com/feeds/users/" + current_vidUploader +
        "/uploads?alt=json-in-script&max-results=" + max_share_entries + "&callback=unshareNext";
        next_url += "&start-index=" + ((max_share_entries * (unshared_page + 1)) + 1);

        var share_script = document.createElement('script');
        share_script.setAttribute('type', 'text/javascript');
        share_script.setAttribute('src', next_url);
        $(script_zone).append(share_script); // inject that script into the DOM.
    }
    */
}
function subShareChanges()
{
    var result_share = new Array();
    var temp = "";
    
    //var sCnt = 0;
    for (var i = 0; i < curShare.size(); i++)
    {
        if ((i % shareBufferSize) == 0)
        {
            result_share.push(temp);
            temp = "";
            //sCnt += 1;
        }
        result_share[result_share.length - 1] += curShare.S_Entry[i].VideoID + " " + 
                          curShare.S_Entry[i].Title + "\n";
    }
    var result_unshare = new Array();
    //var uCnt = 0;
    for (var i = 0; i < curUnshare.size(); i++)
    {
        if ((i % shareBufferSize) == 0)
        {
            result_unshare.push(temp);
            temp = "";
            //uCnt += 1;
        }
        result_unshare[result_unshare.length - 1] += curUnshare.S_Entry[i].VideoID + "\n";
    }
    //alert("unshare: "+result_unshare[0]+"\n\nshare: "+result_share[0]);
    for (var i = 0; i < result_share.length; i++)
    {
        $.ajax({
            type: "POST",
            url: "YT_Proxy.asmx/addSharedVideos",
            contentType: "application/json; charset=utf-8",
            data: "{'username':'" + userName + "'," +
                "'vids':'" + result_share[i] + "'," +
                "'uploader':'"+current_vidUploader + "'" +
            "}",
            //dataType: "json", we'll use jquery's intelligent guess for now.
            success: (function(msg)
            {
                
            }),
            error: AjaxFailed
        });
    }
    for (var i = 0; i < result_unshare.length; i++)
    {
        $.ajax({
            type: "POST",
            url: "YT_Proxy.asmx/removeSharedVideos",
            contentType: "application/json; charset=utf-8",
            data: "{'username':'" + userName + "'," +
                "'vids':'" + result_unshare[i] + "'," +
                "'uploader':'" + current_vidUploader + "'" +
            "}",
            //dataType: "json", we'll use jquery's intelligent guess for now.
            success: (function(msg)
            {
                
            }),
            error: AjaxFailed
        });
    }
    total_vids_shared += curShare.size();
    curShare.clear();

    total_vids_shared -= curUnshare.size();
    curUnshare.clear();
    
    setup_share_nav();
    shared_page = 0;
    pageShareGoto();
    build_shared(1,share_entry_div,current_vidUploader);
}
function getShareEntry(vId)
{
    
    for (var i = 0; i < pageShare.size(); i++)
    {
        if (vId == pageShare.S_Entry[i].VideoID)
            return pageShare.S_Entry[i];
    }
    return null;
}
function getUnshareEntry(vId)
{
    for (var i = 0; i < pageUnshare.size(); i++)
    {
        if (vId == pageUnshare.S_Entry[i].VideoID)
            return pageUnshare.S_Entry[i];
    }
    return null;
}
function matchUnshare(vidID)
{
    //alert(vidID);
    for (var i = 0; i < curUnshare.size(); i++)
    {
        if (curUnshare.S_Entry[i].VideoID == vidID)
            return true;
    }
    return false;
}
function build_shared(un_page, unshare_tag, vidUploader)
{
    if (shareFade2)
    {
        share_entry_div.style.display = 'none';
    }

    $(share_entry_div).html("");
    
    if ((shared_page * max_share_entries) > total_vids_shared)
    {
        pageShare.clear();
        var pageField = document.getElementById('SharedPagingEntry');
        pageField.value = "" + (shared_page + 1);
        // Then we know that for this page, we just need to get entries from
        // curShare
        // To get the starting entry, we need the remainder of the
        // total currently shared vids divided by max_shared entries.
        // so if that remainder is 5, we know that starting position is...
        // 5 plus (max_share_entries * (shared_page - Math.ceil(total_vids_shared/max_share_entries)))
        var sTemp = (max_share_entries - (total_vids_shared % max_share_entries));
        if (sTemp == max_share_entries)
            sTemp = 0;
        var startPos = sTemp +
                        (max_share_entries * ((shared_page) - Math.ceil(total_vids_shared / max_share_entries)));
        var cnt = 0;
        //alert(startPos);
        var unshareZone = document.getElementById('SharedEntries');
        //alert(startPos);
        
        for(var i = startPos; (cnt < max_share_entries)&&(i < curShare.size());i++)
        {
            pageShare.add(curShare.S_Entry[i]);
            $(share_entry_div).append(curShare.S_Entry[i].ShareTag);

            $(curShare.S_Entry[i].ShareTag).multidraggable2({ helper: "clone", revert: true, start: function() { $(unshareZone).unbind(); clear_dts_artifacts(); setup_drags(getShareEntry($(this).attr('vidid')), true); drag_type = 2; },
            stop: function() { wrap_bindup(); drag_clear = false; this.style.opacity = 1.0; }
            });
            $(curShare.S_Entry[i].ShareTag).mousedown(function() { $(unshareZone).unbind();  $('.ui-multidraggable2').css('z-index', '5'); });
            $(curShare.S_Entry[i].ShareTag).mouseup(function() { wrap_bindup(true); $('.ui-multidraggable2').css('z-index', '1'); });
            
            cnt += 1;
        }
        
        
    }
    else
    {
        $.ajax({
            type: "POST",
            url: "YT_Proxy.asmx/getSharedVideos",
            contentType: "application/json; charset=utf-8",
            data: "{'username':'" + userName + "'," +
                "'page':'" + shared_page + "'" +
        "}",
            //dataType: "json", we'll use jquery's intelligent guess for now.
            success: (function(msg)
            {
                var pageField = document.getElementById('SharedPagingEntry');
                pageField.value = "" + (shared_page + 1);
                var clean_msg = fix_msg(msg);
                $(share_entry_div).html("");
                var unshareZone = document.getElementById('SharedEntries');
                pageShare.clear();
                var cnt = 0;
                // With this we want to fill up the shared section with the supplied
                // video id's.
                var msg_array = clean_msg.split('\n');
                var tempEntry = null;
                var enCheck = true;
                for (var i = 0; i < (msg_array.length - 1); i++)
                {
                    enCheck = true;
                    tempEntry = msg_array[i].split(' ');
                    var titleCon = tempEntry[1];
                    for (var j = 2; j < tempEntry.length; j++)
                    {
                        titleCon += " " + tempEntry[j];
                    }
                    if (matchUnshare(tempEntry[0]))
                        enCheck = false;
                    //alert(enCheck+" vidTitle: "+titleCon);
                    var entry = new ShareEntry(tempEntry[0], titleCon, vidUploader, true,enCheck);
                    pageShare.add(entry);
                    // go ahead and append this entry's div to the appropriate entry container.
                    $(share_entry_div).append(entry.ShareTag); // appended.
                    cnt += 1;
                }
                total_vids_shared = parseInt(msg_array[msg_array.length - 1]);

                for (var i = 0; (cnt < max_share_entries) && (i < curShare.size()); i++)
                {
                    pageShare.add(curShare.S_Entry[i]);
                    $(share_entry_div).append(curShare.S_Entry[i].ShareTag);
                    $(curShare.S_Entry[i].ShareTag).multidraggable2({ helper: "clone", revert: true, start: function() { $(unshareZone).unbind(); clear_dts_artifacts(); setup_drags(getShareEntry($(this).attr('vidid')), true); drag_type = 2; },
                        stop: function() { wrap_bindup(); drag_clear = false; this.style.opacity = 1.0; }
                    });
                    $(curShare.S_Entry[i].ShareTag).mousedown(function() { $(unshareZone).unbind(); $('.ui-multidraggable2').css('z-index', '5'); });
                    $(curShare.S_Entry[i].ShareTag).mouseup(function() { wrap_bindup(true); $('.ui-multidraggable2').css('z-index', '1'); });
                    cnt += 1;
                }
                if (!shareNavLoaded)
                {
                    shareNavLoaded = true;
                    setup_share_nav();
                    pageShareGoto();
                }
            }),
            error: AjaxFailed
        });
    }
    
    
    if (shareFade2)
    {
        $(share_entry_div).fadeIn(400);
    }
    shareFade2 = false;
}
function build_unshared(un_page, unshare_tag, vidUploader)
{
    // We know what page number, and we have the tag.  Now if
    // the page is greater than 0, then build the previous buffer.
    // Also if the page is less than maxpages-1, build the next buffer.
    // Above all else, build the current page collection first and
    // add it to the page before constructing the buffers.
    current_vidUploader = vidUploader;
    var share_url = "http://gdata.youtube.com/feeds/users/" + current_vidUploader +
        "/uploads?alt=json&max-results=" + max_share_entries;
    share_url += "&start-index=" + ((max_share_entries * unshared_page) + 1);
    curUnshare.clear();
    pageUnshare.clear();
    // build current entry section.
    // To do so we need the json for the feed. Add the feed as a script to
    // the script_zone div.
    
    full_buffer_build = true;
    /*
    $(function()
    {
        $.getJSON('http://gdata.youtube.com/feeds/users/' + current_vidUploader + '/uploads?alt=json-in-script&callback=?&max-results=' + max_share_entries+ '&start-index=' + ((max_share_entries * unshared_page) + 1), function(data)
        {
            unshareFeed(data);
        });
    });
    */
    var script_zone = document.getElementById('script_zone');
    $(script_zone).html(""); // Clear any scripts in script_zone div
    var share_url = "http://gdata.youtube.com/feeds/users/" + current_vidUploader +
        "/uploads?alt=json-in-script&max-results=" + max_share_entries + "&callback=unshareFeed";
    share_url += "&start-index=" + ((max_share_entries * unshared_page) + 1);

    var share_script = document.createElement('script');
    share_script.setAttribute('type', 'text/javascript');
    share_script.setAttribute('src', share_url);
    $(script_zone).append(share_script); // inject that script into the DOM.

    
    /*
    var share_script = document.createElement('script');
    //share_script.setAttribute('type', 'text/javascript');
    //share_script.setAttribute('src', share_url);
    share_script.type = 'text/javascript';
    share_script.src = share_url;
    document.getElementsByTagName('head')[0].appendChild(share_script); // inject that script into the DOM.
    */
    // The callback from this script injection will go to shareFeed()
    
    
}
function build_share_contents(vidUploader, numVids)
{
    // First order of business, grab the elements we'll be working with.
    var shareEntryBox = document.getElementById('SharedEntries');
    var shareTabs = document.getElementById('SharedNumTabs');
    var unshareTabs = document.getElementById('UnsharedNumTabs');

    var unshare_zone = document.getElementById('UnsharedEntries');
    $(unshare_zone).html(""); // clear what's in it.
    $(unshare_zone).append(unshare_entry_div);
    $(shareEntryBox).dragToSelect({ selectables: '.DnD_Select', onHide: function() { } }, "ui-multidraggable2");
    // Now we can begin grabbing shared video entries.  Make sure to
    // grab the total running number of shared entries from the call as well.
    // We will want to buffer the entry pages in order to ease load times as the
    // user pages through them.  However, this won't really do anything for
    // usage of the number tabs are the goto control, except when the target
    // page is the next/previous page.

    // Now we also begin querying youtube for the videos uploaded by this user.
    // we will buffer it like the other entry. So we only really need to get the
    // query for the current page, and then for the next and previous pages (if
    // there is a next/previous).
    current_numVids = numVids;
    build_unshared(unshared_page, unshare_zone, vidUploader);
    shared_page = 0;
    setup_share_nav();
    pageShareGoto();
    build_shared(shared_page,shareEntryBox, vidUploader);
    
    // Entries only need to contain video id and video title, as well as the default
    // video thumb.
}
function build_share_UI(shareBody, numVids)
{
    // Here's how it is, three divs float left.
    // the one in the middle is just to give a little
    // space in between.
    // Labels at the top, then navigation UI's for paging
    // through the entries, then the droppable entry bodies for
    // listing the entries in divs composed of thumbnail on
    // top, title on bottom.  These divs are draggable.

    var iHtml = "";
    iHtml += "<div id='ShareMain' class='share_main'>";
        iHtml += "<div id='ShareUI_Title' class='share_ui_title'>My Youtube Videos</div>";
        iHtml += "<div class='share_ui_description'>Drag and drop your videos into either " +
                    "the \"Shared\" or \"Not Shared\" boxes to decide which of them will be " +
                    "viewable on your Share Your Culture profile. You may select multiple videos" +
                    " at once by holding ctrl while clicking on the videos, or you can click and " +
                    " drag the mouse to create a selection box over the thumbs you want to select. " +
                    "<br /><br /></div>";
        iHtml += "<div class='share_prompt'>When you are done making changes, click the \"Submit Changes\" button.</div>";
        // For now I'll put a submit changes button at the top, and at the bottom.
        iHtml += "<div class='share_ui_subcon'><div class='share_ui_submit' onclick='subShareChanges()'>Submit Changes</div></div>";
        iHtml += "<div id='SharedContainer' class='share_ui_container'>";
            iHtml += "<div class='share_title'>Shared</div>";
            // Need to make a decision about the appearance of the entry paging ui.
            // I suppose the basic arrows buttons for going left and right between
            // entries would be good, but what about fast navigation... like if I
            // wanted to go to page 93, and I'm only on page 1 at the moment.  I'd
            // normally have to click through a heck of a lot of pages.  So...maybe
            // the UI can look like this:  |<| |1| 2 3 4 5 goto |input|/total |>|
            // Since the orderby default is reverse chronological order of publishing,
            // users will see their latest video uploads first.  Unfortunately, the
            // orderby title is only available to youtube playlist feeds, which can
            // be filled with videos other than the ones the user has uploaded personally.
            // For this reason, providing a solution for additional sorting options will
            // have to be put off till later. However, ordering by viewCount and rating
            // is provided.
            iHtml += "<div id='SharedPager' class='share_pager'>";
                iHtml += "<div class='share_page_arrow' onclick='share_ui_goPrev()'>&lt;</div>";
                iHtml += "<div id='SharedNumTabs' class='share_tab_container'><div id='SharedTabBuffer' class='share_tab_buffer_norm'></div></div>";
                iHtml += "<div id='SharedGotoContainer' class='shared_goto_container'>";
                    iHtml += "&nbsp;Go To <input id='SharedPagingEntry' class='share_page_field' type='text' />";
                    iHtml += " / <span id='SharedPagingTotal'></span>";
                iHtml += "</div>";
                iHtml += "<div class='share_page_arrowR' onclick='share_ui_goNext()'>&gt;</div>";
            iHtml += "</div>";
            iHtml += "<div id='SharedEntries' class='share_entries'></div>";
        iHtml += "</div>";
        iHtml += "<div id='ShareGap' class='share_ui_gap'></div>";
        iHtml += "<div id='UnsharedContainer' class='share_ui_container'>";
            iHtml += "<div class='share_title'>Not Shared</div>";
            iHtml += "<div id='SharedPager' class='share_pager'>";
                iHtml += "<div class='share_page_arrow' onclick='s_ui_goPrev()'>&lt;</div>";
                iHtml += "<div id='UnsharedNumTabs' class='share_tab_container'><div id='UnsharedTabBuffer' class='share_tab_buffer_norm'></div></div>";
                iHtml += "<div id='UnsharedGotoContainer' class='shared_goto_container'>";
                    iHtml += "&nbsp;Go To <input id='UnsharedPagingEntry' class='share_page_field' type='text' />";
                    iHtml += " / <span id='UnsharedPagingTotal'></span>";
                iHtml += "</div>";
                iHtml += "<div class='share_page_arrowR' onclick='s_ui_goNext()'>&gt;</div>";
            iHtml += "</div>";
            iHtml += "<div id='UnsharedEntries' class='share_entries'></div>";
        iHtml += "</div>";
    // Perhaps in a footer-like section of this UI, we'll place a
    // direct upload option to youtube.

    iHtml += "</div>";
    // apply the markup.
    $(shareBody).html(iHtml);
    document.getElementById('SharedEntries').appendChild(share_entry_div);
}
function clear_prev_drag()
{

}
function setup_share_nav()
{
    // We need total number of pages.
    total_share_pages = Math.ceil((total_vids_shared + curShare.size()) / max_share_entries);
    var totalDiv = document.getElementById('SharedPagingTotal');
    totalDiv.innerHTML = "" + total_share_pages;
    
}
function shareChild(entry, added)
{
    // Ok, we need to see if we're on the last page.
    // we also need to know total number of entries currently shared,
    // plus total number of entries moved to shared already.
    var fullTotal = total_vids_shared + curShare.size(); // full total.
    // Now we need to update the share navigation if the current number
    // of pages is changed.
    //alert("fullTotal: " + fullTotal + " total_share_pages: " + total_share_pages + " divisor: " + Math.floor(fullTotal / max_share_entries));
    if (!(Math.ceil(fullTotal / max_share_entries) == total_share_pages))
    {
        // Rebuild navigation
        setup_share_nav();
        // Load the new last page
        shared_page = total_share_pages - 1;
        pageShareGoto();
        build_shared(shared_page, share_entry_div, current_vidUploader);
        
    }
    else
    {
        
        // We just need to append to the current page.
        if (total_share_pages == (shared_page + 1))
        {
            var unshareZone = document.getElementById('SharedEntries');
            if (added)
            {
                $(share_entry_div).append(entry.ShareTag);
                $(entry.ShareTag).multidraggable2({ helper: "clone", revert: true, start: function() { $(unshareZone).unbind(); clear_dts_artifacts(); setup_drags(entry, true); drag_type = 2; },
                    stop: function() { wrap_bindup(); drag_clear = false; entry.ShareTag.style.opacity = 1.0; }
                });
                $(entry.ShareTag).mousedown(function() { $(unshareZone).unbind(); entry.ShareTag.style.zIndex = 5; $('.ui-multidraggable2').css('z-index', '5'); });
                $(entry.ShareTag).mouseup(function() { wrap_bindup(true); entry.ShareTag.style.zIndex = 5; $('.ui-multidraggable2').css('z-index', '1'); });
            }
            else // replace current matching one if it's on this page.
            {
                var shareChilds = share_entry_div.childNodes;
                for (var i = 0; i < shareChilds.length; i++)
                {
                    if (shareChilds[i].getAttribute('vidid') == entry.VideoID)
                    {
                        //alert(pageShare.S_Entry[i].ShareTag.parentNode.nodeType);
                        $(shareChilds[i]).replaceWith(entry.ShareTag);
                        //pageShare.S_Entry[i] = entry;
                        $(entry.ShareTag).multidraggable2({ helper: "clone", revert: true, start: function() { $(unshareZone).unbind(); clear_dts_artifacts(); setup_drags(entry, true); drag_type = 2; },
                            stop: function() { wrap_bindup(); drag_clear = false; entry.ShareTag.style.opacity = 1.0; }
                        });
                        $(entry.ShareTag).mousedown(function() { $(unshareZone).unbind(); entry.ShareTag.style.zIndex = 5; $('.ui-multidraggable2').css('z-index', '5'); });
                        $(entry.ShareTag).mouseup(function() { wrap_bindup(true); entry.ShareTag.style.zIndex = 5; $('.ui-multidraggable2').css('z-index', '1'); });
                        break;
                    }
                }
            }
        }
        else
        {
            // Otherwise, you'll probably want to swing on over
            // to that page.
            shared_page = total_share_pages - 1;
            pageShareGoto();
            build_shared(shared_page, share_entry_div, current_vidUploader);
        }
    }
    
}
function unshareChild(entry, removed)
{
    //alert(entry.Title);
    // Ok, we need to see if we're on the last page.
    // we also need to know total number of entries currently shared,
    // plus total number of entries moved to shared already.
    var fullTotal = total_vids_shared + curShare.size(); // full total.
    // Now we need to update the share navigation if the current number
    // of pages is changed.
    //alert("fullTotal: " + fullTotal + " total_share_pages: " + total_share_pages + " divisor: " + Math.floor(fullTotal / max_share_entries));
    if (!(Math.ceil(fullTotal / max_share_entries) == total_share_pages))
    {
        // Rebuild navigation
        setup_share_nav();
        // Load the new last page
        shared_page = total_share_pages - 1;
        pageShareGoto();
        build_shared(shared_page, share_entry_div, current_vidUploader);

    }
    else
    {

        // We just need to remove from the current page.
        if (!removed)
            $(entry.ShareTag).remove();
        else
        {
            var cloneEm = cloneShareEntry(entry, true, false);
            //alert(cloneEm.Title);
            $(entry.ShareTag).replaceWith(cloneEm.ShareTag);
        }
    }
}
function build_drop_zones()
{
    $('#SharedEntries').droppable({
        drop: function(event, ui)
        {
            if (!drop_clear)
            {
                if (drag_type == 2)
                    return;
                // Remove all the selected objects from UnsharedEntries
                $('.ui-draggable-dragging').css("display", "none"); // kill stray clones.
                var tempClone;
                var unshareZone = document.getElementById('SharedEntries');
                var tempCheck = false;
                var tempGrab;
                var remBool = false;
                for (var i = 0; i < unshare_drag_array.length; i++)
                {
                    tempGrab = unshare_drag_array[i];
                    tempCheck = false;
                    remBool = false;
                    //unshare_entry_div.removeChild(unshare_drag_array[i].ShareTag);
                    //$(unshare_drag_array[i].ShareTag).multidraggable("destroy");
                    $(unshare_drag_array[i].ShareTag).removeClass("ui-multidraggable ui-draggable");

                    var tempClone = cloneShareEntry(unshare_drag_array[i], true);
                    var repClone = cloneShareEntry(unshare_drag_array[i], false, false);
                    tempGrab.ShareTag.parentNode.replaceChild(repClone.ShareTag, unshare_drag_array[i].ShareTag);

                    for (var j = 0; j < pageUnshare.size(); j++)
                    {
                        if (pageUnshare.S_Entry[j].VideoID == repClone.VideoID)
                        {
                            pageUnshare.S_Entry[j] = repClone;
                            //alert("replaced "+j);
                            break;
                        }
                    }

                    //$(tempClone).multidraggable("destroy");
                    //$(tempClone).removeClass("ui-multidraggable ui-draggable");
                    tempClone.ShareTag.style.opacity = 1.0;
                    // We're switching from unshared to shared.
                    // first check if it's in the collection for unshared already if it is,
                    // remove from there. Else add it to the other collection
                    for (var j = 0; j < curUnshare.size(); j++)
                    {
                        if (curUnshare.S_Entry[j].VideoID == tempClone.VideoID)
                        {
                            curUnshare.S_Entry.splice(j, 1); // remove
                            tempCheck = true;
                            break;
                        }
                    }
                    if (!tempCheck)
                    {
                        curShare.add(tempClone);
                        remBool = true;
                    }
                    // We need to recalculate whether we're on the end page, or if we need
                    // to increment the number of pages and move up a page.
                    shareChild(tempClone, remBool);
                }
                clearArray(unshare_drag_array);
                //alert(curShare.size());
                $(unshareZone).dragToSelect({ selectables: '.DnD_Select', onHide: function() { } }, "ui-multidraggable2");
                drop_clear = true;
            }

        },
        over: function(event, ui)
        {

        },
        out: function(event, ui)
        {

        }
    });
    $('#UnsharedEntries').droppable({
        drop: function(event, ui)
        {
            if (!drop_clear)
            {
                if (drag_type == 1)
                    return;
                // Remove all the selected objects from UnsharedEntries
                $('.ui-draggable-dragging').css("display", "none"); // invisify stray clones.
                var tempClone;
                var unshareZone = document.getElementById('UnsharedEntries');
                var tempCheck = false;
                var cloneCheck = false;
                var tempGrab;
                var childArr;
                var remBool = false;
                for (var i = 0; i < share_drag_array.length; i++)
                {
                    remBool = false;
                    tempGrab = share_drag_array[i];
                    cloneCheck = false;
                    tempCheck = false;
                    //unshare_entry_div.removeChild(unshare_drag_array[i].ShareTag);
                    //$(share_drag_array[i].ShareTag).multidraggable("destroy");
                    $(share_drag_array[i].ShareTag).removeClass("ui-multidraggable2 ui-draggable");


                    //var tempClone = cloneShareEntry(share_drag_array[i]);
                    var repClone = cloneShareEntry(share_drag_array[i], false, true);
                    //share_drag_array[i].ShareTag.parentNode.removeChild(unshare_drag_array[i].ShareTag);
                    childArr = unshare_entry_div.childNodes;
                    for (var j = 0; j < childArr.length; j++)
                    {
                        //alert("child: " + childArr[j].attributes.getNamedItem('vidid').value + " clone: " + repClone.VideoID);
                        if (childArr[j].attributes.getNamedItem('vidid').value == repClone.VideoID)
                        {
                            //unshare_entry_div.replaceChild(repClone.ShareTag, pageUnshare.S_Entry[j].ShareTag);
                            unshare_entry_div.replaceChild(repClone.ShareTag, childArr[j]);
                            cloneCheck = true;
                            break;
                        }
                    }

                    //$(tempClone).multidraggable("destroy");
                    //$(tempClone).removeClass("ui-multidraggable ui-draggable");
                    if (cloneCheck) // gear it up, it's been put into place.
                    {
                        repClone.ShareTag.style.opacity = 1.0;
                        $(repClone.ShareTag).multidraggable({ helper: "clone", revert: true, start: function() { $(shareZone).unbind(); clear_dts_artifacts(); setup_drags(repClone); drag_type = 1; },
                            stop: function() { wrap_bindup(); drag_clear = false; s_entry_div.style.opacity = 1.0; }
                        });
                        $(repClone.ShareTag).mousedown(function() { $(unshareZone).unbind(); repClone.ShareTag.style.zIndex = 5; $('.ui-multidraggable').css('z-index', '5'); });
                        $(repClone.ShareTag).mouseup(function() { wrap_bindup(); repClone.ShareTag.style.zIndex = 1; $('.ui-multidraggable').css('z-index', '1'); });
                    }
                    // We're switching from unshared to shared.
                    // first check if it's in the collection for unshared already if it is,
                    // remove from there. Else add it to the other collection
                    for (var j = 0; j < curShare.size(); j++)
                    {
                        if (curShare.S_Entry[j].VideoID == repClone.VideoID)
                        {
                            curShare.S_Entry.splice(j, 1); // remove
                            tempCheck = true;
                            break;
                        }
                    }
                    if (!tempCheck)
                    {
                        curUnshare.add(repClone);
                        remBool = true;
                    }

                    //alert("drag point: " + i + " drag Length: " + share_drag_array.length);
                    unshareChild(tempGrab, remBool);

                }
                /*
                var shareChilds = share_entry_div.childNodes;
                for (var i = 0; i < shareChilds.length; i++)
                {
                if ($(shareChilds[i]).hasClass('ui-draggable-dragging'))
                {
                share_entry_div.removeChild(shareChilds[i]);
                }
                }
                */
                clearArray(unshare_drag_array);
                //alert(curShare.size());
                //$(unshareZone).dragToSelect({ selectables: '.DnD_Select', onHide: function() { } }, "ui-multidraggable2");
                var zoneZone = document.getElementById('SharedEntries');
                $(zoneZone).dragToSelect({ selectables: '.DnD_Select', onHide: function() { } }, "ui-multidraggable2");
                drop_clear = true;
            }

        },
        over: function(event, ui)
        {

        },
        out: function(event, ui)
        {

        }
    });
}
function bring_back_header()
{
    var left_col = document.getElementById('prof_left_col');
    var right_col = document.getElementById('prof_right_col');
    var prof_head = document.getElementById('prof_head');
    left_col.style.display = "block";
    right_col.style.display = "block";
    prof_head.style.display = "block";
    
    var prof_main = document.getElementById('prof_main_content');
    prof_main.className = "prof_main_normal";
    
    var prof_divider = document.getElementById('ProfDivider');
    prof_divider.style.display = 'block';
}
function clear_out_header()
{
    var left_col = document.getElementById('prof_left_col');
    var right_col = document.getElementById('prof_right_col');
    var prof_head = document.getElementById('prof_head');
    left_col.style.display = "none";
    right_col.style.display = "none";
    prof_head.style.display = "none";

    var prof_main = document.getElementById('prof_main_content');
    prof_main.className = "prof_main_full";

    var prof_divider = document.getElementById('ProfDivider');
    prof_divider.style.display = 'none';
}
function build_video_share()
{
    var shareBody = document.getElementById('video_share_body');
    // Check to see if user's youtube account is authorized for use on our site.
    //alert(userName);

    $.ajax({
        type: "POST",
        url: "YT_Proxy.asmx/getUserVideos",
        contentType: "application/json; charset=utf-8",
        data: "{'username':'" + userName + "'" +
        "}",
        //dataType: "json", we'll use jquery's intelligent guess for now.
        success: (function(msg)
        {
            //var str = msg.d; //""+msg.hasOwnProperty('d');
            //alert(msg.d); //fix_msg(msg));
            //prof_preload(userName);
            //alert(msg.charAt(0));
            curShare.clear();
            curUnshare.clear();
            var clean_msg = fix_msg(msg);
            if (clean_msg == "NULL_AUTH")
            {
                // we're going to want to now build the youtube authorization
                // prompt so the user can authorize the site to access their
                // youtube account for them.
                build_auth_prompt(shareBody);
                return;
            }
            var msg_split = clean_msg.split('&');
            unshareNumVids = parseInt(msg_split[0]);
            var vidUploader = msg_split[1];

            // Clear out the columns and status section!
            clear_out_header();
            // Now we want to build the sharing UI;
            build_share_UI(shareBody, unshareNumVids);

            build_drop_zones();
            // The basic structure of the UI is there, now
            // begin placing the unshared videos in the unshared section, and
            // also begin placing the shared videos in the shared section.



            build_share_contents(vidUploader, unshareNumVids);
            setup_unshare_nav(); // this sets up the nav ui for the unshared section
            
        }),
        error: AjaxFailed
    });
    
    
    if (true)
        return;
    if (!ytLoggedIn)
    {
        // Build youtube log in fields.
        
        
        //alert(get_encoded_token_url());
    }
    else
    { 
        
    }
    
}
function convert_apostraphes(str)
{
    var result = "";
    var i = 0;
    for (i = 0; i < str.length; i++)
    {
        if (str.charAt(i) == "'")
        {
            result += "&#39;";
        }
        else
        {
            result += str.charAt(i);
        }
    }

    return result;
}

