Monday, June 24, 2013

Javascript for 'Cross-site Publishing'

<script>
// initialize profile properties
var g_CurrentUserProfileProperties = "";
var g_CurrentUserName = "";
var g_CurrentUserCountry = "";
var g_CurrentUserLanguage = "";
var g_CurrentUserAccountName = "";
var g_CurrentUserWorkEmail = "";
</script>

<!-- div that will be appended with the found items -->
<div id="divContentContainer"></div>

<!-- script that will do the deed -->
<script type="text/javascript">
    $(document).ready(function ($) {
 var e = ExecuteOrDelayUntilScriptLoaded(DisplaySearchResults, "sp.js");      
    });

function DisplaySearchResults()
{
CallloadCurrentUserDataWhenScriptIsloaded();
}


function CallloadCurrentUserDataWhenScriptIsloaded()
{
SP.SOD.executeOrDelayUntilScriptLoaded(loadCurrentUserData, 'SP.UserProfiles.js');
}

function loadCurrentUserData()
{
//Get Current Context
var clientContext = new SP.ClientContext.get_current();

//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);

//Get properties of the current user
userProfileProperties = peopleManager.getMyProperties();

clientContext.load(userProfileProperties);

//Execute the Query.
clientContext.executeQueryAsync(onloadCurrentUserDataSuccess, onloadCurrentUserDataFail);

}
 
function onloadCurrentUserDataSuccess() {  

// Get ProfileProperties object
g_CurrentUserProfileProperties = userProfileProperties.get_userProfileProperties();

// Get specific properties
g_CurrentUserName = userProfileProperties.get_displayName();
g_CurrentUserCountry = g_CurrentUserProfileProperties['Country'];
g_CurrentUserLanguage = g_CurrentUserProfileProperties['Language'];
g_CurrentUserAccountName = g_CurrentUserProfileProperties['AccountName'];
g_CurrentUserWorkEmail = g_CurrentUserProfileProperties['WorkEmail'];

console.log(g_CurrentUserName);
console.log(g_CurrentUserCountry);
console.log(g_CurrentUserAccountName);
console.log(g_CurrentUserWorkEmail);

if (g_CurrentUserCountry != null && g_CurrentUserCountry != undefined)
{
var basePath = "https://jwiersem.sharepoint.com/sites/hrs-content/_api/";
var aFullQuery = "search/query?Querytext='HRS_Country=" + g_CurrentUserCountry + "'&selectproperties='Url,Title,PublishingImage'";

$.ajax({
url: basePath + aFullQuery,
type: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function (data) {
ItemsFound(data);
},
error: function (data) {
//output error HERE
alert('Error api call 1: ' + data.statusText);
}
});
}
}

function onloadCurrentUserDataFail(sender, args) {
alert("Error: " + args.get_message());
}

function ItemsFound(data)
{
//script to build UI HERE
//get the details for each item
var listData = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;

if (listData != null && listData != undefined)
{
var itemCount = listData.length;
var processedCount = 0;
var ul = $("<ul>");
for (i = 0; i < listData.length; i++) {
var aCurrentItem = listData[i].Cells.results;
var aCurrentItemURI = GetValueFromArray(aCurrentItem, "Url");
var aCurrentItemTitle = GetValueFromArray(aCurrentItem, "Title");
var aCurrentItemImageHTML = GetValueFromArray(aCurrentItem, "PublishingImage");
aCurrentItemImageHTML = unescape(aCurrentItemImageHTML);

// Show only the pages with the same language as the user's preferences
var aIsCurrentUserLanguageItem = IsCurrentUserLanguageItemOrGlobal(aCurrentItemURI, g_CurrentUserLanguage);

if (aIsCurrentUserLanguageItem)
{
var htmlStr = "";
var aLink = "<a href='" + aCurrentItemURI + "'>" + aCurrentItemImageHTML + "</a>";
var aTitleSpan = "<span>" + aCurrentItemTitle + "</span>";
var aFullDiv = "<div>" + aLink + aTitleSpan + "</div>";

htmlStr += "<li>" + aFullDiv + "</li>";

ul.append($(htmlStr));
}
} // end for all items in listData
ul.append("</ul>");
$("#divContentContainer").append(ul);
}
}

function IsCurrentUserLanguageItemOrGlobal(aCurrentItemURI, aCurrentUserLanguage)
{
var Yesitis = ((aCurrentItemURI.toLowerCase().indexOf(aCurrentUserLanguage) >= 0) || (aCurrentItemURI.toLowerCase().indexOf("global") >= 0));

return Yesitis;
}

function GetValueFromArray(aArray, aKey)
{
var aReturnValue = "";
var aCounter = 0;

if (aArray != null && aArray != undefined && aArray.length > 0)
{
if (aKey != null && aKey != undefined)
{
$.each(aArray, function(key, value)
{
var bKey = aArray[key]["Key"];
if (bKey == aKey)
{
aReturnValue = aArray[key]["Value"];
aCounter++;
}
});
}
}

if (aCounter > 1)
{
console.log('Error in GetValueFromArray: Multiple entries foudn in array with the same key');
}

if (aReturnValue == undefined || aReturnValue == null || aReturnValue == "")
{
console.log('Error in GetValueFromArray: Key not found in array');
}

return aReturnValue;
}
</script>

1 comment: