").attr("id", "content-body")
);
}
// Adjust the height of the content automatically
$("#content").height($(window).height() - $("#header").height() - 50); // 50 is the padding top/bottom
$(window).resize(function() {
$("#content").height($(window).height() - $("#header").height() - 50); // 50 is the padding top/bottom
});
updateTitle();
}
function updateTitle() {
$("head title").text("");
$("#content-title").text("");
var titleTokens = [project.name, navigationTitle];
$("#navigation").find(".active").each(function(i, d){
titleTokens.push($(d).attr("title"));
});
//console.log(titleTokens);
$("head title").text(titleTokens.join(" : "));
var html = titleTokens.slice(0, -1).join(" : ")
html += (" :
" + titleTokens.slice(-1)[0] + "");
$("#content-title").html(html);
//$("#frontpage-title").text([$("#frontpage-title").text(), navigationTitle].join(" : "));
//$("#frontpage-title-alt").text([$("#frontpage-title-alt").text(), navigationTitle].join(" : "));
}
function emptyNavigation() {
$("#navigation").empty();
}
function removeNavigation() {
$("#nav-ul").remove();
}
function initAndCall(callback) {
init();
// call the callback function when everything is finished
callback();
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m, key, value) {
vars[key] = value;
});
return vars;
}
function loadAlternativeCss(cssType) {
if (!cssType)
cssType = getServerType();
if (config.styleOptions.hasOwnProperty(cssType)) {
$("head")
.append(
$("
")
.attr({
rel: "stylesheet",
type: "text/css",
href: config.styleOptions[cssType]
})
);
}
}
function getServerType() {
if (!config.serverType) {
// Load the script code synchronously
$.ajaxSetup({async: false});
$.getScript(config.serverTypeScript)
.done(function(script, textStatus) {
config.serverType = serverType;
});
$.ajaxSetup({async: true});
}
return config.serverType;
}
function getScriptSync(url) {
// Load the script code synchronously
$.ajaxSetup({async: false});
$.getScript(url)
.done(function(script, textStatus) {});
$.ajaxSetup({async: true});
};
function storeLocalObject(key, obj) {
//Stores the JavaScript object as a string
//console.log(JSON.stringify(obj));
localStorage.setItem(key, JSON.stringify(obj));
//console.log("stored : " + key + " - " + JSON.stringify(obj));
}
function retrieveLocalObject(key) {
// Parses the saved string into a JavaScript object again
//console.log("retrieved : " + key + " - " + localStorage.getItem(key));
return JSON.parse(localStorage.getItem(key));
}
//Available filters is an array of boolean values provided by each page's config file
function initHeaderAndFilters(headerAndFilters) {
globalHeaderAndFilters = headerAndFilters;
if (!headerAndFilters) {
$("#header").css("display", "none");
}
else {
// Load the header html code synchronously
jQuery.ajaxSetup({async: false});
$("#header").load(config.headerOptions[headerAndFilters.headerType].filename);
jQuery.ajaxSetup({async: true});
$("#filter").addClass("red-button hand"); // apply class to the button
// Set the header height dynamically
$("#header").height(config.headerOptions[headerAndFilters.headerType].height);
// Sync nav logo's height with the header
$("#nav-logo").height(config.headerOptions[headerAndFilters.headerType].height);
// Disable/Enable the header fields base on each page's given options
$.each(headerAndFilters.disabledFields, function(i, filterBoolean) {
if (typeof filterBoolean === "boolean") {
$("#" + config.headerOptions[headerAndFilters.headerType].fields[i].fieldId)
//.attr("disabled", filterBoolean)
//.addClass((filterBoolean) ? "disabled" : "");
.addClass((filterBoolean) ? "hidden" : "");
}
else { // filterboolean is array - must match the length of the sub fields
$("#" + config.headerOptions[headerAndFilters.headerType].fields[i].fieldId).children().each(function(j, e) {
$(e).attr("disabled", filterBoolean[j])
//.addClass((filterBoolean[j]) ? "disabled" : "");
.addClass((filterBoolean[j]) ? "hidden" : "");
});
/*
$.each(config.headerOptions[headerAndFilters.headerType].fields[i].elementsId, function(j, elementId) {
$("#" + elementId)
.attr("disabled", filterBoolean[j])
.addClass((filterBoolean[j]) ? "disabled" : "");
});
*/
}
});
populateHeader(headerAndFilters);
}
/*
$("#navigation").append(
"
"
);
$("#header").append(
""
);
*/
// Show/Hide the header/nav according to local settings and keep the object in a temp var
var localHeaderNavSettings = retrieveAndSetHeaderAndNavSettings(headerAndFilters);
var windowEventTimeout = 500;
$("#header-toggle").click(function(e) {
e.preventDefault();
// If the collapse image clicked (arrow up), increase content and nav
if ($("#header-toggle").hasClass("toggle-arrow-up")) {
hideHeader(animate = true);
localHeaderNavSettings.header = false;
}
// Else revert to normal heights/positions
else {
showHeader(animate = true);
localHeaderNavSettings.header = true;
}
storeLocalHeaderAndNavSettings(localHeaderNavSettings);
setTimeout("$(window).resize()", windowEventTimeout);
});
$("#nav-toggle").click(function(e) {
e.preventDefault();
//$("#navigation").toggle("slide", { direction: "left" }, "slow");
if ($("#nav-toggle").hasClass("toggle-arrow-left")) {
hideNav(animate = true);
localHeaderNavSettings.nav = false;
}
else {
showNav(animate = true);
localHeaderNavSettings.nav = true;
}
storeLocalHeaderAndNavSettings(localHeaderNavSettings);
setTimeout("$(window).resize()", windowEventTimeout);
});
if (isPrint()) {
headerAndFilters = null;
hideHeader();
hideNav();
}
}
function getCurrentHeaderHeight() {
return (globalHeaderAndFilters) ? config.headerOptions[globalHeaderAndFilters.headerType].height : 0;
}
function hideHeader(animate) {
if (typeof headerAndFilters === "undefined" || headerAndFilters == null)
return;
$("#header-toggle").removeClass("toggle-arrow-up").addClass("toggle-arrow-down");
if (animate) {
$("#header").animate({
top: (-1*config.headerOptions[headerAndFilters.headerType].height)
}, "slow");
$("#content").animate({top: (headerNavProperties.headerBottomMargin)}, "slow");
}
else {
$("#header").css({
top: (-1*config.headerOptions[headerAndFilters.headerType].height)
});
$("#content").css({top: (headerNavProperties.headerBottomMargin)});
}
$("#content").css({
height: $(window).height() - (2*headerNavProperties.headerBottomMargin)
});
}
function showHeader(animate) {
$("#header-toggle").removeClass("toggle-arrow-down").addClass("toggle-arrow-up");
if (animate) {
$("#header").animate({top: headerNavProperties.headerShowTop}, "slow");
$("#content").animate({
top: (config.headerOptions[headerAndFilters.headerType].height + headerNavProperties.headerBottomMargin)
}, "slow");
}
else {
$("#header").css({top: headerNavProperties.headerShowTop});
$("#content").animate({
top: (config.headerOptions[headerAndFilters.headerType].height + headerNavProperties.headerBottomMargin)
});
}
$("#content").css({height: $(window).height()
- (config.headerOptions[headerAndFilters.headerType].height + 2*headerNavProperties.headerBottomMargin)
});
}
function hideNav(animate) {
$("#nav-toggle").removeClass("toggle-arrow-left").addClass("toggle-arrow-right");
if (animate) {
$("#navigation").animate({left: headerNavProperties.navHideLeft}, "slow");
$("#header").animate({
left: headerNavProperties.headerNavHideLeft,
width: headerNavProperties.headerNavHideWidth
}, "slow");
$("#content").animate({
left: headerNavProperties.contentNavHideLeft,
width: headerNavProperties.contentNavHideWidth
}, "slow");
}
else {
$("#navigation").css({left: headerNavProperties.navHideLeft});
$("#header").css({
left: headerNavProperties.headerNavHideLeft,
width: headerNavProperties.headerNavHideWidth
});
$("#content").css({
left: headerNavProperties.contentNavHideLeft,
width: headerNavProperties.contentNavHideWidth
});
}
}
function showNav(animate) {
$("#nav-toggle").removeClass("toggle-arrow-right").addClass("toggle-arrow-left");
if (animate) {
$("#navigation").animate({left: headerNavProperties.navShowLeft}, "slow");
$("#header").animate({
left: headerNavProperties.headerNavShowLeft,
width: headerNavProperties.headerNavShowWidth
}, "slow");
$("#content").animate({
left: headerNavProperties.contentNavShowLeft,
width: headerNavProperties.contentNavShowWidth
}, "slow");
}
else {
$("#navigation").css({left: headerNavProperties.navShowLeft});
$("#header").css({
left: headerNavProperties.headerNavShowLeft,
width: headerNavProperties.headerNavShowWidth
});
$("#content").css({
left: headerNavProperties.contentNavShowLeft,
width: headerNavProperties.contentNavShowWidth
});
}
}
function populateHeader(headerAndFilters) {
//block();
$.each(config.headerOptions[headerAndFilters.headerType].fields, function(i, field) {
if (field.fieldId == "builds-field")
populateAllBuilds({elementId: "builds", async: false});
if (field.fieldId == "build-field")
populateAllBuilds({elementId: "build", async: false});
else if (field.fieldId == "dates-builds-field") {
populateAllBuilds({elementId: "builds", async: false});
populateDatesBuildsOptions("dates-builds");
}
else if (field.fieldId == "build-config-field")
populateBuildConfigs();
else if ((field.fieldId == "platforms-field") || (field.fieldId == "platform-field"))
populatePlatforms();
else if ((field.fieldId == "rosplatforms-field") || (field.fieldId == "rosplatform-field"))
populateROSPlatforms();
else if (field.fieldId == "level-field")
populateLevels();
else if (field.fieldId == "resolution-field")
populateResolutions();
else if (field.fieldId == "locations-field")
populateLocations();
else if (field.fieldId == "gamers-field") {
var headerStoreName = (config.headerOptions[headerAndFilters.headerType].storeName) ?
config.headerOptions[headerAndFilters.headerType].storeName
: headerAndFilters.headerType;
var localData = retrieveLocalObject(config.restHost + headerStoreName);
tabularise("gamers-field", (localData) ? localData["gamers-field"] : null);
populateSCUsers();
populateSCUserGroups();
populateGamertags();
populateGamertagGroups();
populateCrews();
}
/*
else if (field.fieldId == "gamers-betting-field") {
var headerStoreName = (config.headerOptions[headerAndFilters.headerType].storeName) ?
config.headerOptions[headerAndFilters.headerType].storeName
: headerAndFilters.headerType;
var localData = retrieveLocalObject(config.restHost + headerStoreName);
tabularise("gamers-betting-field", (localData) ? localData["gamers-betting-field"] : null);
populateGamertags();
populateGamertagGroups();
}
*/
else if (field.fieldId == "gamertags-field") {
populateGamertags();
}
else if (field.fieldId == "gamer-group-field") {
populateGamerGroups();
}
else if (field.fieldId == "creators-field") {
populateCreators();
}
else if (field.fieldId == "missions-field") {
$("#freemode-category").change(populateMissions);
$("#freemode-ugcstatus").change(populateMissions);
populateMissions();
}
else if (field.fieldId == "deathmatch-field") {
populateDeathmatch();
}
else if (field.fieldId == "match-type-field") {
populateMatchTypes();
}
else if (field.fieldId == "game-types-field")
populateGameTypes();
else if (field.fieldId == "character-field")
populateCharacters();
else if ((field.fieldId == "freemode-categories-field") || (field.fieldId == "freemode-category-field"))
populateFreemodeCategories();
else if (field.fieldId == "freemode-ugcstatus-field")
populateUGCStatus();
else if (field.fieldId == "user-field")
populateExportUsers();
else if (field.fieldId == "dt-build-field")
populatePlaythroughsBuilds();
else if (field.fieldId == "dt-platform-field")
populatePlaythroughsPlatforms();
else if (field.fieldId == "dt-users-field")
populatePlaythroughsUsers();
else if (field.fieldId == "file-types-field")
populateFileTypes();
else if (field.fieldId == "game-times-field")
populateGameTimes();
else if (field.fieldId == "date-grouping-field")
populateDateGrouping();
else if (field.fieldId == "cutscene-field")
populateCutscenes();
else if (field.fieldId == "clip-category-field")
populateClipCategories();
});
//unBlock();
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
$("input#date-from").datetimepicker({
dateFormat: config.datePickerFormat,
timeFormat: config.timePickerFormat,
maxDate: new Date(),
});
$("input#date-to").datetimepicker({
dateFormat: config.datePickerFormat,
timeFormat: config.timePickerFormat,
maxDate: tomorrow,
});
//
$("input#created-date-from").datetimepicker({
dateFormat: config.datePickerFormat,
timeFormat: config.timePickerFormat,
maxDate: new Date(),
});
$("input#created-date-to").datetimepicker({
dateFormat: config.datePickerFormat,
timeFormat: config.timePickerFormat,
maxDate: tomorrow,
});
var timezoneOffset = new Date().getTimezoneOffset()/60; // hours offset from utc
// reverse the offset and the sign, this happens cause timezoneOffset is the hours difference
// form our current timezone to Utc and we need the opposite
var timezoneString = "UTC" + ((timezoneOffset>0) ? "-" : "+") + -1*timezoneOffset;
$("#dates-field legend span").text("Dates (" + timezoneString + "):");
retrieveAndSetLocalHeaderOptions(headerAndFilters);
$("body input").focus(function() {
$(this).select();
});
$("#header input").keypress(function(e) {
if ($(this).attr("id") == "section" ||
$(this).attr("id") == "token-input-sc-users" ||
$(this).attr("id") == "token-input-sc-user-groups" ||
$(this).attr("id") == "token-input-gamertags" ||
$(this).attr("id") == "token-input-gamertag-groups" ||
$(this).attr("id") == "token-input-crews" ||
$(this).attr("id") == "token-input-dt-users" ||
$(this).attr("id") == "token-input-missions" ||
$(this).attr("id") == "token-input-creators")
return;
if (e.which == 13) {
$("#filter").trigger("click");
}
});
$("#filter")
.click(function() {
storeLocalHeaderOptions(headerAndFilters);
//hideHeader(animate=true);
});
}
function retrieveAndSetLocalHeaderOptions(headerAndFilters) {
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
var defaultHeaderData = {
"platform" : ["PS3"],
"platforms" : ["PS3", "Xbox360"],
"locations" : [],
"age-min" : "",
"age-max" : "",
"sc-users" : [],
"gamertags" : [],
"game-type": [],
"date-from" : $.datepicker.formatDate(config.datePickerFormat, yesterday) + " 00:00",
"date-to" : $.datepicker.formatDate(config.datePickerFormat, new Date()) + " 00:00",
"utc-force" : true,
"build" : ["-1"],
"builds" : ["-1"],
"cwp" : [0],
"build-config" : ["Beta"],
"percentile-lower" : "0",
"percentile-upper" : "100",
"radio-checked": "dates-field", // for default radio button selection
"upper-xp" : 900000,
"time-since-spawn" : 10,
"section": "",
"user": "",
"time-since-spawn": "10",
// Difficulty tracking
"dt-build" : [],
"dt-platform" : [],
"dt-user" : [],
"last_modified" : new Date(),
};
var headerStoreName = (config.headerOptions[headerAndFilters.headerType].storeName) ?
config.headerOptions[headerAndFilters.headerType].storeName
: headerAndFilters.headerType;
var headerData = retrieveLocalObject(config.restHost + headerStoreName);
if (headerData) {
var lastModified = new Date(headerData.last_modified);
// Check for expiration
if (datesDiffInSecs(new Date(), lastModified) > config.storageExpirePeriod) {
//console.log("storage expired");
headerData = defaultHeaderData;
}
}
else
headerData = defaultHeaderData;
$.each(config.headerOptions[headerAndFilters.headerType].fields, function(i, field) {
//if ($("#" + field.fieldId).is(":disabled"))
// return // continue the fields loop
/*
// If the field has a radio button and it's prefered as default
if (field.hasRadio && (headerData["radio-checked"] == field.fieldId)) {
// If the field is not disabled
if (!$("#" + field.fieldId).attr("disabled")) {
// check the radio button
$("#" + field.fieldId + " legend input:radio").prop("checked", true);
}
// If the default radio is disabled identify the alternative option
else {
var alternativeField;
if (field.fieldId == "dates-field") {
alternativeField = "builds-field";
}
else if (field.fieldId == "builds-field") {
alternativeField = "dates-field";
}
// And if it's not disabled as well, select it
if (!$("#" + alternativeField).attr("disabled")) {
$("#" + alternativeField + " legend input:radio").prop("checked", true);
}
}
}
*/
$.each(field.elementsId, function(i, elementId) {
if ($("#" + elementId).is("input")) {
// token input
if ($("#" + elementId).hasClass("token-input")) {
if (!headerData[elementId])
return;
$.each(headerData[elementId], function(i, elementObj) {
$("#" + elementId).tokenInput("add", elementObj);
});
}
else if ($("#" + elementId).is(":checkbox")) {
$("#" + elementId).prop("checked", headerData[elementId]);
}
else {
$("#" + elementId).val(headerData[elementId]);
}
}
else if ($("#" + elementId).is("select")){
$("#" + elementId + " > option").each(function(i) {
if ($.inArray($(this).val(), headerData[elementId]) != -1)
$(this).attr("selected", true);
else
$(this).attr("selected", false);
});
}
});
});
// For showing/hiding the dates/builds/cwt
if (!$("#dates-builds").parent().hasClass("hidden"))
updateDateBuildFields("dates-builds");
}
function storeLocalHeaderOptions(headerAndFilters) {
var headerStoreName = (config.headerOptions[headerAndFilters.headerType].storeName) ?
config.headerOptions[headerAndFilters.headerType].storeName
: headerAndFilters.headerType;
var localData = retrieveLocalObject(config.restHost + headerStoreName);
var headerData = (localData) ? localData : {};
$.each(config.headerOptions[headerAndFilters.headerType].fields, function(i, field) {
//console.log($("#" + field.fieldId + " legend input:radio"));
if (field.hasRadio && $("#" + field.fieldId + " legend input:radio").is(":checked"))
headerData["radio-checked"] = field.fieldId;
$.each(field.elementsId, function(i, elementId) {
// Stores the value for inputs and the selected options array for selects
//console.log(elementId);
//console.log(typeof $("#" + elementId).val());
if ((typeof $("#" + elementId).val() == "string") && $("#" + elementId).is("select"))
headerData[elementId] = [$("#" + elementId).val()];
else if ($("#" + elementId).hasClass("token-input")) {
if ($("#" + elementId).parent().css("display") != "none") // save the selected tab
headerData[field.fieldId] = i;
headerData[elementId] = $("#" + elementId).tokenInput("get");
}
else if ($("#" + elementId).is(":checkbox"))
headerData[elementId] = $("#" + elementId).is(":checked");
else
headerData[elementId] = $("#" + elementId).val();
});
});
//console.log(headerData);
headerData.last_modified = new Date();
storeLocalObject(config.restHost + headerStoreName, headerData);
}
function checkForEmptyHeaderFields() {
}
function retrieveHeaderAndNavSettings() {
var defaultHeaderNavSettings = {
header: true,
nav: true,
};
var headerNavSettings = retrieveLocalObject(headerNavProperties.localStoragekey);
headerNavSettings = (headerNavSettings) ? headerNavSettings : defaultHeaderNavSettings;
return headerNavSettings;
}
function retrieveAndSetHeaderAndNavSettings(headerAndFilters) {
/*
var defaultHeaderNavSettings = {
header: false,
nav: true,
};
var headerNavSettings = retrieveLocalObject(headerNavProperties.localStoragekey);
headerNavSettings = (headerNavSettings) ? headerNavSettings : defaultHeaderNavSettings;
*/
headerNavSettings = retrieveHeaderAndNavSettings();
/*
// css hides the header by default so check if it needs to be expanded
if (headerNavSettings.header && ($("#header").css("display") != "none")) {
showHeader();
}
else {
hideHeader();
}
// css show the nav by default so check if it needs to be hidden
if (!headerNavSettings.nav) {
hideNav();
}
else
showNav();
*/
windowEventTimeout = 500;
if (headerAndFilters) {
showHeader();
/*
$(window).resize(function() {
setTimeout(showHeader, windowEventTimeout);
});
*/
}
showNav();
return headerNavSettings;
}
function storeLocalHeaderAndNavSettings(headerNavSettings) {
storeLocalObject(headerNavProperties.localStoragekey, headerNavSettings);
}
function tabularise(elementId, selected) {
if (!selected)
selected = 0; // select first element by default
deselectAll(elementId);
$("#" + elementId).find("li").each(function(i, item) {
var link = $(item).find("a");
link.click(function(e) {
e.preventDefault();
deselectAll(elementId);
$(this).addClass("active");
$($(this).attr("href")).removeClass("hidden");
// hide/reset the token input - b*#1429040
$(".token-input-dropdown-facebook").hide();
$(".token-input-input-token-facebook input").val("");
});
if (i == selected) {
link.addClass("active");
$(link.attr("href")).removeClass("hidden");
}
});
function deselectAll(elementId) {
$("#" + elementId).find("li").find("a").each(function(j, a) {
$(this).removeClass("active");
$($(this).attr("href")).addClass("hidden");
})
}
}
function populateLevels() {
$.ajax({
url: config.restHost + config.levelsAll,
type: "GET",
data: {},
dataType: "xml",
async: false,
success: function(xml, textStatus, jqXHR) {
var levels = convertLevelsXml(xml);
$.each(levels, function(i, level) {
$("select#level").append(
$("
")
.text(level.Name)
.val(level.Identifier)
.attr("title", level.Name)
);
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
}
});
}
function convertLevelsXml(xml) {
var elementsArray = [];
$(xml).find("Level").each(function(){
var element = {
Id: $(this).find("Id").text(),
CreatedOn: $(this).find("CreatedOn").text(),
ModifiedOn: $(this).find("ModifiedOn").text(),
Name: $(this).find("Name").text(),
Identifier: $(this).find("Identifier").text(),
LevelIdx: $(this).find("LevelIdx").text(),
}
elementsArray.push(element);
});
return elementsArray;
}
function populateLocations() {
$("select#locations").append(
$("
")
.text("All")
.val(null)
.attr("title", "All")
);
$.ajax({
url: config.restHost + config.SCCountries,
type: "GET",
data: {},
dataType: "json",
async: false,
success: function(result, textStatus, jqXHR) {
$.each(result, function(i, location) {
$("select#locations").append(
$("
")
.text(location.Name)
.val(location.Code)
.attr("title", location.Name)
);
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
}
});
}
function populateSCUsers() {
$("#sc-users").tokenInput(
config.restHost + config.SCVerticaUsersSearch,
{
theme: "facebook",
hintText: "Type at least 3 characters to start searching",
searchDelay: 1000,
method: "GET",
queryParam: "name",
minChars: 3,
//preventDuplicates: true,
onResult: function(result) {
return result.map(
function(d) {return {"name": d}; }
)
.sort(function(a, b) {return (a.name.toUpperCase() > b.name.toUpperCase()) ? 1 : -1});
},
//propertyToSearch: null,
//resultsFormatter: function(item){return item},
//tokenFormatter: function(item) { return "
" + item.first_name + " " + item.last_name + "
" }
}
);
}
function populateSCUserGroups() {
$("#sc-user-groups").tokenInput(
config.restHost + config.SCVerticaUsersGroups,
{
theme: "facebook",
hintText: "Type text to get matched group names",
searchDelay: 1000,
method: "GET",
queryParam: "name",
minChars: 0,
//preventDuplicates: true,
onResult: function(result) {
var input = $("#token-input-sc-user-groups").val();
var re = new RegExp(input, "i");
var filteredResult = [];
result.map(
function(d) {
if (re.test(d))
filteredResult.push({ "name": d });
});
filteredResult.sort(function(a, b) {return (a.name.toUpperCase() > b.name.toUpperCase()) ? 1 : -1});
return filteredResult;
},
}
);
}
function populateGamertags() {
rosPlatformsDict = getRosPlatformsDict();
$("#gamertags").tokenInput(
config.restHost + config.VerticaGamersSearch,
{
theme: "facebook",
hintText: "Type at least 3 characters to start searching",
//searchDelay: 1000,
method: "GET",
queryParam: "name",
minChars: 3,
//preventDuplicates: true,
onResult: function(result) {
return result.map(
function(d) {
return {
name: d.GamerHandle + "(" + rosPlatformsDict[d.Platform] + ")",
//id: rosPlatformsDict[d.Platform],
id: d.Id,
};
})
.sort(function(a, b) {return (a.name.toUpperCase() > b.name.toUpperCase()) ? 1 : -1});
},
}
);
}
function getGamertags() {
var gamertags = $("#gamertags").tokenInput("get");
gamertags = gamertags.map(function(d) {
var nameSplit = d.name.split("("); // Split on the opening brucket
return "<" + nameSplit[0] + "|" + nameSplit[1].slice(0, - 1) + ">"; // construct the gamertag
})
.join();
return gamertags;
}
function getAccountIds() {
var accountIds = $("#gamertags").tokenInput("get");
console.log(accountIds);
accountIds = accountIds.map(function(d) {
return d.id;
})
.join();
return accountIds;
}
function getGamerAccountDict() {
var gamerAccountDict = {};
var gamerObjects = $("#gamertags").tokenInput("get");
gamerObjects.map(function(d) {
if (!gamerAccountDict.hasOwnProperty(d.id)) {
gamerAccountDict[d.id] = d.name.split("(")[0];
}
});
return gamerAccountDict;
}
function populateGamertagGroups() {
$("#gamertag-groups").tokenInput(
config.restHost + config.VerticaGamersGroups,
{
theme: "facebook",
hintText: "Type text to get matched group names",
searchDelay: 1000,
method: "GET",
queryParam: "name",
minChars: 0,
//preventDuplicates: true,
onResult: function(result) {
var input = $("#token-input-gamertag-groups").val();
var re = new RegExp(input, "i");
var filteredResult = [];
result.map(
function(d) {
if (re.test(d.Name))
filteredResult.push({ "name": d.Name });
});
filteredResult.sort(function(a, b) {return (a.name.toUpperCase() > b.name.toUpperCase()) ? 1 : -1});
return filteredResult;
},
}
);
}
function populateCrews() {
$("#crews").tokenInput(
config.restHost + config.VerticaCrewsSearch,
{
theme: "facebook",
hintText: "Type text to get matched group names",
searchDelay: 1000,
method: "GET",
queryParam: "name",
minChars: 2,
//preventDuplicates: true,
onResult: function(result) {
return result.map(
function(d) {
return {
name: d.Name,
id: d.Id,
};
})
.sort(function(a, b) {return (a.name.toUpperCase() > b.name.toUpperCase()) ? 1 : -1});
},
}
);
}
function populateMissions() {
var rosPlatformsDict = getRosPlatformsDict();
var customUrl = "";
var category = ($("#freemode-category").val()) ? $("#freemode-category").val() : null;
var ugcStatus = ($("#freemode-ugcstatus").val()) ? $("#freemode-ugcstatus").val() : null;
if (category)
customUrl += ("&category=" + category);
if (ugcStatus)
customUrl += ("&isPublished=" + ugcStatus);
if (customUrl)
customUrl = "?" + customUrl;
//console.log(customUrl);
$("#missions").empty();
$("#missions-field").find("ul").remove();
$(".token-input-dropdown-facebook").hide();
$(".token-input-input-token-facebook input").val("");
$("#missions").tokenInput(
config.restHost + config.VerticaMissionsSearch + customUrl,
{
theme: "facebook",
hintText: "Type at least 3 characters to start searching",
//searchDelay: 1000,
method: "GET",
//queryParam: "name",
queryParam: "name",
minChars: 3,
//preventDuplicates: true,
onResult: function(result) {
return result.map(
function(d) {
return {
name: d.Name + " (" + d.Creator
+ ((rosPlatformsDict[d.CreatorPlatform]) ? ("[" + rosPlatformsDict[d.CreatorPlatform] + "]") : "")
+ " - v." + d.Version + ")",
id: d.Identifier,
};
})
.sort(function(a, b) {return (a.name.toUpperCase() > b.name.toUpperCase()) ? -1 : 1});
},
}
);
}
function populateDeathmatch() {
var rosPlatformsDict = getRosPlatformsDict();
$("#deathmatch").tokenInput(
config.restHost + config.VerticaMissionsSearch,
{
theme: "facebook",
hintText: "Type at least 3 characters to start searching",
//searchDelay: 1000,
method: "GET",
queryParam: "name",
minChars: 3,
//preventDuplicates: true,
tokenLimit: 1,
onResult: function(result) {
return result.map(
function(d) {
return {
name: d.Name + " (" + d.Creator
+ ((rosPlatformsDict[d.CreatorPlatform]) ? ("[" + rosPlatformsDict[d.CreatorPlatform] + "]") : "")
+ " - v." + d.Version + ")",
id: d.Identifier,
};
})
.sort(function(a, b) {return (a.name.toUpperCase() > b.name.toUpperCase()) ? -1 : 1});
},
}
);
}
function populateCreators() {
var rosPlatformsDict = getRosPlatformsDict();
$("#creators").tokenInput(
config.restHost + config.VerticaGamersSearch,
{
theme: "facebook",
hintText: "Type at least 3 characters to start searching",
//searchDelay: 1000,
method: "GET",
queryParam: "name",
minChars: 3,
//preventDuplicates: true,
onResult: function(result) {
return result.map(
function(d) {
return {
name: d.GamerHandle + "(" + rosPlatformsDict[d.Platform] + ")",
id: "<" + d.UserId + "|" + rosPlatformsDict[d.Platform] + ">",
//id: rosPlatformsDict[d.Platform],
};
})
.sort(function(a, b) {return (a.name.toUpperCase() > b.name.toUpperCase()) ? 1 : -1});
},
}
);
}
function getCreators() {
if ($("#creators").size() == 0)
return [];
var gamertags = $("#creators").tokenInput("get");
gamertags = gamertags.map(function(d) {
return d.id;
}).join(",");
//console.log(gamertags);
return gamertags;
}
// Same as above but for select element
function getGamerGroups() {
var obj = {
url: config.restHost + config.VerticaGamersGroups,
data: {},
method: "GET",
dataType: "json",
async: false,
};
return getAjaxData(obj);
}
function populateGamerGroups() {
var gamerGroups = getGamerGroups();
var dfunc = {
getValue: function(d) { return JSON.stringify(d.Gamers); },
getTitle: function(d) { return d.Name; },
getText: function(d) { return d.Name; },
};
populateSelectElements(["gamer-group"], gamerGroups, dfunc);
}
function getGamertagsFromGroups(groups) {
var gamertags = [];
var rosPlatformsDict = getRosPlatformsDict();
var obj = {
url: config.restHost + config.VerticaGamersGroups,
data: {},
method: "GET",
dataType: "json",
async: false,
};
var allGroups = getAjaxData(obj);
$.each(allGroups, function(i, group) {
if ($.inArray(group.Name, groups) != -1) {
gamertags = gamertags.concat(
group.Gamers.map(function(d) {
return ("<" + d.GamerHandle + "|" + rosPlatformsDict[d.Platform] + ">");
})
);
}
});
return gamertags;
}
function getGamertagsFromCrews(crews) {
var gamertags = [];
var rosPlatformsDict = getRosPlatformsDict();
$.each(crews, function(i, crew) {
var obj = {
url: config.restHost + config.VerticaCrews + "/" + crew.id + "/Members",
data: {},
method: "GET",
dataType: "json",
async: false,
};
gamertags = gamertags.concat(getAjaxData(obj));
});
gamertags = gamertags.map(function(d) {
return ("<" + d.GamerHandle + "|" + rosPlatformsDict[d.Platform] + ">");
});
return gamertags;
}
/*
function populateGamers() {
$.ajax({
url: config.restHost + config.SCGroupsAndUsers,
type: "GET",
data: {},
dataType: "json",
async: false,
success: function(result, textStatus, jqXHR) {
//console.log(result);
var gamerNames = result.map(function(d) {return d.Name});
$("#gamer").autocomplete({
source: gamerNames,
minlength: 2,
change: function(e, ui) {
// when the typed item is not in the list, then ui.item will be null
if (!ui.item)
$("#gamer").val("");
},
})
.keypress(function(e) {
// when pressing enter check if the value is valid, otherwise set to null
if (e.which == 13) {
if ($.inArray($(this).val(), gamerNames) == -1)
$(this).val("");
}
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
}
});
}
*/
/*
function populateGameTypes() {
$.ajax({
url: config.restHost + config.gametypesAll,
type: "GET",
data: {},
dataType: "xml",
async: false,
success: function(xml, textStatus, jqXHR) {
var gametypes = convertGametypesXml(xml);
$.each(gametypes, function(i, gametype) {
$("select#game-types").append(
$("
")
.text(gametype.Value)
.val(gametype.Value)
.attr("title", gametype.Value)
);
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
}
});
}
*/
function populateExportUsers() {
$.ajax({
url: config.restHost + config.mapExportStatsUsers,
type: "GET",
data: {},
dataType: "xml",
async: false,
success: function(xml, textStatus, jqXHR) {
var exportUsers = getExportUsersList(xml);
var defaultVal;
//console.log(exportUsers);
$("#user").autocomplete({
source: exportUsers,
minlength: 2,
change: function(event, ui) {
// when the typed item is not in the list, then ui.item will be null
if (!ui.item)
$("#user").val("");
},
})
.keypress(function(e) {
// when pressing enter check if the value is valid, otherwise set to null
if (e.which == 13) {
if ($.inArray($(this).val(), exportUsers) == -1)
$(this).val("");
}
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
}
});
}
function populatePlaythroughsBuilds() {
$.ajax({
url: config.restHost + config.playthroughsBuilds,
type: "GET",
dataType: "json",
data: {},
async: false,
success: function(json, textStatus, jqXHR) {
// Order the build DESC
json.sort(function(a, b) {return (a>b) ? -1 : 1})
$.each(json, function(i, build) {
$("select#dt-build").append(
$("
")
.text(build)
.val(build)
.attr("title", build)
);
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
}
});
}
function populatePlaythroughsPlatforms() {
$.ajax({
url: config.restHost + config.playthroughsPlatforms,
type: "GET",
dataType: "xml",
data: {},
async: false,
success: function(xml, textStatus, jqXHR) {
$(xml).find("Platform").each(function() {
$("select#dt-platform").append(
$("
")
.text($(this).text())
.val($(this).text())
.attr("title", $(this).text())
);
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
}
});
}
function populatePlaythroughsUsers() {
var rosPlatformsDict = getRosPlatformsDict();
$("#dt-users").tokenInput(
config.restHost + config.playthroughsUsers,
{
theme: "facebook",
hintText: "Type text to select from the list",
searchDelay: 1000,
minChars: 0,
//propertyToSearch: "Username",
tokenLimit: 8,
// preventDuplicates: true,
onResult: function(result) {
var input = $("#token-input-dt-users").val();
var re = new RegExp(input, "i");
var filteredResult = [];
result.map(
function(d) {
if (re.test(d.Username))
filteredResult.push(
{
"name": d.Username + ((rosPlatformsDict[d.Platform]) ? ("(" + rosPlatformsDict[d.Platform] + ")") : ""),
"id": d.GamerHandle + ((rosPlatformsDict[d.Platform]) ? ("|" + rosPlatformsDict[d.Platform]) : ""),
}
);
});
filteredResult.sort(function(a, b) {return (a.name.toUpperCase() > b.name.toUpperCase()) ? 1 : -1});
return filteredResult;
},
//resultsFormatter: function(item){return item},
//tokenFormatter: function(item) { return "
" + item.first_name + " " + item.last_name + "
" }
}
);
/*
$.ajax({
url: config.restHost + config.playthroughsUsers,
type: "GET",
data: {},
dataType: "json",
async: false,
success: function(json, textStatus, jqXHR) {
/*
$("#dt-user").autocomplete({
source: json,
minlength: 2,
change: function(event, ui) {
// when the typed item is not in the list, then ui.item will be null
if (!ui.item)
$("#dt-user").val("");
},
})
.keypress(function(e) {
// when pressing enter check if the value is valid, otherwise set to null
if (e.which == 13) {
if ($.inArray($(this).val(), json) == -1)
$(this).val("");
}
});
*/
/*
$.each(json, function(i, user) {
$("select#dt-users").append(
$("
")
.text(user.Username)
.val(user.GamerHandle)
.attr("title", user.Username + " :: " + user.GamerHandle)
);
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
}
});
*/
}
/*
function populateDeathmatches() {
// Social Club Freemode Matches
$.ajax({
url: config.restHost + config.SCFreemodeNames,
type: "GET",
data: {type: "DEATHMATCH"},
dataType: "json",
async: false,
success: function(deathmatches, textStatus, jqXHR) {
$.each(deathmatches, function(i, deathmatch) {
$("select#deathmatch-list").append(
$('
')
.text(deathmatch.Name + " (" + deathmatch.Creator + ")")
.val(deathmatch.UGCIdentifier)
.attr("title", deathmatch.Name + " (" + deathmatch.Creator + ") : " + deathmatch.Description)
//.attr("selected", function() {
// return (pageData && pageData.deathmatch_list == deathmatch.UGCIdentifier) ? "selected" : false;
//})
)
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
},
complete: function() {
}
});
}
*/
/* Retreives the builds and populates given select element
*
* Available options {
* elementId - The DOM element ID
* async - the ajax request sync mode
* }
*
*/
function populateAllBuilds(options) {
$.ajax({
url: config.restHost + config.buildsAll,
type: "GET",
data: {},
dataType: "json",
async: options.async,
success: function(json, textStatus, jqXHR) {
var builds = json.Items.sort(sortByIdentifierDesc);
// Filter out builds without GameVersion
builds.filter(function(b) {return b.GameVersion});
/*
if (options.elementId == "build") {
$("select#" + options.elementId).append(
$("
")
.text(config.buildAllText)
.val("")
.attr("title", config.buildAllText)
);
}
*/
if (builds.length > 0) {
$("select#" + options.elementId).append(
$("
")
.text(config.buildAliasText)
.val(builds[0].Identifier)
.attr("title", config.buildAliasText)
);
}
$.each(builds, function(i, build) {
$("select#" + options.elementId).append(
$("
")
.text(build.Identifier)
.val(build.Identifier)
.attr("title", build.Identifier)
);
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
},
complete: function() {}
});
}
function getAllBuilds() {
var builds = [];
$.ajax({
url: config.restHost + config.buildsAll,
type: "GET",
data: {},
dataType: "json",
async: false,
success: function(json, textStatus, jqXHR) {
builds = json.Items.map(function(b) {return b.Identifier});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
},
complete: function() {}
});
return builds;
}
function getHeaderBuilds() {
var builds = ($("#builds").val() ? $("#builds").val().join() : null);
/*
var availableBuilds = $.map($("#builds option"), function(e) {
return e.value;
});
if ($("#builds").val()) {
if (($("#builds").val().length == 1) && $("#builds").val()[0] == -1) // if latest only is select
builds = (availableBuilds.length > 1) ? availableBuilds[1] : null; // 0 is -1, 1 is actual latest
else
builds = $("#builds").val().filter(function(d) {return (d != -1);}).join(",");
}
else
builds = null;
*/
//console.log(builds);
return builds;
}
function getHeaderBuild() {
var build = ($("#build").val() ? $("#build").val() : null);
/*
var availableBuilds = $.map($("#build option"), function(e) {
return e.value;
});
//console.log(availableBuilds);
if ($("#build").val()) {
if ($("#build").val() == -1) // if latest only is select
build = (availableBuilds.length > 1) ? availableBuilds[1] : null; // 0 is -1, 1 is actual latest
else
build = $("#build").val();
}
else
build = null;
*/
return build;
}
function populateDatesBuildsOptions(elementId) {
var dfunc = {
getValue: function(d) {return d.Value},
getTitle: function(d) {return d.Name},
getText: function(d) {return d.Name},
};
populateSelectElements([elementId], config.datesBuildsOptions, dfunc);
$("#" + elementId).change(function() {updateDateBuildFields(elementId); });
}
function updateDateBuildFields(elementId) {
$("#" + elementId).parent().parent().children("fieldset").each(function(i, f) {
if ($("#" + elementId).val() == 0) {
$(f).removeClass("hidden"); // Show all
if (i == 2) // hide cwp
$(f).addClass("hidden");
}
else {
$(f).addClass("hidden"); // Hide all
if (i == ($("#" + elementId).val() - 1)) // show selected
$(f).removeClass("hidden");
}
});
};
/*
function convertBuildsXml(xml) {
var elementsArray = [];
$(xml).find("Build").each(function() {
var build = {
Id: Number($(this).find("Id").text()),
CreatedOn: $(this).find("CreatedOn").text(),
ModifiedOn: $(this).find("ModifiedOn").text(),
Identifier: ($(this).find("Identifier").text()),
HasAssetStats: ($(this).find("HasAssetStats").text() == "true"),
HasProcessedStats: ($(this).find("HasProcessedStats").text() == "true"),
HasAutomatedEverythingStats: ($(this).find("HasAutomatedEverythingStats").text() == "true"),
HasAutomatedMapOnlyStats: ($(this).find("HasAutomatedMapOnlyStats").text() == "true"),
HasMagDemoStats: ($(this).find("HasMagDemoStats").text() == "true"),
HasMemShortfallStats: ($(this).find("HasMemShortfallStats").text() == "true"),
HasShapeTestStats: ($(this).find("HasShapeTestStats").text() == "true"),
};
elementsArray.push(build);
});
//console.log(elementsArray);
return elementsArray;
}
*/
/*
function populateBuildConfigs() {
$.ajax({
url: config.restHost + config.buildConfigsAll,
type: "GET",
data: {},
dataType: "xml",
async: false,
success: function(xml, textStatus, jqXHR) {
var buildConfigs = convertBuildConfigsXml(xml);
$.each(buildConfigs, function(i, buildConfig) {
$("select#build-config").append(
$("
")
.text(buildConfig.Value)
.val(buildConfig.Value)
);
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
},
complete: function() {}
});
}
function convertBuildConfigsXml(xml) {
var elementsArray = [];
$(xml).find("BuildConfig").each(function(){
var buildConfig = {
Value: $(this).find("Value").text()
};
elementsArray.push(buildConfig);
});
return elementsArray;
}
*/
function populateCutscenes() {
$.ajax({
url: config.restHost + config.cutscenesAll,
type: "GET",
data: {},
dataType: "xml",
async: false,
success: function(xml, textStatus, jqXHR) {
var cutscenes = convertCutscenesXml(xml)
.sort(function(a, b) {return ((a.Name > b.Name) ? 1 : -1)});
$.each(cutscenes, function(i, cutscene) {
$("select#cutscene").append(
$("
")
.text(cutscene.Name)
.val(cutscene.Name)
.attr("title", cutscene.Name)
);
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
},
complete: function() {}
});
}
function convertCutscenesXml(xml) {
var elementsArray = [];
$(xml).find("Cutscene").each(function(){
var element = {
Id: $(this).find("Id").text(),
CreatedOn: $(this).find("CreatedOn").text(),
ModifiedOn: $(this).find("ModifiedOn").text(),
Name: $(this).find("Name").text(),
Identifier: $(this).find("Identifier").text(),
Duration: $(this).find("Duration").text(),
};
elementsArray.push(element);
});
return elementsArray;
}
/* End of xml? */
function getPlatforms() {
var obj = {
url: config.restHost + config.platformsEnums,
data: {},
method: "GET",
dataType: "json",
async: false,
};
return getAjaxData(obj);
}
function populatePlatforms() {
allPlatforms = getPlatforms().slice(1);
//console.log(allPlatforms);
var dfunc = {
getValue: function(d) {return d.Name},
getTitle: function(d) {return d.Name},
getText: function(d) {return d.Name},
};
populateSelectElements(["platform"], allPlatforms, dfunc);
populateSelectElements(["platforms"], allPlatforms, dfunc);
}
function getRosPlatforms() {
if (!rosPlatforms) {
var obj = {
url: config.restHost + config.rosPlatformsEnums,
data: {},
method: "GET",
dataType: "json",
async: false,
};
rosPlatforms = getAjaxData(obj);
}
return rosPlatforms;
}
function getRosPlatformsDict() {
if (!rosPlatformsDict) {
rosPlatformsDict = {};
getRosPlatforms().map(function(d) {rosPlatformsDict[d.Value] = d.Name});
}
return rosPlatformsDict;
}
function populateROSPlatforms() {
var rosPlatforms = getRosPlatforms();
var dfunc = {
getValue: function(d) {return d.Name},
getTitle: function(d) {return d.Name},
getText: function(d) {return d.Name},
};
populateSelectElements(["rosplatform"], rosPlatforms, dfunc);
populateSelectElements(["rosplatforms"], rosPlatforms, dfunc);
}
function getGameTypes() {
var obj = {
url: config.restHost + config.gameTypesEnums,
data: {},
method: "GET",
dataType: "json",
async: false,
};
return getAjaxData(obj);
}
function populateGameTypes() {
var gameTypes = getGameTypes();
var dfunc = {
getValue: function(d) {return d.Name},
getTitle: function(d) {return d.Name},
getText: function(d) {return d.Name},
};
populateSelectElements(["game-types"], gameTypes, dfunc);
}
function populateCharacters() {
var dfunc = {
getValue: function(d) {return d.Value},
getTitle: function(d) {return d.Name},
getText: function(d) {return d.Name},
};
//populateSelectElements(["characters"], config.characters, dfunc);
populateSelectElements(["character"], config.characters, dfunc);
}
function getBuildConfigs() {
var obj = {
url: config.restHost + config.buildConfigsEnums,
data: {},
method: "GET",
dataType: "json",
async: false,
};
return getAjaxData(obj);
}
function populateBuildConfigs() {
var buildConfigs = getBuildConfigs();
var dfunc = {
getValue: function(d) {return d.Name},
getTitle: function(d) {return d.Name},
getText: function(d) {return d.Name},
};
populateSelectElements(["build-config"], buildConfigs, dfunc);
}
function getFileTypes() {
var obj = {
url: config.restHost + config.fileTypesEnums,
data: {},
method: "GET",
dataType: "json",
async: false,
};
return getAjaxData(obj);
}
function populateFileTypes() {
var fileTypes = getFileTypes();
var dfunc = {
getValue: function(d) {return d.Name},
getTitle: function(d) {return d.Name},
getText: function(d) {return d.Name},
};
populateSelectElements(["file-types"], fileTypes, dfunc);
}
function populateGameTimes() {
var dfunc = {
getValue: function(d) {return d.Value},
getTitle: function(d) {return d.Name},
getText: function(d) {return d.Name},
};
populateSelectElements(["game-times"], config.gameTimes, dfunc);
}
function getDateGrouping() {
var obj = {
url: config.restHost + config.dateGroupingEnums,
data: {},
method: "GET",
dataType: "json",
async: false,
};
return getAjaxData(obj);
}
function populateDateGrouping() {
var dateGrouping = getDateGrouping();
var dfunc = {
getValue: function(d) {return d.Name},
getTitle: function(d) {return (d.FriendlyName) ? d.FriendlyName : d.Name},
getText: function(d) {return (d.FriendlyName) ? d.FriendlyName : d.Name},
};
populateSelectElements(["date-grouping"], dateGrouping, dfunc);
}
function getMatchTypes() {
if (!matchTypes) {
var obj = {
url: config.restHost + config.matchTypesEnums,
data: {},
method: "GET",
dataType: "json",
async: false,
};
matchTypes = getAjaxData(obj);
}
return matchTypes;
}
function getMatchTypesDict() {
if (!matchTypesDict) {
matchTypesDict = {};
getMatchTypes().map(function(d) {matchTypesDict[d.Value] = (d.FriendlyName) ? d.FriendlyName : d.Name});
}
return matchTypesDict;
}
function populateMatchTypes() {
var matchTypes = getMatchTypes();
matchTypes.unshift({
"FriendlyName": "None",
"Name" : "",
"Value": null
});
var dfunc = {
getValue: function(d) {return d.Name},
getTitle: function(d) {return (d.FriendlyName) ? d.FriendlyName : d.Name},
getText: function(d) {return (d.FriendlyName) ? d.FriendlyName : d.Name},
};
populateSelectElements(["match-type", "match-types"], matchTypes, dfunc);
}
function getMatchSubTypesDict() {
var matchTypesDict = getMatchTypesDict();
if (!matchSubTypesDict) {
matchSubTypesDict = {};
$.each(matchTypes, function(matchKey, matchType) {
if (config.matchSubTypesEnumsDict.hasOwnProperty(matchType.Name)) {
var obj = {
url: config.restHost + config.matchSubTypesEnumsDict[matchType.Name],
data: {},
method: "GET",
dataType: "json",
async: false,
};
var subTypeDict = {};
getAjaxData(obj).map(function(d) {subTypeDict[d.Value] = (d.FriendlyName) ? d.FriendlyName : d.Name});
matchSubTypesDict[matchKey] = subTypeDict;
}
});
//console.log(matchSubTypesDict);
}
return matchSubTypesDict;
}
function getFreemodeCategories() {
if (!freemodeCategories) {
var obj = {
url: config.restHost + config.freemodeCategoriesEnums,
data: {},
method: "GET",
dataType: "json",
async: false,
};
freemodeCategories = getAjaxData(obj);
}
return freemodeCategories;
}
function getFreemodeCategoriesDict() {
if (!freemodeCategoriesDict) {
freemodeCategoriesDict = {};
getFreemodeCategories().map(function(d) {freemodeCategoriesDict[d.Value] = (d.FriendlyName) ? d.FriendlyName : d.Name});
}
return freemodeCategoriesDict;
}
function populateFreemodeCategories() {
var freemodeCategories = getFreemodeCategories();
var dfunc = {
getValue: function(d) {return d.Name},
getTitle: function(d) {return (d.FriendlyName) ? d.FriendlyName : d.Name},
getText: function(d) {return (d.FriendlyName) ? d.FriendlyName : d.Name},
};
populateSelectElements(["freemode-categories"], freemodeCategories, dfunc);
freemodeCategories.unshift({FriendlyName: "All", Name: ""});
populateSelectElements(["freemode-category"], freemodeCategories, dfunc);
}
function getJobResults() {
if (!jobResults) {
var obj = {
url: config.restHost + config.getJobResultsEnums,
data: {},
method: "GET",
dataType: "json",
async: false,
};
jobResults = getAjaxData(obj);
}
return jobResults;
}
function getJobResultsDict() {
if (!jobResultsDict) {
jobResultsDict = {};
getJobResults().map(function(d) {jobResultsDict[d.Value] = (d.FriendlyName) ? d.FriendlyName : d.Name});
}
return jobResultsDict;
}
function populateUGCStatus() {
var freemodeCategories = getFreemodeCategories();
var dfunc = {
getValue: function(d) {return d.Value},
getTitle: function(d) {return d.Name},
getText: function(d) {return d.Name},
};
populateSelectElements(["freemode-ugcstatus"], config.ugcStatus, dfunc);
}
function populateResolutions() {
var clipCategories = getClipCategories();
var dfunc = {
getValue: function(d) {return d},
getTitle: function(d) {return d},
getText: function(d) {return d},
};
populateSelectElements(["resolution"], config.resolutionsAll, dfunc);
}
function getClipCategories() {
var obj = {
url: config.restHost + config.clipCategoriesEnums,
data: {},
method: "GET",
dataType: "json",
async: false,
};
return getAjaxData(obj);
}
function populateClipCategories() {
var clipCategories = getClipCategories();
var dfunc = {
getValue: function(d) {return d.Name},
getTitle: function(d) {return d.Name},
getText: function(d) {return d.Name},
};
populateSelectElements(["clip-categories"], clipCategories, dfunc);
populateSelectElements(["clip-category"], clipCategories, dfunc);
}
function getPlaythroughsUsers() {
var obj = {
url: config.restHost + config.playthroughsUsers,
data: {},
method: "GET",
dataType: "json",
async: false,
};
return getAjaxData(obj);
}
function getPlaythroughUsersAsDict() {
var dict = {};
getPlaythroughsUsers().map(function(d) {
//console.log(d.GamerHandle + " " + d.Username);
if (!d.GamerHandle)
return;
if (!dict.hasOwnProperty(d.GamerHandle))
dict[d.GamerHandle] = d.Username;
});
return dict;
}
function getMissionHashes() {
var obj = {
url: config.webHost + config.missionHashesCSV,
data: {},
method: "GET",
dataType: "text",
async: false,
};
var dict = {};
getAjaxData(obj).split("\n").map(function(d) {
var pair = d.split(",");
dict[pair[0]] = pair[1];
});
//console.log(dict);
return dict;
}
function getRadioHashes() {
var obj = {
url: config.webHost + config.radioHashesCSV,
data: {},
method: "GET",
dataType: "text",
async: false,
};
var dict = {};
getAjaxData(obj).split("\n").map(function(d) {
var pair = d.split(",");
dict[pair[0]] = pair[1];
});
//console.log(dict);
return dict;
}
function getWeaponHashes() {
var obj = {
url: config.webHost + config.weaponHashesCSV,
data: {},
method: "GET",
dataType: "text",
async: false,
};
var dict = {};
getAjaxData(obj).split("\n").map(function(d) {
var pair = d.split(",");
dict[pair[0]] = pair[1];
});
//console.log(dict);
return dict;
}
function getWeaponStatnames() {
var obj = {
url: config.webHost + config.weaponStatnamesCSV,
data: {},
method: "GET",
dataType: "text",
async: false,
};
var dict = {};
getAjaxData(obj).split("\n").map(function(d) {
var pair = d.split(",");
dict[pair[0]] = {
"Name" : pair[0],
"FriendlyName" : pair[1],
};
});
//console.log(dict);
return dict;
}
function getWeaponsAll() {
var obj = {
url: config.restHost + config.weaponsAll,
data: {},
method: "GET",
dataType: "json",
async: false,
};
return getAjaxData(obj);
}
function getWeaponCategoriesEnums() {
var obj = {
url: config.restHost + config.weaponCategoriesEnums,
data: {},
method: "GET",
dataType: "json",
async: false,
};
return getAjaxData(obj);
}
function getExpenditureCategoriesEnums() {
var obj = {
url: config.restHost + config.expenditureCategoriesEnums,
data: {},
method: "GET",
dataType: "json",
async: false,
};
return getAjaxData(obj);
}
function getVehicleHashes() {
var obj = {
url: config.restHost + config.vehiclesAll,
data: {},
method: "GET",
dataType: "json",
async: false,
};
var dict = {};
getAjaxData(obj).map(function(d) {
dict[d.Identifier] = d.FriendlyName;
});
//console.log(dict);
return dict;
}
/*
*
* Generic Function to replace the ones above
*
* */
/*
datafunctions = {
getValue: function(d) {return d....},
getTitle: function(d) {return d....},
getText: function(d) {return d....},
}
data can come from getAjaxData
*/
function populateSelectElements(elementIds, data, dataFunctions) {
$.each(elementIds, function(i, elementId) {
//console.log(elementId);
$.each(data, function(j, d) {
//console.log(dataFunctions.getText(d));
var option = $("
");
option.text(dataFunctions.getText(d))
.val(dataFunctions.getValue(d))
.attr("title", dataFunctions.getTitle(d));
/* This will not work on IE
if (dataFunctions.onClick) {
option.on("click", function() {dataFunctions.onClick(d);})
}
*/
$("select#" + elementId).append(option);
});
if (dataFunctions.onClick) {
$("select#" + elementId).on("click", function() {
dataFunctions.onClick(data[$("select#" + elementId)[0].selectedIndex]);
});
}
if (dataFunctions.onChange) {
$("select#" + elementId).on("change", function() {
dataFunctions.onChange(data[$("select#" + elementId)[0].selectedIndex]);
});
}
});
}
/*
datafunctions = {
getValue: function(d) {return d....},
getText: function(d) {return d....},
getTitle: function(d) {return d....},
getChildren: function(d) {return d....},
onClick: function() {return d...}
};
Data can come from getAjaxData
*/
function populateHierarchicalElements(elements, data, dataFunctions) {
$.each(elements, function(i, element) {
var ul = $("
");
$.each(data, function(j, d) {
var li = $("
");
li.append(
$("
")
.text(dataFunctions.getText(d))
.val(dataFunctions.getValue(d))
.attr("title", dataFunctions.getTitle(d))
.click(function() {
dataFunctions.onClick(dataFunctions.getValue(d), dataFunctions.getText(d));
})
.addClass("hand")
);
populateHierarchicalElements(li, dataFunctions.getChildren(d), dataFunctions);
li.appendTo(ul);
});
if (ul.children("li").length > 0)
ul.appendTo(element);
});
}
/**
* object has the format of
* object = {
* url: ...,
* data: {...},
* method: GET/POST,
* dataType: ...,
* contentType: ...,
* async: true/false,
* }
*/
function getAjaxData(object) {
var result = [];
$.ajax({
url: object.url,
type: object.method,
data: object.data,
dataType: object.dataType,
contentType: object.contentType,
async: object.async,
cache: object.cache,
success: function(data, textStatus, jqXHR) {
result = data;
},
error: function (xhr, ajaxOptions, thrownError) {
console.error(this.url + "\n" + ajaxOptions + " " + xhr.status + " " + thrownError);
},
complete: function() {}
});
return result;
}
/* END of retrieve and populate functions */
function cleanGraph(id) {
var svg = d3.select("#" + id + " svg");
svg.selectAll("g")
.transition()
.style("opacity", 0.01)
.remove();
svg.selectAll("text")
.transition()
.style("opacity", 0.01)
.remove();
if (typeof window.onresize === "function")
window.onresize = null;
}
// Function for key delay searches
var typewatch = function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
}
}();
var commas = function(d) { return d3.format(",")(d); };
var commasFixed2 = function(d) { return d3.format(",")(d.toFixed(2)); };
var commasFixed = function(d, n) { return d3.format(",")(d.toFixed((n) ? n : 0)); };
var cashCommasFixed = function(d, n) { return "$ " + commasFixed2(d, n); };
var round2 = function(d) {return d3.round(d, 2); };
function msTicks2UnixTime(ticks) {
/*
* MS ticks counting start at 12:00:00 midnight, Jan 1, 0001
* Unix Time starts at midnight Jan 1, 1970 (in milliseconds)
* 1 tick is 10000 milliseconds
* There are 621355968000000000 ticks between 01/01/0001 and 01/01/1970
*/
return ((ticks - 621355968000000000) / 10000);
}
function msTicks2Secs(ticks) {
/* 1 tick is 10000 milliseconds */
return (ticks / (10000 * 1000));
}
function getDateString(dateElementId, isUTC) {
var dateString = $("#" + dateElementId).val();
if (!dateString)
return null;
if (isUTC) {
dateString = new Date(config.dateInputUTCFormat.parse(dateString)).toISOString();
}
else
dateString = new Date(config.dateInputFormat.parse(dateString)).toISOString();
return dateString;
}
// Returns the date object from a json date string
function parseJsonDate(jsonDate) {
//var dateRe = new RegExp("^/Date\\((\\d+)[\\+\\d]*\\)/$");
//var constructor = date.replace(dateRe, "new Date($1)");
//if (constructor == date) {
// throw 'Invalid serialized DateTime value: "' + date + '"';
//}
//var date = new Date(parseInt(jsonDate.slice(6, -1), 10));
if (!jsonDate)
return "";
var epochTime;
var jsonDateString = jsonDate.slice(6, -2);
if (jsonDateString.indexOf("+") != -1) {
var dates = jsonDateString.split("+");
epochTime = parseInt(dates[0])
+ ((dates[1]) ? Number(dates[1].slice(0, 2))*config.anHourInMillisecs : 0);
}
else if (jsonDateString.indexOf("-") != -1) {
var dates = jsonDateString.split("-");
epochTime = parseInt(dates[0])
- ((dates[1]) ? Number(dates[1].slice(0, 2))*config.anHourInMillisecs : 0);
}
else
epochTime = parseInt(jsonDateString);
return new Date(epochTime);
};
// Return the diff of two date strings in secs
function dateStringsDiffInSecs(dateString1, dateString2) {
var date1 = new Date(dateString1),
date2 = new Date(dateString2);
if (isValidDate(date1) && (isValidDate(date2)))
return datesDiffInSecs(date1, date2);
else
return 0;
}
// Return the difference of two day objects in secs
function datesDiffInSecs(date1, date2) {
// Convert to unix time millisecs and subtract; then convert to secs
return ((date1.getTime() - date2.getTime()) / 1000);
}
// Return only the date in utc from a datetime string
function extractDate(dateString) {
var date = new Date(dateString);
if (isValidDate(date))
return date.getFullYear() +"-"+ zeros(date.getMonth()+1) +"-"+ zeros(date.getDate());
else
return null;
}
function isValidDate(d) {
if (Object.prototype.toString.call(d) !== "[object Date]")
return false;
return !isNaN(d.getTime());
}
var zeros = d3.format("02d");
function truncate(string, chars) {
if (chars < 3) chars += 3;
return string.slice(0, chars-3) + "...";
}
function formatSecs(secs) {
var h = zeros(Math.floor(secs / 3600));
var m = zeros(Math.floor((secs % 3600) / 60));
var s = zeros(Math.floor((secs % 3600) % 60));
return (h + ":" + m + ":" + s);
}
function formatMins(mins) {
return formatSecs(mins*60);
}
function formatSecsWithDays(secs) {
var d = zeros(Math.floor(secs / 86400));
var h = zeros(Math.floor((secs % 86400) / 3600));
var m = zeros(Math.floor(((secs % 86400) % 3600) / 60));
var s = zeros(Math.floor(((secs % 86400) % 3600) % 60));
return (d + ":" + h + ":" + m + ":" + s);
}
function frameTimeToFPS(frameTime) {
return (frameTime) ? (1000 / frameTime) : frameTime;
}
function capitaliseString(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function toUTCStringWOSecs(d) {
return d.toUTCString().replace(/:\d+ /g, " ");
}
function formatPercentage(value, total) {
return (commasFixed2((value/total)*100));
}
/* CSV operations*/
function exportToCSV(columnsArray, rowsArray, frameId, filename) {
var Columns = [{ ColumnNames : columnsArray.map(function(d) {return ("\"" + d +"\""); }).join(",") }];
var Rows = [];
rowsArray.map(function(r) {
Rows.push({row : r.map(function(d) {return ("\"" + d +"\""); }).join(",")});
});
var csvData = { "Columns": Columns, "Rows": Rows };
$("#" + frameId).contents().find("#CsvData")[0].value = JSON.stringify(csvData);
$("#" + frameId).contents().find("#CsvFilename")[0].value = filename;
return;
}
function addCSVButton(elementId, frameId, onClickFunction) {
$("#" + elementId)
.append(
$("")
.attr("id", frameId)
.addClass("csv-frame")
.attr("src", config.webHost + config.csvBackend)
.load(function() {
var iFrameForm = $(this).contents().find("form");
if (iFrameForm.size() == 0)
return;
$(iFrameForm)
.find("#ExportCSVButton")
.addClass("red-button hand")
.attr("onCLick", onClickFunction)
})
)
};
function getCSVFilename(extra) {
var pValues = config.headerOptions[headerAndFilters.headerType].getParamValues();
//console.log(pValues["Pairs"]);
var dates = "";
dates += (pValues["Pairs"]["StartDate"]) ? extractDate(pValues["Pairs"]["StartDate"]) : "";
dates += (pValues["Pairs"]["EndDate"]) ? ("_" + extractDate(pValues["Pairs"]["EndDate"])) : "";
var builds = (pValues["Pairs"]["BuildIdentifiers"]) ? (pValues["Pairs"]["BuildIdentifiers"]).split(",").join("-") : "";
var cpw = (pValues["Pairs"]["CompanywidePlaytestId"]) ? (pValues["Pairs"]["CompanywidePlaytestId"]) : "";
return (encodeURI(($("#content-title").text() + ((extra) ? (" : " + extra) : "")).replace(/\s|,/g, "_"))
+ ((dates) ? ("_" + dates + "_") : dates)
+ ((builds) ? ("_" + builds + "_") : builds)
+ ((cpw) ? ("_" + cpw + "_") : cpw)
+ ".csv");
}
function fillEmptyResults(resultArray, metric, size) {
var extraItems = [];
$.each(resultArray, function(i, resultIem) {
if ((i > 0) && ((resultIem[metric]) - resultArray[i-1][metric] > size)) {
var repeat = (resultIem[metric] - resultArray[i-1][metric] -size )/size;
for(var j=1; j<=repeat; j++) {
var newItem = {};
$.each(resultArray[i-1], function(key, value) {
newItem[key] = 0;
});
newItem[metric] = resultArray[i-1][metric] + size*j;
extraItems.push(newItem);
}
}
});
if (extraItems) {
resultArray = (resultArray.concat(extraItems)).sort(
function(a, b) {
return (a[metric] >= b[metric]) ? 1 : -1;
});
}
return resultArray;
}
/*
function addCSVButton(elementId, onClickFunction) {
$("#" + elementId).append(
$("")
.attr("type", "button")
.attr("id", "export-csv")
.attr("name", "export-csv")
.attr("title", "Export to CSV")
.val("Export Data to CSV")
.css("float", "right")
.addClass("red-button hand")
.click(onClickFunction)
);
}
*/
// convert xml functions
function convertGametypesXml(xml) {
var elementsArray = [];
$(xml).find("GameType").each(function(){
var gametype = {
Value: $(this).find("Value").text()
};
elementsArray.push(gametype);
});
return elementsArray;
}
function getExportUsersList(xml) {
var elementsArray = [];
$(xml).find("ExportUser").each(function(){
elementsArray.push($(this).text());
});
return elementsArray;
}