﻿var hub10_favoriteTermGuid = '55aa181b-5b23-4db8-8bb6-8ffa31e23562';

var hub10_xmlhttpItems = null;

// SOAP prefix declarations
var hub10_Office_SoapPrefix = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:soap1="http://schemas.microsoft.com/sharepoint/soap/"><soap:Body>';
var hub10_Social_SoapPrefix = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:soc="http://microsoft.com/webservices/SharePointPortalServer/SocialDataService"><soap:Body>';

// Standard SOAP postfix 
var hub10_SoapPostfix = '</soap:Body></soap:Envelope>';

this.hub2010_currentUser = null;
this.hub2010_domElement = null;
this.hub2010_favoritesXml = null;
this.hub10_VDIR = null;

// generic helper to perform sync calls to UpdateListItems web service
function hub10_UpdateListItemsOfficeServiceCall(soapbatch) {
    if (!hub10_xmlhttpItems) hub10_xmlhttpItems = hub10_GetHTTPObject();
	
    // perform the call synchronously
    hub10_xmlhttpItems.open("POST", hub10_VDIR + "/_vti_bin/Lists.asmx?op=UpdateListItems", false);

    hub10_xmlhttpItems.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    hub10_xmlhttpItems.setRequestHeader("Content-Length", soapbatch.length);
    hub10_xmlhttpItems.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");

    hub10_xmlhttpItems.send(soapbatch);

    var bError = false;

    if (hub10_xmlhttpItems.readyState != 4) return null;
    var errornodes = [];
    var xmlDocObj = hub10_GetSoapResponseXml(hub10_xmlhttpItems);

    //check for either an errorstring or faultstring
    errornodes = xmlDocObj.getElementsByTagName("errorstring");
    if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
        alert("Unable to update :\n" + errornodes[0].firstChild.nodeValue);
        bError = true;
    }
    else {
        errornodes = xmlDocObj.getElementsByTagName("faultstring");
        if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
            alert("Sorry, we were unable to update the list :\n" + errornodes[0].firstChild.nodeValue);
            bError = true;
        }
    }

    // If there was a problem updating the item we will get an ErrorText
    errornodes = xmlDocObj.getElementsByTagName("ErrorText");
    if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
        alert("Update failed due to bad list URI or missing list columns :\n" + errornodes[0].firstChild.nodeValue);		
        bError = true;
    }

    return;


}


// generic helper to perform sync calls to Social Data web service
function hub10_UpdateSocialDataServiceCall(soapbatch, postUrl, action) {

    if (!hub10_xmlhttpItems) hub10_xmlhttpItems = hub10_GetHTTPObject();

    // perform the call synchronously
    hub10_xmlhttpItems.open("POST", postUrl, false);

    hub10_xmlhttpItems.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    hub10_xmlhttpItems.setRequestHeader("Content-Length", soapbatch.length);
    hub10_xmlhttpItems.setRequestHeader("SOAPAction", action);

    hub10_xmlhttpItems.send(soapbatch);

    var bError = false;

    if (hub10_xmlhttpItems.readyState != 4) return null;
    var errornodes = [];
    var xmlDocObj = hub10_GetSoapResponseXml(hub10_xmlhttpItems);

    //check for either an errorstring or faultstring
    errornodes = xmlDocObj.getElementsByTagName("errorstring");
    if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
        alert("Unable to update :\n" + errornodes[0].firstChild.nodeValue);
        bError = true;
    }
    else {
        errornodes = xmlDocObj.getElementsByTagName("faultstring");
        if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
            alert("Sorry, we were unable to update the list :\n" + errornodes[0].firstChild.nodeValue);
            bError = true;
        }
    }

    // If there was a problem updating the item we will get an ErrorText
    errornodes = xmlDocObj.getElementsByTagName("ErrorText");
    if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
        alert("Update failed due to bad list URI or missing list");		
        bError = true;
    }

    return;


}

// Given a Social Data Service XML blog, 
// transform it on the client using the socialDataService.xsl 
// and render the results to the given Html element
function hub10_RenderFavoritesSocialDataXmlAsHtml(sdsFavoritesXmlDocObj, htmlDomElement)
{
	// Get the XSLT from the server.
	if (!hub10_xmlhttpItems) hub10_xmlhttpItems = hub10_GetHTTPObject();

	var xslUrl = hub10_VDIR + '/supportFiles/socialDataService.xsl';

    // perform the call synchronously
    hub10_xmlhttpItems.open("GET", xslUrl, false);
    hub10_xmlhttpItems.send();
    if (hub10_xmlhttpItems.readyState != 4) return null;
	var xslDocObj = hub10_GetSoapResponseXml(hub10_xmlhttpItems);

    if (typeof XSLTProcessor != "undefined") 
    {
        var xslProc = new XSLTProcessor ();
        xslProc.importStylesheet(xslDocObj);
        var node = xslProc.transformToDocument(sdsFavoritesXmlDocObj);
        htmlDomElement.innerHTML = "";
        htmlDomElement.appendChild(node);
    }
    else if (typeof sdsFavoritesXmlDocObj.transformNode != "undefined") 
    {
        htmlDomElement.innerHTML = sdsFavoritesXmlDocObj.transformNode(xslDocObj);
    }
    else 
    {
        htmlDomElement.innerHTML = "Favorites can not be rendered in this browser.";
    }
}


function hub10_GetSocialDataServiceCall(soapbatch, postUrl, action) {

    if (!hub10_xmlhttpItems) hub10_xmlhttpItems = hub10_GetHTTPObject();

    // perform the call synchronously
    hub10_xmlhttpItems.open("POST", postUrl, false);

    hub10_xmlhttpItems.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    hub10_xmlhttpItems.setRequestHeader("Content-Length", soapbatch.length);
    hub10_xmlhttpItems.setRequestHeader("SOAPAction", action);

    hub10_xmlhttpItems.send(soapbatch);

    var bError = false;

    if (hub10_xmlhttpItems.readyState != 4) return null;
    var errornodes = [];
    
    var xmlDocObj = hub10_GetSoapResponseXml(hub10_xmlhttpItems);

    //check for either an errorstring or faultstring
    errornodes = xmlDocObj.getElementsByTagName("errorstring");
    if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
        //alert("Unable to update :\n" + errornodes[0].firstChild.nodeValue);		
        bError = true;
    }
    else {
        errornodes = xmlDocObj.getElementsByTagName("faultstring");
        if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
            //alert("Sorry, we were unable to update the list :\n" + errornodes[0].firstChild.nodeValue);		
            bError = true;
        }
    }

    // If there was a problem updating the item we will get an ErrorText
    errornodes = xmlDocObj.getElementsByTagName("ErrorText");
    if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
        alert("Update failed due to bad list URI or missing list columns :\n" + errornodes[0].firstChild.nodeValue);		
        bError = true;
    }

    if (!bError) {
        return xmlDocObj;
    }

    return "";

}

// Given a query, return the value of a specific list item field that matches that soapbatch query
function hub10_GetListItemOfficeServiceCall(soapbatch, rowAttribute) {

    if (!hub10_xmlhttpItems) hub10_xmlhttpItems = hub10_GetHTTPObject();
    // perform the call synchronously
    hub10_xmlhttpItems.open("POST", hub10_VDIR + "/_vti_bin/Lists.asmx?op=GetListItems", false);

    hub10_xmlhttpItems.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    hub10_xmlhttpItems.setRequestHeader("Content-Length", soapbatch.length);
    hub10_xmlhttpItems.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetListItems");

    hub10_xmlhttpItems.send(soapbatch);

    var bError = false;

    if (hub10_xmlhttpItems.readyState != 4) return null;
    var errornodes = [];
    var xmlDocObj = hub10_GetSoapResponseXml(hub10_xmlhttpItems);

    //check for either an errorstring or faultstring
    errornodes = xmlDocObj.getElementsByTagName("errorstring");
    if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
        //alert("Unable to update :\n" + errornodes[0].firstChild.nodeValue);		
        bError = true;
    }
    else {
        errornodes = xmlDocObj.getElementsByTagName("faultstring");
        if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
            //alert("Sorry, we were unable to update the list :\n" + errornodes[0].firstChild.nodeValue);		
            bError = true;
        }
    }

    // If there was a problem updating the item we will get an ErrorText
    errornodes = xmlDocObj.getElementsByTagName("ErrorText");
    if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
        alert("Update failed due to bad list URI or missing list columns :\n" + errornodes[0].firstChild.nodeValue);		
        bError = true;
    }


    if (!bError) {

        var val = "0";

        if (window.addEventListener) {
            if ((xmlDocObj.getElementsByTagName("rs:data")[0].attributes["ItemCount"].value) > "0") {
				var nodez = xmlDocObj.getElementsByTagName("z:row")[0].attributes[rowAttribute];
                if (nodez) {val = nodez.value;}
                
            }
        }
        else {
            if ((xmlDocObj.selectSingleNode(".//rs:data/@ItemCount").value) > "0") {
            	var nodez = xmlDocObj.selectSingleNode(".//z:row/@" + rowAttribute);
                if(nodez) {val = nodez.value;}
            }
        }


        return val;

    }

    return "";

}

// Add a tag to the tag store for the GetItDone item ID
function hub10_AddSectionFavorite(itemID) 
{
    var listName = 'Get It Done';
    var physicalListName = 'GetItDone';
    var soapbatch;
    var owsxml;

    // using just the document's Item ID, query the library for the docTitle and docUrl
    owsxml = "<Where>";
    owsxml += "<Eq><FieldRef Name='ID'/><Value Type='Integer'>" + itemID + "</Value></Eq>";
    owsxml += "</Where>";

    soapbatch = hub10_Office_SoapPrefix;
    soapbatch += '<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">';
    soapbatch += '<listName>' + listName + '</listName>';
    soapbatch += '<query><Query>' + owsxml + '</Query></query>';
    soapbatch += '<viewFields><ViewFields><FieldRef Name="FileRef" /><FieldRef Name="Title" /></ViewFields></viewFields>';
    soapbatch += '<queryOptions><QueryOptions><IncludeMandatoryColumns>TRUE</IncludeMandatoryColumns></QueryOptions></queryOptions></GetListItems>';
    soapbatch += hub10_SoapPostfix;

    var documentTitle = hub10_GetListItemOfficeServiceCall(soapbatch, "ows_Title");
    var fileName = hub10_GetListItemOfficeServiceCall(soapbatch, "ows_FileLeafRef");
    var fileNameStrArr = fileName.split(";#"); // not "49;#Filename.doc", just "Filename.doc"
    var docUrl = hub10_VDIR + "/" + physicalListName + "/" + fileNameStrArr[1] ;

    // using the obtained title and URL set the tag

    if (docUrl != null && documentTitle != null) {
        soapbatch = hub10_Social_SoapPrefix;
        soapbatch += '<soc:AddTag>';
        soapbatch += '<soc:url>' + docUrl + '</soc:url><soc:termID>{' + hub10_favoriteTermGuid + '}</soc:termID>';
        soapbatch += '<soc:title>' + documentTitle + '</soc:title><soc:isPrivate>false</soc:isPrivate>';
        soapbatch += '</soc:AddTag>';
        soapbatch += hub10_SoapPostfix;

        var postUrl = hub10_VDIR + '/_vti_bin/SocialDataService.asmx?op=AddTag';
        var action = 'http://microsoft.com/webservices/SharePointPortalServer/SocialDataService/AddTag';
        hub10_UpdateSocialDataServiceCall(soapbatch, postUrl, action);
        alert("The item has been tagged as one of your Hub Favorites");
    }

    return;

}



// Add a tag to the tag store for the Content Library item ID
function hub10_AddFavorite(itemID) 
{
    var listName = 'Content Library';
    var physicalListName = 'ContentLibrary';
    var soapbatch;
    var owsxml;

    // using just the document's Item ID, query the library for the docTitle and docUrl
    owsxml = "<Where>";
    owsxml += "<Eq><FieldRef Name='ID'/><Value Type='Integer'>" + itemID + "</Value></Eq>";
    owsxml += "</Where>";

    soapbatch = hub10_Office_SoapPrefix;
    soapbatch += '<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">';
    soapbatch += '<listName>' + listName + '</listName>';
    soapbatch += '<query><Query>' + owsxml + '</Query></query>';
    soapbatch += '<viewFields><ViewFields><FieldRef Name="FileRef" /><FieldRef Name="Title" /></ViewFields></viewFields>';
    soapbatch += '<queryOptions><QueryOptions><IncludeMandatoryColumns>TRUE</IncludeMandatoryColumns></QueryOptions></queryOptions></GetListItems>';
    soapbatch += hub10_SoapPostfix;

    var documentTitle = hub10_GetListItemOfficeServiceCall(soapbatch, "ows_Title");
    var fileName = hub10_GetListItemOfficeServiceCall(soapbatch, "ows_FileLeafRef");
    var fileNameStrArr = fileName.split(";#"); // not "49;#Filename.doc", just "Filename.doc"
    var docUrl = hub10_VDIR + "/" + physicalListName + "/" + fileNameStrArr[1] ;

    // using the obtained title and URL set the tag

    if (docUrl != null && documentTitle != null) {
        soapbatch = hub10_Social_SoapPrefix;
        soapbatch += '<soc:AddTag>';
        soapbatch += '<soc:url>' + docUrl + '</soc:url><soc:termID>{' + hub10_favoriteTermGuid + '}</soc:termID>';
        soapbatch += '<soc:title>' + documentTitle + '</soc:title><soc:isPrivate>false</soc:isPrivate>';
        soapbatch += '</soc:AddTag>';
        soapbatch += hub10_SoapPostfix;

        var postUrl = hub10_VDIR + '/_vti_bin/SocialDataService.asmx?op=AddTag';
        var action = 'http://microsoft.com/webservices/SharePointPortalServer/SocialDataService/AddTag';
        hub10_UpdateSocialDataServiceCall(soapbatch, postUrl, action);
        alert("The item has been tagged as one of your Hub Favorites");
    }

    return;

}

// Relies on 2010's ECMA client context referenced in _layouts/sp.js
function hub2010_LoadVdirUrl() 
{
	try 
	{
		if (this.hub10_VDIR == null) 
		{
			var clientContext = new SP.ClientContext.get_current();
			
			this.csite = clientContext.get_site();
			clientContext.load(csite);
			clientContext.executeQueryAsync(
				Function.createDelegate(this, this.hub2010_onUrlQuerySucceeded), Function.createDelegate(this, this.hub2010_onUrlQueryFailed)
			);
		}
	}
	catch(e)
	{
		alert("Exception on load" + e.message);
	}
	
}

function hub2010_onUrlQuerySucceeded(sender, args) 
{
		this.hub10_VDIR = this.csite.get_url();
}

function hub2010_onUrlQueryFailed(sender, args) 
{
	alert("url query failed");
}


// Relies on 2010's ECMA client context referenced in _layouts/sp.js
function hub2010_loadCurrentUserInfo(domElement) 
{
	try 
	{
		var clientContext = new SP.ClientContext.get_current();
		var web = clientContext.get_web();
		this.hub2010_currentUser = web.get_currentUser();
		this.hub2010_domElement = domElement;
		clientContext.load(hub2010_currentUser);
		clientContext.executeQueryAsync(
			Function.createDelegate(this, this.hub2010_onUserQuerySucceeded), Function.createDelegate(this, this.hub2010_onUserQueryFailed)
		);
	}
	catch(e)
	{
		alert(e);
	}
	
}

// Given a userid, fetch their 'keywords' from the SDS web service 
// and render the transformed Html to the given dom Element
function hub10_DisplayFavorites(domElement) 
{
	// Load current user information
	hub2010_loadCurrentUserInfo(domElement);
    return;

}


function hub2010_FetchFavoritesXmlForSilverlight(hub10_currentUserId) 
{
	var retVal = "";
	
	if (hub10_currentUserId)
	{
        soapbatch = hub10_Social_SoapPrefix;
        soapbatch += '<soc:GetTagsOfUser>';
        soapbatch += '<soc:userAccountName>' + hub10_currentUserId + '</soc:userAccountName><soc:maximumItemsToReturn>999</soc:maximumItemsToReturn>';
        soapbatch += '<soc:startIndex>0</soc:startIndex>';
        soapbatch += '</soc:GetTagsOfUser>';
        soapbatch += hub10_SoapPostfix;

        var postUrl = hub10_VDIR + '/_vti_bin/SocialDataService.asmx?op=GetTagsOfUser';
        var action = 'http://microsoft.com/webservices/SharePointPortalServer/SocialDataService/GetTagsOfUser';

        this.hub2010_favoritesXml = hub10_GetSocialDataServiceCall(soapbatch, postUrl, action);
        
        // parse XML using the XSLT from the server.
		if (!hub10_xmlhttpItems) hub10_xmlhttpItems = hub10_GetHTTPObject();
	
		var xslUrl = hub10_VDIR + '/supportFiles/socialDataServiceAsString.xsl';
		
	    // load the XSL synchronously
	    hub10_xmlhttpItems.open("GET", xslUrl, false);
	    hub10_xmlhttpItems.send();
	    if (hub10_xmlhttpItems.readyState != 4) return null;
		var xslDocObj = hub10_GetSoapResponseXml(hub10_xmlhttpItems);
	

	    if (typeof XSLTProcessor != "undefined") 
	    {
	    	// MOZILLA
	        var xslProc = new XSLTProcessor ();
	        xslProc.importStylesheet(xslDocObj);
	        var node = xslProc.transformToDocument(this.hub2010_favoritesXml);
	        retVal = (new XMLSerializer()).serializeToString(node);
	    }
	    else if (typeof this.hub2010_favoritesXml.transformNode != "undefined") 
	    {
	    	// IE
	        retVal = this.hub2010_favoritesXml.transformNode(xslDocObj);
	    }
	    else 
	    {
	        retVal = "Favorites can not be processed.";
	    }

    }
    else {
    	alert("Favorites could not be processed. User context was not available.");
    }
	
	return retVal;
}


function hub2010_onUserQuerySucceeded(sender, args) 
{
	var hub10_currentUserId = this.hub2010_currentUser.get_loginName();
	
	if (hub10_currentUserId && this.hub2010_domElement) {
        soapbatch = hub10_Social_SoapPrefix;
        soapbatch += '<soc:GetTagsOfUser>';
        soapbatch += '<soc:userAccountName>' + hub10_currentUserId + '</soc:userAccountName><soc:maximumItemsToReturn>999</soc:maximumItemsToReturn>';
        soapbatch += '<soc:startIndex>0</soc:startIndex>';
        soapbatch += '</soc:GetTagsOfUser>';
        soapbatch += hub10_SoapPostfix;

        var postUrl = hub10_VDIR + '/_vti_bin/SocialDataService.asmx?op=GetTagsOfUser';
        var action = 'http://microsoft.com/webservices/SharePointPortalServer/SocialDataService/GetTagsOfUser';

        this.hub2010_favoritesXml = hub10_GetSocialDataServiceCall(soapbatch, postUrl, action);
        
        hub10_RenderFavoritesSocialDataXmlAsHtml(this.hub2010_favoritesXml, this.hub2010_domElement);
    }
    else {
    	alert("dom or currentuserid null");
    }
	return;
}


function hub2010_onUserQueryFailed(sender, args) 
{	
	alert("user query failed");
	return;
}



// Remove an existing favorite from the social data / term store for this user & URL
function hub10_RemoveFavorite(encodedUrl) {

    // are you sure?
    if (confirm("Are you sure you want to remove this favorite?")) 
    {
        var soapbatch;
        var owsxml;

        soapbatch = hub10_Social_SoapPrefix;
        soapbatch += '<soc:DeleteTag>';
        soapbatch += '<soc:url>' + encodedUrl + '</soc:url><soc:termID>' + hub10_favoriteTermGuid + '</soc:termID>';
        soapbatch += '</soc:DeleteTag>';
        soapbatch += hub10_SoapPostfix;

        var postUrl = hub10_VDIR + '/_vti_bin/SocialDataService.asmx?op=DeleteTag';
        var action = 'http://microsoft.com/webservices/SharePointPortalServer/SocialDataService/DeleteTag';

        hub10_UpdateSocialDataServiceCall(soapbatch, postUrl, action);

        return;
    }
}

// Add a quiz result list item to the quiz result list
function hub10_SubmitQuizResult(resultsListName, userId, product, productVersion, score) {

    var soapbatch;
    var owsxml;

    owsxml = "<Batch><Method ID='1' Cmd='New'>";
    owsxml += "<Field Name='Title'>"+ product + " " + productVersion + " Quiz Response</Field>";
    owsxml += "<Field Name='Product'>" + product + "</Field>";
    owsxml += "<Field Name='ProductVersion'>" + productVersion + "</Field>";
    owsxml += "<Field Name='Respondent'>"+ userId +"</Field>";
    owsxml += "<Field Name='Score'>" + score + "</Field>";
    owsxml += "</Method></Batch>";

    soapbatch = hub10_Office_SoapPrefix;
    soapbatch += '<UpdateListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">';
    soapbatch += '<listName>' + resultsListName + '</listName>';
    soapbatch += '<updates>' + owsxml + '</updates></UpdateListItems>';
    soapbatch += hub10_SoapPostfix;

    hub10_UpdateListItemsOfficeServiceCall(soapbatch);

    return;

}







// Handle the readystatechange for async soap calls
function hub10_HandleEvent() {
    var bError = false;

    if (hub10_xmlhttpItems.readyState != 4) return;

    var errornodes = [];
    var xmlDocObj = hub10_GetSoapResponseXml(hub10_xmlhttpItems);

    //check for either an errorstring or faultstring
    errornodes = xmlDocObj.getElementsByTagName("errorstring");

    if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
        alert("Unable to save the update :\n" + errornodes[0].firstChild.nodeValue);
        bError = true;
    }
    else {
        errornodes = xmlDocObj.getElementsByTagName("faultstring");
        if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
            alert("Sorry, we were unable to save your update:\n" + errornodes[0].firstChild.nodeValue);
            bError = true;
        }

    }

    // If there was a problem updating the item we will get an ErrorText
    errornodes = xmlDocObj.getElementsByTagName("ErrorText");

    if (typeof (errornodes) != 'undefined' && errornodes.length > 0) {
        alert("Sorry, the submission failed due to missing list columns:\n" + errornodes[0].firstChild.nodeValue);
        bError = true;
    }

    if (!bError) {
        // javascript:history.go(0);
    }

}


// Cross Browser helper to filter the XML results
// Returns array of Node objects
function hub10_GetSoapResponseXml(responseHttp) {
    var m_Items;

    // Mozilla
    if (window.addEventListener) {
        m_Items = responseHttp.responseXML; //.getElementsByTagName(tagName);
    }
    else { // IE
        var xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
        xmlDocument.loadXML(responseHttp.responseText);
        m_Items = xmlDocument;
    }

    return m_Items;

}

function hub10_GetHTTPObject() {
    var httpobj;

    if (window.XMLHttpRequest) {
        try { httpobj = new XMLHttpRequest(); }
        catch (e) { httpobj = null; }

    }
    else if (window.ActiveXObject) {
        try { httpobj = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch (e) {
            try { httpobj = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch (e) { httpobj = null; }
        }
    }

    return httpobj;
}



/* UI FUNCTIONS */
// to be called by NewForm.aspx in Forums
function hub10_getSelectedProductByID(parentId) {

    var soapbatch;
    var owsxml;

    owsxml = "<Where>";
    owsxml += "<Eq><FieldRef Name='ID'/><Value Type='Integer'>" + parentId + "</Value></Eq>";
    owsxml += "</Where>";

    soapbatch = hub10_Office_SoapPrefix;
    soapbatch += '<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">';
    soapbatch += '<listName>Forums</listName>';
    soapbatch += '<query><Query>' + owsxml + '</Query></query>';
    soapbatch += '<viewFields><ViewFields><FieldRef Name="Product" /></ViewFields></viewFields>';
    soapbatch += '<queryOptions><QueryOptions><Folder></Folder><IncludeMandatoryColumns>TRUE</IncludeMandatoryColumns></QueryOptions></queryOptions></GetListItems>';
    soapbatch += hub10_SoapPostfix;

    var val = hub10_GetListItemOfficeServiceCall(soapbatch, "ows_Product");

    // val can be multivalued - take the first product value out
    var vals = val.split(";#");
    return vals[1];

}

// to be called only from the NewForm.aspx in Forums - set the product choice based on querystring values
function hub10_setSelectedProduct(productValue) {

    if (productValue) {
        productValue= productValue.toLowerCase();
        // sourceValue = sourceValue.replace(/%2e/g, ".");
        // sourceValue = sourceValue.replace(/%2f/g, "|");
        // var product = sourceValue.substring(sourceValue.lastIndexOf("|") + 1, sourceValue.lastIndexOf(".aspx"));

        // find idAttachmentsRow 0 then find the checkboxes by relative position
        var phcontrol = document.getElementById("idAttachmentsRow");
        var numChildren = phcontrol.parentElement.children.length;
        var spanControl = phcontrol.parentElement.children[numChildren - 2].children[1].children[1];
        // span > class+title > input | label
        var selectObj = spanControl.children[0];
        for (var i = 0; i < selectObj.length; i++) {
            var title = selectObj.options[i].text;

            if (title.toLowerCase() == productValue) {
                // set the selected state
                selectObj.options[i].selected = true;
            }
        }
        // else do nothing

        return productValue;
    }
    return "";
}

function hub10_activateTab(tabNum)
{
	var tab1 =  document.getElementById("hub10_bookshelf_tab1"); 
	var tab2 =  document.getElementById("hub10_bookshelf_tab2");
	var tab3 =  document.getElementById("hub10_bookshelf_tab3");
	var tab4 =  document.getElementById("hub10_bookshelf_tab4");
	
	var favoritesDiv = document.getElementById("hub2010Favorites");
	
	var div1 = document.getElementById("hub10_bookshelf_featuredVideo");
	var div2 = document.getElementById("hub10_bookshelf_featured");
	var div3 = document.getElementById("hub10_bookshelf_mybookmarks");
	var div4 = document.getElementById("hub10_bookshelf_topratedcontent");
	
	var activeDiv = document.getElementById("hub10_bookshelf_activeContent");
	
	// set all tabs to unselected
	tab1.className ="ph-tab-unselected";
	tab2.className ="ph-tab-unselected";
	tab3.className ="ph-tab-unselected";
	tab4.className ="ph-tab-unselected";
	
	div1.style.display = "none";
	div2.style.display = "none";
	div3.style.display = "none";
	div4.style.display = "none";

			
	switch(tabNum)
	{

		case 1:
			tab1.className ="ph-tab-selected";
			// div1.style.display = "block";
			activeDiv.innerHTML= div1.innerHTML;
			hub10_SetCookie("hub10_activeTab", 1);
		break;
		
		case 2:
			tab2.className = "ph-tab-selected";
			// for the bookmarks tab, call a client side function to render the data
			hub10_DisplayFavorites(favoritesDiv);
			//div2.style.display = "block";
			activeDiv.innerHTML= div2.innerHTML;

			hub10_SetCookie("hub10_activeTab", 2);
		break;
		
		case 3:
			tab3.className="ph-tab-selected";
			//div3.style.display = "block";
			activeDiv.innerHTML= div3.innerHTML;			
			hub10_SetCookie("hub10_activeTab", 3);
		break;
	
		case 4:
			tab4.className="ph-tab-selected";
			//div4.style.display = "block";
			activeDiv.innerHTML= div4.innerHTML;				
			hub10_SetCookie("hub10_activeTab", 4);
		break;

		default:
			hub10_SetCookie("hub10_activeTab", 1);
			activeDiv.innerHTML= div1.innerHTML;
			return;	
	}
}

function hub10_SetCookie(cookieName, cookieValue) 
{
	if (cookieName && cookieValue) 
	{
    	var date = new Date();
    	var days = 120;
    	date.setTime(date.getTime()+(days*24*60*60*1000));
    	var expires = "; expires="+date.toGMTString();
    	document.cookie = cookieName+"="+cookieValue+expires+"; path=/";
    }
}

function hub10_DetermineActiveTabByCookie()
{
	ExecuteOrDelayUntilScriptLoaded(hub2010_LoadVdirUrl, "sp.js");
    var activeTab = 1;
    var c_name = "hub10_activeTab";
	if (document.cookie.length > 0)
	{
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
	  { 
	    c_start=c_start + c_name.length+1; 
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    activeTab = unescape(document.cookie.substring(c_start,c_end));
	  } 
	}
	//hub10_activateTab(parseInt(activeTab));
	hub10_activateTab(1);
	
}


function ph_submitSearch(dropDownControl)
{
	if (!dropDownControl)
	{
		return;
	}
	// get the first portion of the url
	var URL = window.location.href.split('?')[0];				
	var inputText = dropDownControl.options[dropDownControl.selectedIndex].value;
	
	if(inputText != 'All')
	{
		window.location = URL + "?Product=" + inputText + "&Key=0";
	}
	else  //is all
	{							
		window.location = URL;
	}
}


// get a query string variable value from the url
function hub10_getQueryVariable(variable) 
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  
  for (var i=0;i<vars.length;i++) 
  {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  
  return "";
}


ExecuteOrDelayUntilScriptLoaded(hub2010_LoadVdirUrl, "sp.js");

