/* Minification failed. Returning unminified contents.
(658,13-23): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: hasZipCode
*/
var Dell = window.Dell || {};
Dell.Controllers = Dell.Controllers || {}
Dell.Controllers.vue = {};
(function ($, window, document) {
(function () {
'use strict';
var vueApp = {},
components = {},
$this = this,
debug = true,
hasPerf = Dell.perfmetrics;
Vue.config.devtools = debug;
Vue.config.debug = debug;
$.extend(jQuery.expr[':'], {
attrContains: function (el, idx, sel) {
var attrs = el.attributes;
for (var i = 0; i < attrs.length; i++) {
if (attrs[i].nodeName.toLowerCase().indexOf(sel[3].toLowerCase()) != -1)
return true;
}
return false;
}
});
var testExp = function (exp, n, cn) {
var hasCon = (console && console.log);
try {
eval(exp);
} catch (e) {
var msg = e.toString().toLowerCase();
if (hasCon && (msg.indexOf('referenceerror') === -1 && msg.indexOf('function') === -1)) {
//ignore undefined functions -- most likely from specific mixin functions/component methods
console.log('%cVUE Expression Error: Inline Expression from [' + cn + '] ' + n + ' = ' + exp + " \nError Message -- " + e, "color: red;");
//return;
}
}
//if (hasCon)
// console.log('TEST VUE Expression --> ' + n + ' = ' + exp);
};
var testExpressions = function (c) {
var item = Dell.Services.DataModel.Stacks[0];
for (var i = 0; i < c.length; i++) {
if (components[c[i]]) {
$(components[c[i]].template).find('[v-if],:attrContains("v-bind")').each(function () {
$this = $(this);
$.each(this.attributes, function (idx, attr) {
if (attr.name == 'v-if' || attr.name.indexOf('v-bind') != -1)
testExp(attr.value, attr.name, c[i]);
});
});
}
}
};
$this.register = function (k, el, d, op) {
if (hasPerf)
Dell.perfmetrics.start('Vue.Register.' + k);
vueApp[k] = new Vue({
el: el,
data: d,
components: (op && op.components ? op.components : {}),
methods: (op && op.methods ? op.methods : {})
});
Vue.nextTick(function () {
if (hasPerf)
Dell.perfmetrics.end('Vue.Register.' + k);
}(k));
//checkCache(k);
};
this.newComponent = function (a, co, reg) {
if (typeof a !== 'undefined') {
var n = !$.isArray(a) ? [{ name: a, co: co }] : a;
for (var i = 0; i < n.length; i++) {
var co = n[i].co;
if (co.template && (typeof co.template !== 'string')) {
//work with a cloned copy of the template
co.template = co.template.cloneNode(true);
if (co.template.hasAttribute('inline-template'))
cleanInlineTmpl(co, true);
else
co.template = getComponentTemplate(co);
}
if (co.components && $.isArray(co.components)) {
var c = {};
for (var i2 = 0; i2 < co.components.length; i2++)
c[co.components[i2]] = Dell.Controllers.vue.getComponent(co.components[i2]);
//if (debug)
// testExpressions(co.components); //only for debugging
co.components = c;
}
// Save the reuseable constructor options
components[n[i].name] = co;
// Register the constructor with corresponding id
if ((typeof reg !== 'undefined' && reg) || (typeof n[i].register !== 'undefined' && n[i].register))
Vue.component(n[i].name, components[n[i].name]);
}
}
};
function cleanInlineTmpl(co, ch) {
var i = 0;
var $el = $(co.template);
//clean children (include child attributes + remove duplicates within for each loops)
//remove duplicate children whithin v-for containers.
$el.find('[only-child]').not(':first-child').remove();
//remove static attributes (any attributes that we want bound via v-bind:)
$el.find(':attrContains("v-bind")').addBack($el).each(function () {
for (i = this.attributes.length - 1; i >= 0; i--) {
if (this.attributes[i].name.indexOf('v-bind:') === 0) {
var stcNm = this.attributes[i].name.replace('v-bind:', '');
if (this.hasAttribute(stcNm))
this.removeAttribute(stcNm);
}
}
});
//remove any v-hide classes used for initial rendering
$el.find('.v-hide').addBack($el).removeClass('v-hide');
//return $el[0];
//remove predefined child component templates and needless v- attributes binding (cause needless exponential re-rendering)
if (co.components) {
for (i = 0; i < co.components.length; i++) {
var $childCo = $el.find(co.components[i]);
if ($childCo.length !== 0)
$childCo.empty();
}
}
}
function getComponentTemplate(co) {
if (co.template) {
cleanInlineTmpl(co, true);
var tmplt = co.template.outerHTML;
//co.template.innerHTML = '';
return tmplt;
}
return '';
}
this.getComponent = function (n) {
if (components[n])
return components[n];
else
return undefined;
};
this.isDefined = function (k) {
return typeof vueApp[k] !== 'undefined';
};
var checkCache = function (k) {
var key = 'VueTimer-' + k;
if (window.localStorage && localStorage[key])
vueApp[k].timers = JSON.parse(localStorage.getItem(key));
else
vueApp[k].timers = [];
};
this.setVMData = function (k, p, d) {
if (vueApp[k]) {
//vueApp[k].timers.push(performance.now());
if (hasPerf)
Dell.perfmetrics.start('Vue.Update.' + k);
Vue.set(vueApp[k], p, d);
vueApp[k].$forceUpdate();
Vue.nextTick(function () {
//var idx = vueApp[k].timers.length - 1;
//vueApp[k].timers[idx] = (performance.now() - vueApp[k].timers[idx]);
if (hasPerf)
Dell.perfmetrics.end('Vue.Update.' + k);
}(k));
}
};
this.getAvgTime = function (k) {
if (vueApp[k]) {
var avg = 0;
var c = vueApp[k].timers.length;
for (var i = 0; i < c; i++) {
avg += vueApp[k].timers[i];
}
avg = avg / c;
if (typeof console !== 'undefined' && typeof console.log !== 'undefined')
console.log(k + ' average render time (' + c + ' samples) = ' + avg);
if (typeof localStorage !== 'undefined')
window.localStorage.setItem('VueTimer-' + k, JSON.stringify(vueApp[k].timers));
return avg;
} else {
return 0;
}
};
this.getVMData = function (k) {
if (vueApp[k])
return vueApp[k].$data;
else
return undefined;
};
}).call(Dell.Controllers.vue);
})(jQuery, window, document);
var Dell = window.Dell || {};
Dell.Services = Dell.Services || {}
Dell.Services.personalization = {};
(function($, win, doc) {
(function () {
var $this = this;
$this.userContext = {};
$this.apiUrl = "";
$this.pageSize = 150;
$this.promotionMessage = '';
$this.personalizationApiUrl = function () {
var urlString = $this.apiUrl;
var userContext = $this.getUserContext();
var skus = $this.getSkus();
var category = $this.getCategory();
var pageSize = $this.getPageSize();
if (userContext !== null && (typeof userContext !== "undefined") && userContext.toString().trim() !== "") {
urlString = urlString + userContext;
}
if (skus !== null && (typeof skus !== "undefined") && skus.toString().trim() !== "") {
urlString = urlString + skus;
}
if (category !== null && (typeof category !== "undefined") && category.toString().trim() !== "") {
urlString = urlString + category;
}
if (pageSize !== null && (typeof pageSize !== "undefined") && pageSize.toString().trim() !== "") {
urlString = urlString + pageSize;
}
return urlString;
};
$this.setSkus = function (stacks) {
$this.skus = [];
for (var i = 0; i < stacks.length; i++) {
if (stacks[i].Stack.Sku.Value.toLowerCase().trim() !== "") {
$this.skus.push("sku=" + stacks[i].Stack.Sku.Value.toLowerCase() + "&");
}
}
$this.skus = $this.skus.join("");
if ($this.skus.length > 0) {
$this.skus = $this.skus.substring(0, $this.skus.length - 1);
}
};
$this.getSkus = function () {
return $this.skus;
};
$this.getCategory = function () {
return "&category=" + Dell.Metrics.sc.categoryid;
}
$this.getPageSize = function () {
return "&page_size=" + $this.pageSize;
}
$this.getUserContext = function () {
return '{0}/{1}/{2}/{3}?'.
format($this.userContext.Country, $this.userContext.Language, $this.userContext.CustomerSet, $this.userContext.Segment);
};
$this.setSku = function (sku) {
$this.skus = '';
if (sku) {
$this.skus = "sku=" + sku;
}
}
/* TODO: Currently, a good amount of JS for accessories is in AccessoryProductDetail.cshtml partial.
* We eventually need to move that out to a separate file.
* This function/AJAX will need to be moved out as well when SNP PD page gets Vue-ified to its own controller.
* An ideal solution would be to make this a directive where the call is made and the messages are applied at page load.
*/
$this.getPromotionMessage = function (url, uc, sku, el, messageEl) {
$this.apiUrl = url;
$this.userContext = uc;
$this.setSku(sku);
Dell.Services.httpGetService.getData($this.personalizationApiUrl()).success(function (data) {
if (data.offers) {
for (var i = 0; i < data.offers.length; i++) {
if (data.offers[i].messages) {
if (data.offers[i].messages[0].container == null || data.offers[i].messages[0].container == 'taglines') {
el.removeClass('hidden');
messageEl.html(data.offers[i].messages[0].text);
break;
}
}
}
} else {
console.log('API call was successful, but no messages were found for: ' + sku);
}
}).error(function () {
console.log('API call failed for personalization show promotion message for: ' + sku);
});
}
}).call(Dell.Services.personalization);
})(jQuery,window,document);;
var Dell = window.Dell || {};
Dell.Controllers = Dell.Controllers || {}
Dell.Controllers.diecut = {};
(function ($, window, document) {
(function () {
'use strict';
var $this = Dell.Controllers.diecut,
$rootScope = $('[data-scope]'),
$series = $rootScope.find(".series-Family"),
comoDieCuts = null,
comoLinkFrmt = ' {1}',
personalizationApiUrl = $rootScope.data('personapi'),
$dieCuts = $series.find('.dfs-merchandizing-die-cut'),
categoryName = $rootScope.attr('data-cat-name'),
personalizationService = Dell.Services.personalization;
$this.DieCutMessages = [];
var updateNabiscoInline = function(st) {
var $nabisco = $('.ups-promotion');
for (var i = 0, l = st.length; i < l; i++) {
var $n = $nabisco.filter('.stack-' + i);
if (st[i].Stack.PromotionMessage && st[i].Stack.PromotionMessage.Value != null && st[i].Stack.PromotionMessage.Value.length > 0) {
$n.find('.bug_text span').not('.bug_pointer').html(st[i].Stack.PromotionMessage.Value);
$n.closest('.ups-promotion').children().removeClass('v-hide');
}
}
};
$this.mapPersonalizationResults = function (data,stacks) {
if (typeof data != 'undefined') {
$this.DieCutMessages = [];
$.each(data.offers, function (key , offer) {
// this check is for the diecuts
if (offer.messages.length > 0) {
for (var j = 0; j < offer.messages.length; j++) {
// add only result page diecut message types to the diecutmessages scope array
if (offer.messages[j].container && offer.messages[j].container.indexOf("results page diecut") !== -1) {
// using last character of message's container field as the array index
var index = offer.messages[j].container.substring(offer.messages[j].container.length - 1);
$this.DieCutMessages[index - 1] = offer.messages[j].text;
}
}
}
//this check is for the taglines
//if to prevent any other types except for taglines
for (var i = 0; i < stacks.length; i++) {
if (stacks[i].Stack.Sku.Value.toLowerCase() === offer.sku) {
for (var j = 0; j < offer.messages.length; j++) {
if (!offer.messages[j].container || offer.messages[j].container.indexOf("taglines") !== -1) {
stacks[i].Stack.PromotionMessage.Value = offer.messages[j].text;
stacks[i].Options.ShowPromotion = true;
stacks[i].RenderPromotions = true;
stacks[i].Stack.DisplayPromotion = true;
Dell.Controllers.productstack.mapPersonalization = true; //map persona only once to prevent circular dependency
break;
}
}
}
}
});
if (Dell.Controllers.productstack.mapPersonalization) {
//prevent re-render on page load of entire vuestacks until personalized content is in separate component/controller
if ($('stackrow').length > 0)
updateNabiscoInline(stacks);
else
Dell.Controllers.productstack.updateStacks(stacks);
}
$this.handleDiecuts();
}
};
$this.getPersonalizedData = function (stacks) {
var lwpObj = {};
personalizationService.apiUrl = personalizationApiUrl;
try{ lwpObj = Dell.Transactional.buildLightweightProfile();}catch(e){}
personalizationService.userContext.Country = lwpObj.c;
personalizationService.userContext.Language = lwpObj.l;
personalizationService.userContext.Segment = lwpObj.s;
personalizationService.userContext.CustomerSet = lwpObj.cs;
if (typeof Dell.Services.DataModel !== 'undefined' && typeof Dell.Services.DataModel.Stacks !== 'undefined')
personalizationService.setSkus(stacks);
Dell.Services.httpGetService.getData(Dell.Services.personalization.personalizationApiUrl()).success(function (data) {
if (data.offers.length > 0) {
$this.mapPersonalizationResults(data,stacks);
} else {
$this.handleDiecuts();
}
}).error(function () {
$this.handleDiecuts();
});
};
$this.renderDiecut = function (stacks) {
if (personalizationApiUrl)
$this.getPersonalizedData(stacks);
else
$this.handleDiecuts();
}
$this.handleDiecuts = function() {
if ($rootScope.hasClass('results')) {
// injects text into die cut css found in web page
$(".result-page-die-cut").remove();
var diecut = $(".result-page-die-cut-main");
if (diecut.length > 0) {
var productStacks = $(".product-stack-row");
var productStackCount = productStacks.length;
for (var i = 1; i < productStackCount - 1; i += 2) {
var diecutClone = diecut.clone();
if (typeof $this.DieCutMessages != 'undefined') {
var messageContent = $this.DieCutMessages[Math.floor(i / 2)];
// p.centered is the text value location we need to replace with our content from personalization api
if (messageContent) diecutClone.find("p.centered").html(messageContent);
}
diecutClone = $(diecutClone).removeClass("result-page-die-cut-main").addClass("result-page-die-cut");
$(productStacks[i]).append(diecutClone);
}
// make element visible
$(".result-page-die-cut").removeClass("hide").addClass('hidden-xs');
}
}
};
$this.dieCutApiUrl = function (apiUrl) {
return '{0}diecut/GetDiecutMessages?categoryId={1}'.format(Dell.Services.apiUrl, categoryName);
};
$this.getComoDieCuts = function () {
$.ajax($this.dieCutApiUrl()).success(function (data) {
comoDieCuts = data;
$this.assignComoDieCuts(comoDieCuts);
}).error(function () { $this.assignComoDieCuts(); });
};
$this.assignComoDieCuts = function (d) {
if (typeof d !== 'undefined' && d != null && d.length > 0) {
//display warm/hot state como messaging & links
for (var i = 0; i < d.length; i++) {
var dieCut = d[i];
var $match = $series.filter('[data-categorycode=' + dieCut.StackId + ']').find('.dfs-merchandizing-die-cut');
if ($match.length != 0) {
var dieCutLinks = '';
if (dieCut.IsVisible) {
$match.find('.promo').html(dieCut.MessagingText);
if (dieCut.LearnLink.IsVisible)
dieCutLinks += comoLinkFrmt.format(dieCut.LearnLink.Url, dieCut.LearnLink.Caption, dieCut.LearnLink.Target);
if (dieCut.ApplyLink.IsVisible && dieCut.ApplyLink.Caption != null && dieCut.ApplyLink.Caption != '')
dieCutLinks += ' | ' + comoLinkFrmt.format(dieCut.ApplyLink.Url, dieCut.ApplyLink.Caption, dieCut.ApplyLink.Target) + '';
$match.find('.dpaLinks').html(dieCutLinks);
$match.show();
} else {
$match.hide();
}
}
}
}
//hide for mobile only
$dieCuts.removeClass('hide').addClass('hidden-xs');
};
}).call(Dell.Controllers.diecut);
})(jQuery, window, document);;
var Dell = Dell || {};
Dell.Controllers = Dell.Controllers || {};
Dell.Controllers.cfcModal = {};
(function ($, window, document) {
(function () {
'use strict';
var $this = this,
key = 'cfcModal',
$modal = $('#cfc-modal'),
$zipInput = $('#inputZipcode'),
$zipSubmit = $modal.find('.cfcCta'),
showLoading = true,
cfcModalData = {
hasError: false,
isValid: false,
userZipCode: "",
modalCtaLabel: "",
cfcModel: {}, //data received from EstimatedDeliveryModel api call
deliveryDates: {}, // data received from EstimatedDeliveryDates api call
shippingModel: {}, // shipping data from product stack
},
linkWithZipCode = "",
newShippingMessage = "",
apiUrl = serverUrls.apiServiceUrl,
orderCode = "",
stackType = "",
selectionstate = "",
itemIdentifiers = "",
weight = "",
type = "",
oc = "",
ocs = "",
skus = "",
primaryCtaCaption = "",
postObj = {},
postObjJson = {},
isSnp = false,
clearForm = false,
loadForm = true,
zipRegex = /^[0-9]{5}(?:-[0-9]{4})?$/,
validateTrigger = false,
req = null,
page = $('meta[name=wacontroller]').attr("content").toLowerCase(),
$document = $(document);
function initVueTemplate() {
Dell.Controllers.vue.newComponent([
{
name: 'cfcmodal',
co: {
template: $('cfcmodal')[0],
props: { cfcmodeldata: Object }
},
register: true
}
]);
Dell.Controllers.vue.register(key, $modal[0], { cfcModalData: cfcModalData });
}
function initCfcModal() {
cfcModalData.userZipCode = loadCookieZipCode();
$document.on('updateCFCShippingModal', function (event) {
if (cfcModalData.modalCtaLabel === "" && typeof cfcModalData.shippingModel.EstimatedDeliveryModel !== 'undefined') {
cfcModalData.modalCtaLabel = cfcModalData.shippingModel.EstimatedDeliveryModel.PrimaryCtaCaption;
}
/*zipCode = $this.getZipCode();
if (zipCode != '') {
$this.getShippingInfo(zipCode);
}*/
if (!Dell.Controllers.vue.isDefined(key))
initVueTemplate();
else
Dell.Controllers.vue.setVMData(key, 'cfcModalData', cfcModalData);
Vue.nextTick(function () {
$modal = $('#cfc-modal');
$zipInput = $('#inputZipcode');
$zipSubmit = $modal.find('.cfcCta');
$zipInput.on('change keyup', validateZipCode);
$document.on('submit', '#zipform', function (e) {
e.preventDefault();
submit();
});
});
}).on('newResultsReceived newStacksReceived', bindEvents);
bindEvents();
/*$scope.$watch(function () { return cfcService.showLoading; }, function (newVal, oldVal) {
$scope.showLoading = newVal;
});
$scope.$watch(function () { return cfcService.error; }, function (newVal, oldVal) {
$scope.error = newVal;
});
$scope.$watch(function () { return cfcService.hasZipCode; }, function (newVal, oldVal) {
$scope.hasZipCode = newVal;
});
$scope.$watch(function () { return cfcService.clearForm; }, function (newVal, oldVal) {
$scope.zipform.userZipCode.$error.pattern = true;
});
$scope.$watch(function () { return cfcService.loadForm; }, function (newVal, oldVal) {
$scope.zipform.userZipCode.$error.required = false;
});*/
};
function bindEvents() {
if (page !== 'pdreview')
$('#root-canvas, #configurations-content, #deals-content').on('click', 'a.cfcDates', function (e) { e.preventDefault(); loadCFCModal($(this)); });
};
function loadCFCModal($e) {
type = $e.attr('data-type').toLowerCase();
weight = $e.attr('data-weight');
oc = $e.attr('data-id');
var stack = Dell.Controllers.productstack.getProduct({ id: oc });
ocs = '';
skus = '';
//update to work with compare and candy aisle stack groups
for (var i = 0; i < Dell.Services.DataModel.Stacks.length; i++) {
if (Dell.Services.DataModel.Stacks[i].IsMerchandisingContainer == false) {
var ps = Dell.Services.DataModel.Stacks[i].Stack;
/*
* SnpStock.Status - 0: None, 5: LimitedStock, 7: PreOrder
* For reference - Dell.Transactional.Runtime.Shop.ProductStack.StockStatus
*/
if ((ps.Type !== 0 && ps.SnpStock.Status === 0 ||
ps.SnpStock.Status === 5 ||
ps.SnpStock.Status === 7) || ps.Type === 0) {
if (ps.Type === 1) {
skus += ps.Sku.Value + ';';
} else {
ocs += ps.OrderCodeSkus + ';'
}
}
}
}
cfcModalData.shippingModel = stack.Stack.Shipping;
$document.trigger('updateCFCShippingModal');
//$this.loadModal(oc, stack.Stack.Shipping, type, ocs, skus, weight);
}
function submit() {
cfcModalData.userZipCode = $zipInput.val();
if (cfcModalData.userZipCode === "") {
cfcModalData.userZipCode = $this.getCFCZipCode();
}
$this.getShippingInfo(cfcModalData.userZipCode);
}
function validateZipCode() {
if (!validateTrigger) {
validateTrigger = true;
//allow call every 250ms
cfcModalData.userZipCode = $zipInput.val();
cfcModalData.isValid = (zipRegex.exec(cfcModalData.userZipCode) === null);
$document.trigger('updateCFCShippingModal');
//$zipSubmit.attr('disabled', hasError);
setTimeout(function () { validateTrigger = false; }, 250);
}
}
$this.cfcApiUrl = function () {
return '{0}EstimatedDelivery/EstimatedDeliveryModel?postalCode={1}&productId={2}&selectionstate={3}&isSNP={4}&weight={5}'.
format(apiUrl, cfcModalData.userZipCode, oc, selectionstate, isSnp, weight);
};
$this.cfcDeliveryDatesApiUrl = function () {
return '{0}EstimatedDelivery/EstimatedDeliveryDates'.
format(apiUrl);
};
$this.loadModal = function (oc, shippingModel, type, ocs, skus, weight) {
showLoading = true;
hasZipCode = false;
cfcModalData.userZipCode = $this.getZipCode();
orderCode = oc;
cfcModalData.shippingModel = shippingModel;
stackType = type;
isSnp = stackType === 'snp' || parseInt(stackType) === 1;
ocs = ocs;
skus = skus;
weight = weight;
if (cfcModalData.userZipCode != '') {
$this.getShippingInfo(cfcModalData.userZipCode);
}
};
function existsInCookie() {
return (amplify.store.localStorage !== undefined || amplify.store.sessionStorage !== undefined) ?
(typeof amplify.store().cfcZipCode !== 'undefined') : false;
};
function loadCookieZipCode() {
return existsInCookie() ? amplify.store().cfcZipCode : '';
};
$this.clearModal = function () {
$('#inputZipcode').val('');
clearForm = !clearForm;
};
$this.getZipCode = function () {
var cookieValue = $.cookie('location');
if (typeof cookieValue !== 'undefined' && cookieValue !== '') {
var cookieObj = JSON.parse(cookieValue);
if (typeof cookieObj.zipcode !== 'undefined' && cookieObj.zipcode !== "") {
return cookieObj.zipcode;
} else {
return '';
}
} else {
return '';
}
};
function setLoadingState(loading) {
$modal.attr('data-state', loading ? 'iconSpinner' : '');
}
$this.getShippingInfo = function (zipCode) {
if (typeof zipCode !== 'undefined' && zipCode !== "") {
cfcModalData.hasError = false;
//showLoading = true;
setLoadingState(true);
cfcModalData.userZipCode = zipCode;
$this.setCFCZipCode(zipCode);
if (req === null || req.readyState >= 4) {
req = Dell.Services.httpGetService.getData($this.cfcApiUrl())
.success(function (data, stcd, xhr, stg) {
cfcModalData.cfcModel = data;
showLoading = false;
postObj["PostalCode"] = zipCode;
postObj["SystemId"] = ocs;
postObj["SnpId"] = skus;
postObjJson = JSON.stringify(postObj);
setLoadingState(false);
Dell.Services.httpGetService.postData({
url: $this.cfcDeliveryDatesApiUrl(),
data: postObjJson,
success: function (deliveryData, stcd, xhr, stg) {
cfcModalData.deliveryDates = deliveryData;
$this.updateProductStack(data.ProductStackDeliveryMessage, data.PrimaryCtaCaption, deliveryData);
},
error: function (e) {
$this.updateProductStack(null, cfcModalData.cfcModel.PrimaryCtaCaption, { zipCode: zipCode });
}
});
}).error(function () {
setLoadingState(false);
cfcModalData.hasError = true;
$document.trigger('updateCFCShippingModal');
});
}
}
};
$this.getDeliveryDates = function (zipCode) {
cfcModalData.userZipCode = zipCode;
var skus = '';
var ocs = '';
if ($('.snp-hero-productStack').length > 0 || $('#review-summary').length > 0) {
var oc = $('.cfcDates').attr('data-id');
var type = $('.cfcDates').attr('data-type').toLowerCase();
ocs = $('.cfcDates').attr('data-ordercodeskus');
if (type === 1 || type.toLowerCase() === 'snp') {
skus = oc;
ocs = '';
}
} else {
for (var i = 0; i < Dell.Services.DataModel.Stacks.length; i++) {
if (Dell.Services.DataModel.Stacks[i].IsMerchandisingContainer == false) {
var ps = Dell.Services.DataModel.Stacks[i].Stack;
/*
* SnpStock.Status - 0: None, 5: LimitedStock, 7: PreOrder
* For reference - Dell.Transactional.Runtime.Shop.ProductStack.StockStatus
*/
if ((ps.Type !== 0 && ps.SnpStock.Status === 0 ||
ps.SnpStock.Status === 5 ||
ps.SnpStock.Status === 7) || ps.Type === 0) {
if (ps.Type === 1) {
skus += ps.Sku.Value + ';';
} else {
ocs += ps.OrderCodeSkus + ';'
}
}
}
}
}
if (typeof Dell !== 'undefined' && typeof Dell.Services !== 'undefined' && typeof Dell.Services.DataModel !== 'undefined' && typeof Dell.Services.DataModel.Stacks !== 'undefined' && Dell.Services.DataModel.Stacks.length > 0) {
$this.primaryCtaCaption = Dell.Services.DataModel.Stacks[0].Stack.Shipping.EstimatedDeliveryModel.PrimaryCtaCaption;
}
$this.postObj["PostalCode"] = zipCode;
$this.postObj["SystemId"] = ocs;
$this.postObj["SnpId"] = skus;
$this.postObjJson = JSON.stringify($this.postObj);
Dell.Services.httpGetService.postData({
url: $this.cfcDeliveryDatesApiUrl(),
data: $this.postObjJson,
success: function (deliveryData, stcd, xhr, stg) {
$this.updateProductStack(null, $this.primaryCtaCaption, deliveryData);
}
});
};
$this.setSelectionState = function (ss) {
$this.selectionstate = ss;
};
$this.setCFCZipCode = function (zipCode) {
cfcModalData.userZipCode = zipCode;
amplify.store('cfcZipCode', zipCode, { expires: 86400000 }); //keep for 24hrs.
// set cookie to be read by CART (https)
$.cookie('cfcZipCode', zipCode, { expires: 1, path: '/' }); // keep for 1 day
SHOP.Transactional.Location.setZipCodeInLocationCookie(zipCode);
};
$this.getCFCZipCode = function () {
if (amplify.store.localStorage !== undefined || amplify.store.sessionStorage !== undefined) {
if (typeof amplify.store().cfcZipCode !== 'undefined') {
return amplify.store('cfcZipCode');
}
}
return -1;
};
$this.updateProductStack = function (message, link, deliverydata) {
linkWithZipCode = cfcModalData.userZipCode !== "" && typeof cfcModalData.userZipCode !== 'undefined' ? link + ' - ' + cfcModalData.userZipCode : link;
newShippingMessage = message;
/*if ($('#ProductStackContainer.vuePOC').length === 0) {
$rootScope.$broadcast('updateCFCShipping');
// SNP Pd Page & Systems Pd Review Page, Can be removed when those page is moved to Vue
if ($('.snp-hero-productStack').length > 0 || $('#review-summary').length > 0) {
$('.cfcZipCode').empty();
$('.cfcDates').html($this.linkWithZipCode);
$('.cfcMessage').html($this.newShippingMessage);
}
}
else {*/
$document.triggerHandler('cfcModelData', [{
newShippingMessage: newShippingMessage,
linkWithZipCode: linkWithZipCode,
orderCode: orderCode,
zipCode: cfcModalData.userZipCode,
linkWithoutZipCode: link,
deliverydata: deliverydata
}]);
//}
};
$document.ready(initCfcModal);
}).call(Dell.Controllers.cfcModal);
})(jQuery, window, document);;
$(document).ready(function () {
var cmsPageLocator = {
Init: function () {
this.BindEvents();
},
BindEvents: function () {
$(document).keypress(cmsPageLocator.Events.EnableShortCuts);
},
Events: {
EnableShortCuts: function (ev) {
var kCode = ev.keyCode || ev.which; // gets the keycode in ie or ns
// CTRL + SHIFT + E (Edit CMS Page)
if (ev.ctrlKey && ev.shiftKey && (kCode === 69 || kCode === 5)) {
var mEditurl = $("meta[name='cmsurl']").attr("content");
if (mEditurl != null && mEditurl.length > 0) {
if (confirm("Edit page?")) {
window.open(mEditurl, 'cmsEditWin');
}
}
}
// CTRL + SHIFT + M (Microcontent List)
}
}
};
cmsPageLocator.Init();
});
var SHOP = window.SHOP || {};
SHOP.Transactional = SHOP.Transactional || {};
SHOP.Transactional.KeyBoardShortCuts = SHOP.Transactional.KeyBoardShortCuts || {};
(function ($, window, document) {
var map = {};
var previewForceRefreshHotKeys = { // should be changed to local once it is binded to keypress
Init: function () {
previewForceRefreshHotKeys.BindEvents();
},
BindEvents: function () {
$(document).on("keyup", previewForceRefreshHotKeys.Events.OnDocumentKeyPress);
$(document).on("keydown", previewForceRefreshHotKeys.Events.OnDocumentKeyPress);
},
Events: {
OnDocumentKeyPress: function (e) {
e = e || event; //IE fallback
map[e.keyCode] = e.type === 'keydown';
if (map[17] && map[18] && map[80]) {
previewForceRefreshHotKeys.Operations.ShowPreviewPage(); //ctrl+alt+p
map = {};
}
else if (map[17] && map[18] && map[82]) {
previewForceRefreshHotKeys.Operations.ForceRefreshPage(); //ctrl+alt+R
map = {};
}
}
},
Operations: {
replaceDomainNameinUrl: function (href, domain) {
var hlink = document.createElement('a');
hlink.setAttribute('href', href);
hlink.host = domain;
return hlink.href;
},
addParams: function (url, data) {
if (!$.isEmptyObject(data) && url.toUpperCase().indexOf(data.toUpperCase()) < 0) {
url += (url.indexOf('?') >= 0 ? '&' : '?') + data;
}
return url;
},
ShowPreviewPage: function () {
var currentUrl = $("meta[name='canonical']").context.URL;
var previewUrl = previewForceRefreshHotKeys.Operations.replaceDomainNameinUrl(currentUrl, Dell.Transactional.InternalSubDomain);
if (Dell.Transactional.updateQueryStringParameter) {
if (previewUrl.indexOf('preview=off') > -1) {
previewUrl = Dell.Transactional.updateQueryStringParameter(previewUrl, "preview", "on");
} else if (previewUrl.indexOf('preview=0') > -1) {
previewUrl = Dell.Transactional.updateQueryStringParameter(previewUrl, "preview", "1");
} else if (previewUrl.indexOf('preview=false') > -1) {
previewUrl = Dell.Transactional.updateQueryStringParameter(previewUrl, "preview", "true");
} else {
previewUrl = Dell.Transactional.updateQueryStringParameter(previewUrl, "preview", "on");
}
window.open(previewUrl, "_blank");
}
},
ForceRefreshPage: function () {
var currentUrl = $("meta[name='canonical']").context.URL;
var forceRefreshUrl = previewForceRefreshHotKeys.Operations.replaceDomainNameinUrl(currentUrl, Dell.Transactional.InternalSubDomain);
forceRefreshUrl = previewForceRefreshHotKeys.Operations.addParams(forceRefreshUrl, "forceRefresh=on");
window.open(forceRefreshUrl, "_blank");
}
}
}
previewForceRefreshHotKeys.Init();
})(jQuery, window, document);;
var Dell = window.Dell || {};
Dell.Services = Dell.Services || {}
Dell.Services.productstack = {};
(function ($, window, document) {
(function () {
'use strict';
var $this = this,
$scope = $('#ProductStackContainer.vuePOC'),
stacks = $scope.find('.product-stack-inner-row');
$this.getNumberOfRows = function (a) {
/*if ($('#featuredItems').length > 0 || (typeof stacks == 'undefined') || ($('.recommendations-container').length > 0 && !($(window).width() < 768))) {
return 1;
} else {
return (SHOP.Transactional.Breakpoint.isPhone() ? stacks.length : ($('.device-sm').is(':visible')) ? parseInt(Math.ceil(stacks.length / 3)) : parseInt(Math.ceil(stacks.length / 4));
}*/
var count = a ? a.length : $scope.find('.ups-image').length;
return count > 0 ? Math.ceil(count / $this.getItemsPerRow()) : 1;
};
$this.getParentCollection = function (stacks) {
return $this.getNumberOfRows(stacks);
};
$this.getItemsPerRow = function () {
SHOP.Transactional.Breakpoint.getMediaQuery(true);
if (window.changeStacksLayout)
return (SHOP.Transactional.Breakpoint.isPhone() ? 1 : SHOP.Transactional.Breakpoint.isTablet() ? 2 : 3);
else
return (SHOP.Transactional.Breakpoint.isPhone() ? 1 : SHOP.Transactional.Breakpoint.isTablet() ? 3 : 4);
}
$this.goToCompare = function () {
var orderCodeObject = Dell.Transactional.getCodes('ocs', true),
$URLtoReturn = "";
for (var i = 0; i < orderCodeObject.length; i++) {
$URLtoReturn += (i === 0) ? "?ocs=" + orderCodeObject[i] : "," + orderCodeObject[i];
}
return $URLtoReturn;
};
}).call(Dell.Services.productstack);
})(jQuery, window, document, History);
Dell.Controllers = Dell.Controllers || {};
Dell.Controllers.productstack = {};
(function ($, window, document, History) {
(function () {
'use strict';
var $scope = {},
$this = this,
vm = [],
om,
componentsDefined = false,
$pStack = $('#ProductStackContainer.vuePOC'),
curRow = 0,
user = !Dell.Services.userContext ? { Country: '', Segment: '' } : Dell.Services.userContext.get(),
resize = false,
wac = $('meta[name="wacontroller"]').attr('content'),
isDeals = wac === 'deals' || $('#deals-page').length > 0,
isSingleOc = wac === 'productdetails' && $('.product-configurator').length === 1,
isMultiOc = !isSingleOc && $('#configurations-container').length > 0,
isRec = wac === 'recommendations' || $('.recommendations-container').length > 0,
$siteWrapper = $('#site-wrapper'),
isCompare = $('#comparectrl').length > 0,
resultsPage = $('[data-state=resultsPage]').length || $('[data-state=getAnavResults]').length,
curPg = 1,
addToCartTxt = null,
$rootScope = $('[data-scope]'),
vueMixinCalled = false,
angRecSvcDM = false,
cfcUpdate = false,
moduleIndex = -1,
itemIndex = -1,
scrollFired = false,
deliveryData = {},
hasDeliveryData = false,
locationCookie = $.cookie('location'),
$window = $(window),
$document = $(document),
hasPerfMetrics = typeof Dell.perfmetrics !== 'undefined';
if (typeof locationCookie !== 'undefined' && locationCookie !== "") {
locationCookie = JSON.parse(locationCookie);
}
$this.renderDiecut = Dell.Controllers.diecut.renderDiecut;
$this.mapPersonalization = false;
$this.getParentCollection = function () {
$scope.rows = ProductStackService.getNumberOfRows($scope.modelStacks);
return $scope.rows;
};
$this.getCollectionStart = function (index) {
return $scope.ipr * (index + 1);
};
$this.getCollectionEnd = function (index) {
return ((index + 1) === $scope.rows) ? $scope.modelStacks.length - ($scope.ipr * index) : $scope.ipr;
};
$this.getProduct = function (p, d) {
var prod;
var stks = d || vm;
if (p) {
if (p.index && stks[p.index]) {
prod = stks[p.index];
} else if (p.id) {
var lcid = p.id.toLowerCase();
var s = !p.noSpaces ? $.grep(stks, function (e) { return e.Stack.ItemIdentifier.toLowerCase() == lcid || e.Stack.Sku.Value.toLowerCase() == lcid; }) :
$.grep(stks, function (e) { return e.Stack.ItemIdentifier.toLowerCase().replace(' ', '-') == lcid || e.Stack.Sku.Value.toLowerCase().replace(' ', '-') == lcid; });
if (isRec && s.length === 0) {
s = !p.noSpaces ? $.grep(Dell.Services.DataModel.ModuleGroups[0].Items, function (e) { return e.Stack.ItemIdentifier.toLowerCase() == lcid || e.Stack.Sku.Value.toLowerCase() == lcid; }) :
$.grep(Dell.Services.DataModel.ModuleGroups[0].Items, function (e) { return e.Stack.ItemIdentifier.toLowerCase().replace(' ', '-') == lcid || e.Stack.Sku.Value.toLowerCase().replace(' ', '-') == lcid; });
}
if (s.length > 0) prod = s[0];
try {
/*Handle All Deals Multiple Stacks*/
if (!prod && !p.sc) {
if (Dell.Services.DataModel.AllDealsCategories && Object.keys(Dell.Services.DataModel.AllDealsCategories).length > 0) {
for (var j = 0; j < Object.keys(Dell.Services.DataModel.AllDealsCategories).length; j++) {
var stackData = Dell.Services.DataModel.AllDealsCategories[Object.keys(Dell.Services.DataModel.AllDealsCategories)[j]].Results.Stacks;
if (stackData) {
var stacks = (stackData.Stacks ? stackData.Stacks : stackData);
prod = Dell.Controllers.productstack.getProduct({ id: p.id, sc: true }, stacks);
if (prod) {
return prod;
}
}
}
}
}
}
catch (e) {
console.error(e);
}
}
}
return prod;
}
$this.hasWindow10Home = function () {
if ($(window)[0].Dell.Metrics.sc.country === 'us' && $(window)[0].Dell.Metrics.sc.segment === 'bsd') {
return $scope.modelStacks && $scope.modelStacks
.map(function (stack) {
return stack.Specs.TechSpecs.filter(function (spec) {
return spec.Label.toLocaleUpperCase() === "OPERATING SYSTEM"
&& spec.Values[0].toLocaleUpperCase().includes("WINDOWS 10 HOME");
});
})
.reduce(function (prev, cur) {
return prev.concat(cur);
}).length > 0;
} else {
return false;
}
}
$this.hasCfcUpdate = function () { return cfcUpdate; };
$this.moduleIndex = function () { return moduleIndex; };
$this.itemIndex = function () { return itemIndex; };
var getPage = function (i) {
var max = $this.ipr * i;
return vm.slice((max - $this.ipr), (max < vm.Stacks.length + 1 ? max : vm.Stacks.length));
};
var updateCfcData = function (vm) {
var counter = 0;
if (hasDeliveryData) {
vm.forEach(function (v, i) {
var product = parseInt(v.Stack.Type) === 1 ? v.Stack.Sku.Value : v.Stack.OrderCodeSkus;
if (typeof product != 'undefined' && product != '') {
var productDeliveryData = deliveryData.deliverydata[product];
if (typeof productDeliveryData != 'undefined' && productDeliveryData.ShowDeliveryMessage) {
v.Stack.Shipping.ShippingTitle.Value = '';
$('.cfcZipCode').empty();
v.Stack.Shipping.ShippingDate.Value = productDeliveryData.DeliveryMessage;
v.Stack.Shipping.EstimatedDeliveryModel.ProductStackDeliveryMessage = productDeliveryData.DeliveryMessage;
}
v.Stack.Shipping.EstimatedDeliveryModel.PrimaryCtaCaption = deliveryData.linkWithoutZipCode;
v.Stack.Shipping.EstimatedDeliveryModel.ZipCode = deliveryData.zipCode;
counter++;
}
});
}
return counter;
}
$document.on('newUserState', bindPersonalized)
.on('newResultsReceived newStacksReceived', function (e, d, a) {
var append = typeof a !== 'undefined' ? a : false,
cfcUpdated = updateCfcData((d.Stacks ? d.Stacks : d));
if (d.VueIndex && !(d.Source && d.Source == "deals")) {
var gr = Dell.Services.DataModel.ModuleGroups[d.VueIndex];
gr.Items = d.Stacks ? d.Stacks : d;
}
if (!append) {
$this.updateStacks((d.Stacks ? d.Stacks : d), d.VueIndex);
} else {
var scrollTop = $window.scrollTop();
$this.updateStacks(vm.concat((d.Stacks ? d.Stacks : d)), d.VueIndex);
Vue.nextTick(function () {
$window.scrollTop(scrollTop);
});
}
resultsPage = $('[data-state=resultsPage]').length || $('[data-state=getAnavResults]').length || $('[data-state=hasSelectedRefinements]').length || $('[data-state=getMoreAnavResults]').length;
if (resultsPage > 0)
Dell.Services.DataModel.Stacks = vm;
$document.trigger('Dell.Services.DataModel');
/*$scope.waitForFinalEvent(function () {
addToCompareService.universalAlreadyExistsInStore($scope.modelStacks);
$scope.$apply($rootScope.comparecount = "(" + amplify.store('productOC:size') + "/3)");
}, 300, $scope.fullDateString.getTime());*/
})
.on('originalstacks', function () {
//$document.trigger('newFilterData', Dell.Services.DataModel.AnavFilterViewModel); //this may send the incorrect original vm data
if (typeof Dell !== 'undefined' && typeof Dell.Services !== 'undefined' && typeof Dell.Services.DataModel !== 'undefined' && typeof Dell.Services.DataModel.AnavFilterModel !== 'undefined' && typeof Dell.Services.DataModel.AnavFilterModel.Results !== 'undefined') {
$this.updateStacks(Dell.Services.DataModel.AnavFilterModel.Results.Stacks);
}
})
.on('resetAnav', function () {
$scope.modelStacks = $scope.$parent.DataModel.Stacks;
})
.on('newCandyAisleResultsReceived', function () {
if ($scope.$parent.moduleIndex === $scope.moduleIndex) {
$scope.modelStacks = $scope.$parent.apiModuleProductStacks;
$scope.determineLayout();
}
});
var updateCfcData = function (vm) {
var counter = 0;
if (hasDeliveryData) {
vm.forEach(function (v, i) {
var product = parseInt(v.Stack.Type) === 1 ? v.Stack.Sku.Value : (!v.Stack.OrderCodeSkus ? 'undefined' : v.Stack.OrderCodeSkus);
if (typeof product != 'undefined' && product != '') {
var productDeliveryData = deliveryData.deliverydata[product];
if (typeof productDeliveryData != 'undefined' && productDeliveryData.ShowDeliveryMessage) {
v.Stack.Shipping.ShippingTitle.Value = '';
v.Stack.Shipping.ShippingDate.Value = productDeliveryData.DeliveryMessage;
v.Stack.Shipping.EstimatedDeliveryModel.ProductStackDeliveryMessage = productDeliveryData.DeliveryMessage;
}
v.Stack.Shipping.EstimatedDeliveryModel.PrimaryCtaCaption = deliveryData.linkWithoutZipCode;
v.Stack.Shipping.EstimatedDeliveryModel.ZipCode = deliveryData.zipCode;
counter++;
}
});
}
return counter;
}
$(document).on('updateCFCShipping cfcModelData', function (e, d) {
deliveryData = d;
hasDeliveryData = d !== undefined && d !== null;
if (hasDeliveryData) {
$document.trigger('bootstrapChk');
var counter = 0,
maxIndex = !isCompare ? 1 : Dell.Services.DataModel.CompareCategories.length,
newVm = [];
cfcUpdate = true;
counter = updateCfcData(om);
for (var i = 0; i < maxIndex; i++) {
newVm = (!isCompare ? vm : Dell.Services.DataModel.CompareCategories[i].Containers);
counter = updateCfcData(newVm);
if (counter > 0) {
$this.updateStacks(newVm, (!isCompare ? null : i));
}
}
try {
/*
* Below code is required to handle CFC in All deals tab as all Deals has multiple staks.
*/
if (Dell.Services.DataModel.AllDealsCategories && Object.keys(Dell.Services.DataModel.AllDealsCategories).length > 0) {
var counter = 0;
for (var j = 0; j < Object.keys(Dell.Services.DataModel.AllDealsCategories).length; j++) {
var stackData = Dell.Services.DataModel.AllDealsCategories[Object.keys(Dell.Services.DataModel.AllDealsCategories)[j]].Results.Stacks;
if (stackData) {
var stacks = (stackData.Stacks ? stackData.Stacks : stackData);
counter += updateCfcData(stacks);
}
}
if (counter > 0) {
$(document).trigger("updateAllDeals", [Dell.Services.DataModel]);
}
}
}
catch (e) {
console.error(e);
}
}
})
.on('updateCompare', function (e, d) {
if (!vueMixinCalled) {
$this.vueMixins();
}
$this.updateStacks(d, Dell.Controllers.comparectrl.groupIndex);
})
.one('Dell.Services.DataModel', function ProductStackDataModel() {
vm = Dell.Services.DataModel ? Dell.Services.DataModel.Stacks || Dell.Services.DataModel.Stack || (Dell.Services.DataModel.AnavFilterModel && Dell.Services.DataModel.AnavFilterModel.Results.Stacks ? Dell.Services.DataModel.AnavFilterModel.Results.Stacks : []) : [];
if (om === undefined)
om = JSON.parse(JSON.stringify(vm));
//bindPersonalized();
if (Dell.Controllers.deals)
Dell.Controllers.deals.checkPagination(Dell.Services.DataModel);
if (isMultiOc)
$this.updatePagination();
if (isRec && Dell.Services.DataModel.ModuleGroups) {
//set the cta state and text correctly depending on itemStates
//for the first module group that is expanded on candy aisle pages
var recGroup = Dell.Services.DataModel.ModuleGroups[0];
addToCartTxt = recGroup.Items[0].Stack.Links.AddToCartLink.Caption;
for (var i = 0; i < recGroup.ItemStates.length; i++) {
setupCta($('#candyCarousel-' + recGroup.Id).find('a.addItemToCartCta[data-idx="' + i + '"]'), recGroup.ItemStates[i]);
}
}
})
.on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
$this.addAndUpdateZipCodeProductStack();
}).on('updateMerchTiles', function () {
$.each($('.merchandizingTile'), function () {
var rowHeight = $(this).closest('.product-stack-inner-row').height();
$(this).height(rowHeight);
});
});
var compareLinkSeq = function (a, b) {
// Use toUpperCase() to ignore character casing
return a.Sequence - b.Sequence;
};
var defineComponents = function () {
if (componentsDefined)
return;
componentsDefined = true;
// create components
var $ps = $('.vuePOC').eq(0);
Dell.Controllers.vue.newComponent([
{
name: 'psmerchandizing',
co: { template: $ps.find('div.ups-merchandizing')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'pscompareremove',
co: { template: $ps.find('pscompareremove > div')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'pscompare',
co: { template: $ps.find('pscompare > div')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'pspromo',
co: { template: $ps.find('div.ups-promotion')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'psimage',
co: { template: $ps.find('div.ups-image')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'pstitle',
co: { template: $ps.find('div.ups-title')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'psratings',
co: { template: $ps.find('div.ups-ratings')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'pssimpleprice',
co: { template: $ps.find('div.ups-simple-price')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'psmarketing',
co: { template: $ps.find('div.ups-marketingblurb')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'psiconography',
co: { template: $ps.find('div.ups-iconography')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'psfeature',
co: { template: $ps.find('div.ups-feature')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'psweight',
co: { template: $('.ups-weight')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'psdescription',
co: { template: $ps.find('div.ups-description')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'psmanufacturer',
co: { template: $ps.find('div.ups-manufacturer')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'psspecialoffers',
co: { template: $ps.find('div.ups-special-offers')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'pspricing',
co: { template: $ps.find('div.ups-price')[0], props: { item: Object, index: Number, rowindex: Number, testidprefix: String } }
},
{
name: 'psdpa',
co: { template: $ps.find('div.ups-dpa')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'psrewards',
co: { template: $ps.find('div.ups-rewards')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'psbusinessrewards',
co: { template: $ps.find('div.ups-business-rewards')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'psshipping',
co: { template: $ps.find('div.ups-shipping')[0], props: { item: Object, index: Number, rowindex: Number, soafeaturetoggle: Boolean } }
},
{
name: 'psevalue',
co: { template: $ps.find('div.ups-evaluecode')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'pssnpstockstatus',
co: { template: $ps.find('pssnpstockstatus div.ups-stockstatus')[0], props: { item: Object, index: Number, rowindex: Number, snpstock: Object } }
},
{
name: 'psstockstatus',
co: { template: $ps.find('psstockstatus div.ups-stockstatus')[0], props: { item: Object, index: Number, rowindex: Number, snpstock: Object } }
},
{
name: 'psmoreinfo',
co: { template: $ps.find('span.ups-moreinfo')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'pshideinfo',
co: { template: $ps.find('span.ups-hideinfo')[0], props: { item: Object, index: Number, rowindex: Number } }
},
{
name: 'pscta',
co: { template: $ps.find('div.ups-cta')[0], props: { item: Object, index: Number, rowindex: Number, secondary: Boolean } }
},
{
name: 'stackrow',
co: {
template: $ps.find('div.product-stack-row')[0],
props: {
row: Array,
rowindex: Number,
soafeaturetoggle: Boolean,
testidprefix: String,
snpstock: Object
},
components: ['psmerchandizing', 'pscompareremove', 'pscompare', 'pspromo', 'psimage', 'pstitle', 'psratings', 'pssimpleprice', 'psmarketing', 'psiconography', 'psfeature', 'psweight', 'psdescription', 'psmanufacturer', 'psspecialoffers', 'pspricing', 'psdpa', 'psrewards', 'psbusinessrewards', 'psshipping', 'psevalue', 'psstockstatus', 'pssnpstockstatus', 'psmoreinfo', 'pshideinfo', 'pscta']
}
},
{
name: 'stackcontroller',
co: {
template: '',
props: {
row: Array,
rowindex: Number,
index: Number,
soafeaturetoggle: Boolean,
testidprefix: String,
item: Object,
snpstock: Object
},
components: ['stackrow']
},
register: true
}
]);
};
$this.initVue = function (d, idx) {
defineComponents();
var k = 'ProductStacks' + (idx ? '-' + idx : '');
var $pcs = $('#ProductStackContainer.vuePOC');
//CandyAisle and Compare have separate productstack carousels. Target correct index if defined
var $pc = !((isRec || isCompare) && idx !== undefined && Dell.Services.DataModel.ModuleGroups !== undefined) ? $pcs.eq(idx ? idx : 0) :
$('#' + Dell.Services.DataModel.ModuleGroups[idx].Id + '-content #ProductStackContainer').eq(0);
$pc.removeClass('ng-hide').find('stackrow').not(':first').remove();
$pc.find('stackrow').empty();//only one child allowed within component
Dell.Controllers.vue.register(k, $pc[0], d);
//create a vue instance
};
var sortLinks = function (vm) {
for (var i = 0; i < vm.length; i++) {
if (typeof vm[i].Stack.Links.Links !== undefined && vm[i].Stack.Links.Links !== null && vm[i].Stack.Links.Links.length > 0)
vm[i].Stack.Links.Links.sort(function (a, b) { return a.Sequence == b.Sequence ? 0 : (a.Sequence > b.Sequence) || -1; }); //ascending order
}
}
$this.updateStacks = function (d, idx) {
if (d && d.length > 0) {
var k = 'ProductStacks' + (idx ? '-' + idx : '');
vm = JSON.parse(JSON.stringify(d));
$this.determineLayout();
//remove open popovers
$('#ProductStackContainer.vuePOC').find('[data-toggle="popover"]').popover('hide');
sortLinks(vm);
if (!Dell.Controllers.vue.isDefined(k))
$this.initVue({ Stacks: vm }, idx);
else
Dell.Controllers.vue.setVMData(k, 'Stacks', vm);
if (!$this.mapPersonalization) //prevent circular dependency
$this.renderDiecut(vm);
$this.mapPersonalization = false;
}
Vue.nextTick(function () {
var $pcs = $('#ProductStackContainer.vuePOC');
Dell.Services.lazyload.loadImage($pcs.find('img.lazy, img.img-product').attr('src', '//i.dell.com/images/global/general/1x1.gif'));
bindLinks();
bindPersonalized();
$document.trigger('updateProductStacks');
//check for unmatched expanded tech specs. Ensure all are in expanded / collapsed state
$('.tech-spec-row-group').each(function () {
var $prnt = $(this);
var $accSpecs = $prnt.find('[id=show-hide-tech-specs]');
var $accExp = $accSpecs.filter('.in');
if ($accExp.length > 0 && $accExp.length < $accSpecs.length) {
$($prnt).find('.tech-spec-value').each(function (i) {
$(this).find('#show-hide-tech-specs').collapse('show');
$(this).find('a').removeClass('collapsed');
});
}
});
if (Dell.Controllers.dfsModal)
Dell.Controllers.dfsModal.bindEvents();
if (resultsPage)
$document.trigger('updateMerchTiles');
/*if ($this.isMobile && idx !== undefined) {
var $parent = $pcs.eq(idx ? idx : 0).closest('.seriesFamilyTablet');
//$parent.find('.scroll-control').attr('style', '');
//$parent.find('.toggle-off').toggle();
//SHOP.Transactional.OffCanvas.setupTransition();
}*/
});
};
var comoCheck = function (t) {
var match = false;
var state = typeof Dell.Services.userContext !== 'undefined'
? Dell.Services.userContext.getComoState()
: 'cold';
var s = typeof t !== 'undefined' && t !== null ? t.split('|') : ['cold'];
$.each(s,
function (i) {
if (state === s[i].toLowerCase())
match = true;
});
return match;
};
var bindPersonalized = function () {
//ismember="@(UserContext.Current.IsDellAdvantageMember ? "true" : "false")"
//hasprofile="@((UserContext.Current.IsAuthenticated || UserContext.Current.IsRecognized) ? "true" : "false")"
//productrewards="@item.NgNameFor(ps => ps.Stack.Rewards)"
//comorewardsmessage="@item.NgNameFor(ps => ps.Stack.ComoRewardsMessage)">
user = Dell.Services.userContext.get();
checkComo();
$('.rewards-popover').each(
function (e) {
var $this = $(this);
//e.preventDefault();
$this.removeData("bs.popover");
var pid = $this.attr('id').replace('daTtip-', '');
var stack = Dell.Controllers.productstack.getProduct({ id: pid });
if (stack != null) {
$this.popover({
content: (stack.Stack.ComoRewardsMessage != null && stack.Stack.ComoRewardsMessage !== "")
? stack.Stack.ComoRewardsMessage
: (user.IsDellAdvantageMember)
? stack.Stack.Rewards.DellAdvantageMessagingAuthenticatedMember
: (user.IsAuthenticated || user.IsRecognized)
? stack.Stack.Rewards.DellAdvantageMessagingAuthenticated
: stack.Stack.Rewards.DellAdvantageMessagingUnauthenticated,
title: stack.Stack.Rewards.DellAdvantageMessagingTitle +
" ",
container: 'body',
html: true,
placement: 'auto right'
});
}
});
//MAP pricing authenticated CTA callouts - show/hide auth-content or unauth-content based on auth state
$('.dellPricing .auth-content').toggle(user.IsAuthenticated);
$('.dellPricing .unauth-content').toggle(!user.IsAuthenticated);
if (user.IsAuthenticated)
$('.mapPricingInfo[rel="shop_product_stack_map_price_info_unauthenticated"]').attr('rel', 'shop_product_stack_map_price_info_authenticated');
};
var checkComo = function () {
var $como = $('[v-bind\\:class^=comoCss\\(]').addClass('ng-hide');
$como.each(function () {
var states = $(this).attr('v-bind:class');
states = states.substring(9, states.length - 2);
if (comoCheck(states))
$(this).removeClass('ng-hide');
});
};
var getId = function (i, f) {
var noSpaces = f !== undefined ? f : true,
chr = noSpaces ? '-' : ' ';
if (i.Stack === undefined)
return '0';
else
return (i.Stack.Type !== 2 && i.Stack.Type !== 1 ? i.Stack.ItemIdentifier.replace(' ', chr).toLowerCase() : i.Stack.Sku.Value.replace(' ', chr).toLowerCase());
};
var getOrderCode = function (i) {
if (i.Stack === undefined)
return '0';
else
return (i.Stack.Type === 1 ? i.Stack.Sku.Value.replace(' ', '-').toLowerCase() : i.Stack.ItemIdentifier.replace(' ', '-').toLowerCase());
};
var loadPsSpinner = function ($p) {
// Add to cart spinnner deals/category/franchise (.seriesFamilyTablet) candy aisle spinner (.recommendations-container), singleOC (.product-configurator)
$siteWrapper.attr('data-state', 'iconSpinner');
if (isMultiOc && !$this.isMobile) {
$('#loaderDivImage').eq(0).show();
}
}
var hidePsSpinner = function ($p) {
// Add to cart spinnner category/franchise (#middle-content) deals (.seriesFamilyTablet) candy aisle spinner (.recommendations-container), singleOC (.product-configurator)
$siteWrapper.attr('data-state', '');
if (isMultiOc && !$this.isMobile) {
$('#loaderDivImage').eq(0).hide();
}
}
var setupCta = function (t, d) {
if (t.length && d) {
if (d.IsSelected)
t.removeClass('btn-success').addClass('btn-default').html($('[data-scope]').attr('data-remove-label'));
else
t.removeClass('btn-default').addClass('btn-success').html(addToCartTxt);
}
}
var AddItemToCart = function (t) {
var $t = $(t);
var idx = $t.attr('data-idx');
if (idx !== null) {
var async = $t.attr('data-async') !== undefined ? $t.attr('data-async').toLowerCase() === 'true' : false;
var mgIdx = !isRec ? 0 : !SHOP.Transactional.Breakpoint.isPhone() ?
$('#ProductStackContainer.vuePOC').index($t.closest('#ProductStackContainer')) : mobGetModuleGroupIndex($t);
var item = !isRec ? vm[idx] : Dell.Services.DataModel.ModuleGroups[mgIdx].Items[idx];
var loc = item.Options.Settings.Location;
$document.trigger('bootstrapChk');
// Prevents Add to Cart from proceeding if there
// are any Configuration Validation Errors/Incompatibilities
// Check if any Configuration selections have been made
var selectionStateChanged = '';
if (isSingleOc) {
var $sc = angular.element($('[data-scope]')).scope();
if ($sc) {
var $root = $sc.$root;
//$rootScope.$broadcast('addingToCart');
if (item.ConfigurableItem.HasValidationErrors && item.ConfigurableItem.ValidationMessages && item.ConfigurableItem.ValidationMessages.length > 0) {
$root.$broadcast('validationError');
return;
}
if (typeof $root.selectionStateChanged !== 'undefined' && $root.selectionStateChanged == true) {
selectionStateChanged = '&selectionStateChanged=true';
}
}
}
var $parent = $t.closest('#ProductStackContainer');
var psIndex = !(SHOP.Transactional.Breakpoint.isPhone() && isRec) ? $('#ProductStackContainer.vuePOC').index($parent) : mobGetModuleGroupIndex($parent);
// If ASyncCart Feature Toggle is Enabled
// If Is NOT a SNP Item on Candy Aisle
if (async && loc !== 8) {
// Add spinner until API is complete.
loadPsSpinner($parent, psIndex);
var baseApiPath = Dell.Services.apiUrl;//a.href;
var asyncCartApi = 'addtocart/get?productid=';
//add addtocart api with sku if exists otherwise use ordercode
var itemIdentifier = getId(item);
var stackloc = isRec ? 'rec' : item.Options.StackContext;
// Get CartItemId if it exists (Only pages with a configurator)
var $loc = Dell.Services.location.search();
var cartItemId = $loc.cartItemId !== undefined ? $loc.cartItemId : '';
var cartId = '';
var selected = isRec && t.hasClass('btn-success');
var isSelected = isRec ? (selected ? '&isSelected=true' : '&isSelected=false') : '';
if (stackloc === 'svc' || stackloc === 'cfg') {
cartId = cartItemId;
}
else if (stackloc === 'rec') {
cartId = Dell.Services.DataModel ? Dell.Services.DataModel.CartItemId : '';
}
if (cartId !== "") {
cartItemId = '&cartItemId=' + cartId;
}
// Get SelectionState if it exists (Only pages with a configurator)
var selectionId = '';
var selectionCode = '';
if (stackloc === 'svc' || stackloc === 'cfg') {
selectionCode = Dell.Services.DataModel.Stacks[0].ConfigurableItem !== undefined ? Dell.Services.DataModel.Stacks[0].ConfigurableItem.SelectionState : ($loc.selectionState !== undefined ? $loc.selectionState : '');
}
else if (stackloc === 'rec') {
selectionCode = Dell.Services.DataModel ? Dell.Services.DataModel.SelectionCode : '';
}
if (selectionCode && selectionCode !== "") {
selectionId = '&selectionState=' + selectionCode;
}
// Get Location (Page)
var location = '&location=' + item.Options.Settings.Location;
// Build the API Url
var apiUrl = baseApiPath + asyncCartApi + itemIdentifier + cartItemId + selectionId + isSelected + location + selectionStateChanged;
Dell.Services.httpGetService.getData({
url: apiUrl,
success: function (data) {
if (loc != 7 && loc != 8 && loc != 13) {
$.cookie('return-from-cart', window.location.href, { path: '/' });
}
if (data.ShouldRedirect) {
DELL.com.GlobalNav.cartCount();
window.location.href = data.RedirectUrl;
//scope.$parent.$parent.showSpinner = false;
} else {
DELL.com.GlobalNav.cartCount();
//scope.$parent.$parent.showSpinner = false;
}
hidePsSpinner($parent);
},
error: function (data) {
//console.log('Add to Cart API failed for item identifier: ' + itemIdentifier);
// scope.$parent.$parent.showSpinner = false;
hidePsSpinner($parent);
}
});
} else {
if (isRec) {
$document.trigger('bootstrapChk');
var recommendationsService = angular.element('[data-scope]').injector().get('recommendationsService'),
CandyAisleApiService = angular.element('[data-scope]').injector().get('CandyAisleApiService');
if (recommendationsService)
recommendationsService.setDataModel(Dell.Services.DataModel); //ensure dataModel is set when recService is called in generating the ApiUrl including selectionState
if (item.Stack.ItemIdentifier === Dell.Services.DataModel.Stack.Stack.ItemIdentifier) {
loadPsSpinner($parent, psIndex);
Dell.Services.httpGetService.postData({
url: recommendationsService.getApiUrl() + recommendationsService.getCartUrl(),
data: recommendationsService.getCartItem(),
success: function () {
hidePsSpinner($parent);
window.location.href = item.Stack.Links.AddToCartLink.Url;
},
error: function (data) {
hidePsSpinner($parent);
window.location.href = item.Stack.Links.AddToCartLink.Url;
}
});
} else if (item.Stack.ItemIdentifier !== Dell.Services.DataModel.Stack.Stack.ItemIdentifier) {
loadPsSpinner($parent, psIndex);
/*if (scope.$parent.isQuikViewModal) {
scope.$parent.$parent.showSpinner = true;
var itemStateIndex = scope.getItemIndex(scope.productid);
var moduleIndex = scope.moduleIndex;
} else {*/
//scope.$parent.$parent.$parent.$parent.showSpinner = true;
//var itemStateIndex = ($(window).width() < 768) ? idx : idx;
//var moduleIndex = scope.$parent.$parent.$parent.moduleIndex;
//}
Dell.Services.httpGetService.getData({
url: CandyAisleApiService.candyAisleApiUrl(psIndex, idx),
success: function (data) {
hidePsSpinner($parent);
//preserve itemStates (incorrect values may be returned by api call
var iSt = Dell.Services.DataModel.ModuleGroups[psIndex].ItemStates;
//update correct module group for mobile
for (var i = 0; i < data.ModuleGroups.length; i++) {
if (Dell.Services.DataModel.ModuleGroups[psIndex].Id === data.ModuleGroups[i].Id)
Dell.Services.DataModel.ModuleGroups[psIndex] = data.ModuleGroups[i];
}
Dell.Services.DataModel.ModuleGroups[psIndex].ItemStates = iSt;
if (typeof Dell.Services.DataModel.Stack !== 'undefined' && data.Stack)
Dell.Services.DataModel.Stack = data.Stack;
if (!data.CartItemId || data.CartItemId === 'undefined')
data.CartItemId = Dell.Services.DataModel.CartItemId;
Dell.Services.DataModel.ApiUrl = data.ApiUrl;
Dell.Services.DataModel.ModuleGroups[psIndex].ItemStates[idx].IsSelected = Dell.Services.location.search(null, null, this.url).isSelected.toLowerCase() === 'true';
data.ModuleGroups = Dell.Services.DataModel.ModuleGroups;
$document.trigger('candyAddedToCart', [data, idx, psIndex, $t]);
},
error: function (data) {
hidePsSpinner($parent);
/*if (scope.$parent.isQuikViewModal) {
scope.$parent.$parent.showSpinner = false;
$('#quikview-modal').modal('hide');
}*/
}
});
return;
}
} else {
hidePsSpinner($parent);
window.location.href = !Dell.Services.DataModel.DeltaConfigureEnabled ? item.Stack.Links.AddToCartLink.Url : Dell.Services.location.search('selectionState', Dell.Services.DataModel.Stacks[0].ConfigurableItem.SelectionState, item.Stack.Links.AddToCartLink.Url);
}
}
}
};
$document.on('candyAddedToCart', function (e, data, idx, psIndex, $t, pid) {
if (data.ModuleGroups[psIndex]) {
$document.trigger('bootstrapChk');
if ($t === undefined)
$t = $('#candyCarousel-' + data.ModuleGroups[psIndex].Id).find('a.addItemToCartCta[data-idx="' + idx + '"]');
var recommendationsService = angular.element('[data-scope]').injector().get('recommendationsService');
var $root = angular.element($('[data-scope]')).scope().$root;
var ConfiguratorService = angular.element('[data-scope]').injector().get('ConfiguratorService');
Dell.Services.DataModel.Stack = data.Stack;
ConfiguratorService.setSelectionState(data.SelectionCode, data.CartItemId);
ConfiguratorService.setConfiguratorState(data.Stack.ConfiguratorState);
//History.replaceState({ SelectionState: data.SelectionCode }, '', Dell.Services.location.search("selectionState", data.SelectionCode));
Dell.Services.DataModel.SelectionCode = data.SelectionCode;
$root.AnalyticsConfigurator = data.SelectionCode;
data.VueIndex = idx;
recommendationsService.setDataModel(data);
if (data.ModuleGroups[psIndex])
setupCta($t, data.ModuleGroups[psIndex].ItemStates[idx]);
$root.selectionStateChanged = true;
$root.$broadcast('candyAddedToCart');
$root.$apply();
DELL.com.GlobalNav.cartCount();
}
});
var AddMapPriceSkuToCart = function () {
try {
$('.mapPricingInfo').attr('rel', 'shop_product_stack_map_price_info_' + (Dell.Services.userContext.get().IsAuthenticated ? 'authenticated' : 'unauthenticated'));
$('.addmap-price').on('click', function () {
var $this = $(this);
if ($this.attr('data-authenabled') === 'false')
return;
if (ResolveWebUrl && ResolveApiUrl) {
var cartUrl = ResolveWebUrl("cart"),
itemid = $this.attr('data-itemid'),
issnp = $this.attr('data-issnp').toLowerCase(),
mapauthenticated = $this.attr('data-map').toLowerCase();
var cartItem = (issnp == 1 || issnp == 2)
? { "SnpItemDataList": [{ "SnpProductId": itemid }] }
: { "ConfigProductSpecs": [{ "OrderCode": itemid }] };
Dell.Services.httpGetService.postData(
{
url: ResolveApiUrl("cart/item"),
data: JSON.stringify(cartItem),
success: function () {
var user = Dell.Services.userContext.get();
var hasprofile = (user.IsAuthenticated || user.IsRecognized);
if (mapauthenticated !== 'false' && !hasprofile)
window.location.href = Dell.Services.DataModel.LoginCartUrl;
else
window.location.href = cartUrl;
},
error: function () {
window.location.href = cartUrl;
}
});
}
});
} catch (e) { Dell.Shop.Debug('info', e) }
};
$this.initialLoad = true;
var bindLinks = function () {
if (hasPerfMetrics)
Dell.perfmetrics.start('ProductStackLinks-binding');
var vueCt = $('#ProductStackContainer.vuePOC');
vueCt.find('.moreInfoExpander, .hideInfoExpander').off('click.more').on('click.more', function () { $this.toggleMoreHide(this); });
if (SHOP.Transactional.Breakpoint.isPhone() && !isSingleOc && !isCompare) {
if ($('#accessoryResults').length > 0 && ($('#accessoryResults').attr('data-state') === 'resultsPage' || $('#accessoryResults').attr('data-state') === 'hasSelectedRefinements'))
inverseInfoExpander();
else
resetInfoExpander();
}
var pops = vueCt.find('[data-toggle="popover"]').popover();
pops.on('click', function (e) {
e.preventDefault();
e.stopPropagation();
pops.not(this).popover('hide');
}).on('hidden.bs.popover', function () {
$('.popover:not(.in)').css('display', 'none');
});
vueCt.find('[custom-popover-html]').each(function (i, el) {
$(el).popover({
trigger: 'focus',
html: true,
content: el.getAttribute('popover-html'),
placement: 'left auto',
title: el.getAttribute('popover-title'),
container: 'body'
}).on('shown.bs.popover', function () {
var $this = $('.popover.fade.in');
if (typeof $this[0] !== 'undefined' && $this[0].offsetLeft < 0) {
$this.css("left", "0");
}
}).on('hidden.bs.popover', function () {
$('.popover').remove();
});
});
$('a.fastdelivery').off('click.fastdelivery').on('click.fastdelivery', function () { populateFastDelivery($(this).attr('data-index')); });
$('a.addItemToCartCta').off('click.addToCart').on('click.addToCart', function (e) { AddItemToCart(this); });
$('a.tech-specs-accordian').off('click.expanTechSpecs').on('click.expanTechSpecs', function (e) { $this.expandRow(this); });
$document.off('click.modalJump').on('click.modalJump', '.total-savings-modal-jump', function (e) {
e.preventDefault();
var modal_id = e.target.id;
if (modal_id !== undefined) {
var unique_scope_id = $(this).closest(".modal").attr('id');
var modal_id_array = "";
if ($(this).closest(".modal").attr('aria-labelledby') == 'totalSavingsModal') {
modal_id_array = unique_scope_id.split('total-savings-modal-');
unique_scope_id = modal_id_array[1];
$('#total-savings-modal-' + unique_scope_id + ' .modal-body').animate({
scrollTop: $('#' + modal_id + '-' + unique_scope_id).offset().top
- ($('#total-savings-modal-' + unique_scope_id).offset().top + 50)
}, 200);
}
}
});
if (isRec)
$document.off('click.quickview', '.ups-image img, .ups-title span').on('click.quickview', '.ups-image img, .ups-title span', function (e) {
e.preventDefault();
var $this = $(this);
$document.trigger('bootstrapChk');
//get angular quickview service and scope
var rc = angular.element('[data-scope]');
var quikViewService = rc.injector().get('quikViewService');
var $rootScope = rc.scope().$root;
var psIndex = -1;
if (SHOP.Transactional.Breakpoint.isPhone() && isRec) {
psIndex = mobGetModuleGroupIndex($this);
} else {
psIndex = $('.vuePOC').index($(e.target).closest('#ProductStackContainer'));
}
if (psIndex !== -1) {
itemIndex = $this.attr('data-index');
moduleIndex = psIndex;
quikViewService.quikViewModal = Dell.Services.DataModel.ModuleGroups[psIndex].Items[itemIndex];
//$rootScope.$apply();
$rootScope.$broadcast('loadQuikviewModal');
$('#quikview-modal').off('show.bs.modal').on('show.bs.modal', function () {
if (Dell.Services.DataModel.ModuleGroups[psIndex].ItemStates[itemIndex].IsSelected) {
$('#quikview-modal .quikViewCta a').removeClass('btn-success').addClass('btn-default').html($('[data-scope]').attr('data-remove-label'));
} else {
$('#quikview-modal .quikViewCta a').removeClass('btn-default').addClass('btn-success').html(Dell.Services.DataModel.ModuleGroups[psIndex].Items[itemIndex].Stack.Links.AddToCartLink.Caption);
}
}).modal('show');
}
});
if (isRec) {
$('.dellmetrics-recomaddtocart').each(function () {
var metrics = $(this).data('metrics');
metrics.quantity = 1;
metrics.module = $(this).closest('.off-canvas-state').attr('id');
$(this).attr('data-metrics', JSON.stringify(metrics));
});
if ($('[data-soldout=true]').length) {
$('.addItemToCartCta').hide();
}
}
AddMapPriceSkuToCart();
if (hasPerfMetrics)
Dell.perfmetrics.end('ProductStackLinks-binding');
};
var populateFastDelivery = function (i) {
// populateFastDelivery(fastdelivery.ModalTitle.Value, fastdelivery.ModalBody.Value, fastdelivery.ModalReturnButtonLabel.Value, fastdelivery.Continue3RdPartyWebsiteLink.Caption, fastdelivery.Continue3RdPartyWebsiteLink.Url,
// metricsClass, doctype, position, variant, '@productid')
var fdm = document.getElementById('fast-delivery-modal');
if (fdm !== null && i !== null && vm !== null && i < vm.length) {
var s = vm[i];
var fd = s.Stack.FastDelivery;
fd.variant = s.Stack.Type !== 2 ? s.Stack.ItemIdentifier : s.Stack.Sku.Value;
fd.productId = getId(s);
if (typeof angular === 'undefined') {
fd.position = i;
$(document).trigger('fastDeliveryModelData', { fastDeliveryModel: fd });
} else {
$(document).trigger('bootstrapChk');
var $s = angular.element(fdm).scope();
$s.$apply(function () {
$s.fastDeliveryModel.body = fd.ModalBody.Value || '';
$s.fastDeliveryModel.continue3RdPartyWebsiteLinkCaption = fd.Continue3RdPartyWebsiteLink.Caption || '';
$s.fastDeliveryModel.continue3RdPartyWebsiteLinkUrl = fd.Continue3RdPartyWebsiteLink.Url || '';
$s.fastDeliveryModel.productid = getId(vm[i]);
$s.fastDeliveryModel.returnLabel = fd.ModalReturnButtonLabel.Value;
$s.fastDeliveryModel.title = fd.ModalTitle.Value;
$s.fastDeliveryModel.variant = s.Stack.Type !== 2 ? s.Stack.ItemIdentifier : s.Stack.Sku.Value;
$s.fastDeliveryModel.snpRedirectTo3RdPartyWebsiteLinkUrl = fd.SnpRedirectTo3RdPartyWebsiteLink ? (fd.SnpRedirectTo3RdPartyWebsiteLink.Url || '') : '';
$s.fastDeliveryModel.modalTimer = fd.ModalTimer;
$s.fastDeliveryModel.fastDeliveryModalEnabled = fd.FastDeliveryModalEnabled;
if (typeof fd.FastDeliveryModalEnabled == 'string' || fd.FastDeliveryModalEnabled instanceof String) {
$s.fastDeliveryModel.fastDeliveryModalEnabled = fd.FastDeliveryModalEnabled.toLowerCase() === "true" ? true : false;
}
//Assign the snpRedirectTo3RdPartyWebsiteLinkUrl to continue3RdPartyWebsiteLinkUrl so keep the one variable to redirect
if (typeof $s.fastDeliveryModel.snpRedirectTo3RdPartyWebsiteLinkUrl !== 'undefined' &&
$s.fastDeliveryModel.snpRedirectTo3RdPartyWebsiteLinkUrl !== "" && $s.fastDeliveryModel.snpRedirectTo3RdPartyWebsiteLinkUrl.indexOf('?sku=') !== -1) {
$s.fastDeliveryModel.continue3RdPartyWebsiteLinkUrl =
$s.fastDeliveryModel.snpRedirectTo3RdPartyWebsiteLinkUrl;
}
});
}
}
};
var mobGetModuleGroupIndex = function ($t) {
var id = $t.closest('.seriesFamilyTablet').attr('id').replace('-content', '');
for (var i = 0; i < Dell.Services.DataModel.ModuleGroups.length; i++) {
if (Dell.Services.DataModel.ModuleGroups[i].Id == id)
return i;
}
}
$this.vueMixins = function () {
vueMixinCalled = true;
Vue.mixin({
methods: {
rowSet: function (d) {
return [this.Stacks];
},
rowCount: function () {
return $this.rows;
},
getRow: function (i) {
if (!isRec) {
var max = $this.ipr * i;
return this.Stacks.slice((max - $this.ipr), (max < this.Stacks.length ? max : this.Stacks.length));
} else {
if (!$this.isMobile)
return this.Stacks;
else
return [this.Stacks[i - 1]];
}
},
getIndex: function (i, r) {
return (((r - 1) * $this.ipr) + i);
},
comparecount: function () {
return "(" + amplify.store('productOC:size') + '/3)';
},
isZeroOrNull: function (v) {
return (v == null || Number(v.replace(/[^\d]/g, '')) === 0);
},
isNullOrEmpty: function (v) {
return (typeof v === 'undefined' || v === null || v.length === 0);
},
isAny: function (a) {
return (typeof a !== 'undefined' && a !== null && a.length > 0);
},
isEnterprisePd: function () {
return $('#product-details-txn').length > 0;
},
isSingleOc: function () {
return isSingleOc;
},
isPhone: function () {
return SHOP.Transactional.Breakpoint.isPhone();
},
checkWin10: function () {
return user.Country.toLowerCase() === 'us' && user.Segment.toLowerCase() === 'bsd';
},
isSeg: function (s) {
return user.Segment.toLowerCase() === s.toLowerCase();
},
isCtry: function (c) {
return user.Country.toLowerCase() === c.toLowerCase();
},
isAuthenticated: function (c) {
return !user.IsAuthenticated ? false : user.IsAuthenticated;
},
comoCss: function (t) {
//check como state
return comoCheck(t) ? '' : 'ng-hide';
},
getUrlWithReturnUrl: function (u) {
var currentUrl = window.location.href;
var urlWithReturnUrl = u.indexOf('') > -1 ? u + currentUrl : u + '&returnurl=' + encodeURIComponent(currentUrl);
return urlWithReturnUrl;
},
getCurrItemJson: function (i) {
return JSON.stringify(i);
},
getDataMetricAttr: function (i, p, snp) {
var mo = {
clickthru: 'products',
doctype: (i.Stack.Type === snp ? 'snp' : 'systems'),
position: p,
variant: (i.Stack.Type !== snp ? i.Stack.ItemIdentifier : i.Stack.Sku.Value)
};
return JSON.stringify(mo);
},
fillId: function (i, s) {
return s.replace(/#id#/g, getId(i));
},
id: function (i, pre, f) {
var noSpaces = f !== undefined ? f : true;
return (pre || '') + getId(i, f);
},
getOrderCode: function (i, s) {
return (s || '') + getOrderCode(i);
},
soaShowShippingMessaging: function (t, i) {
var r = true;
if (typeof t != "undefined" && typeof i.Stack.SnpStock.Status != "undefined") {
if (t && i.Stack.SnpStock.Status === 6)
r = false;
}
return r;
},
soldOutCss: function (i) {
return i.Stack.ProductSoldOut && !isSingleOc ? ' sold_out' : '';
},
showMarketingBlurbImageBottom: function (i) {
return i.Options.Settings.ShowMarketingBlurb && i.Stack.MarketingBlurb.ShowMarketingBlurb
? " image-cell-bottom"
: "";
},
nabiscoColorOverride: function (i) {
var isMultiOcAlienwarePage = $("body.alienware-white").length === 1;
var applyBorderColor = !i.Stack.ProductSoldOut && (i.Stack.Treatment === 2 && isMultiOcAlienwarePage ? false : true);
return applyBorderColor ? ' border-left-color:' + window.nabiscoOverrideColor : '';
},
ctaUrl: function (link) {
var linkUrl = link.Url;
if (link.IsCustomizeAndBuy) {
if (SHOP.Transactional.Breakpoint.isPhone()) {
linkUrl += "/configurations";
} else {
linkUrl += "?view=configurations";
}
}
return linkUrl;
},
ctaCss: function (i, hasColor) {
//dellmetrics-recomaddtocart --> candyAisle
//dellmetrics-browseconfig --> single OC
var s = 'addItemToCartCta btn text-white col-xs-12 bottom-offset-10 whitespace-normal';
if (isRec)
s += ' dellmetrics-recomaddtocart';
if (isSingleOc)
s += ' dellmetrics-browseconfig';
if (i && i.Options.Settings.Location == 10)
s += ' dellmetrics-addtocart';
s += !hasColor ? ' btn-success' : ' btn-'
return s;
},
getDataMetricAttrWithprice: function (i, p, snp) {
var mo = {
clickthru: 'products',
doctype: (i.Stack.Type === snp ? 'snp' : 'systems'),
position: p,
variant: (i.Stack.Type !== snp ? i.Stack.ItemIdentifier : i.Stack.Sku.Value),
productid: (i.Stack.Type !== snp ? i.Stack.ItemIdentifier : i.Stack.Sku.Value),
price: i.Stack.Pricing.DellPrice.InnerValue,
option: (i.Stack.Sku != 'undefined' ? i.Stack.Sku.Value : "")
};
return JSON.stringify(mo);
},
buttonColour: function (i) {
switch (i) {
case 0:
return 'success';
case 1:
return 'primary';
default:
return 'default';
}
},
reviewSummaryUrl: function (errors) {
if ((!errors || !Dell.Controllers.vueConfig.errorHasMod(errors)) && Dell.Services.DataModel.ReviewSummaryLink)
return Dell.Services.location.search('selectionState', Dell.Services.DataModel.Stacks[0].ConfigurableItem.SelectionState, Dell.Services.DataModel.ReviewSummaryLink.Url);
else
return '#';
},
hasValidationErrors: function (errors) {
return !errors ? false : errors.length > 0;
},
getVariant: function (item) {
var productVariant = parseInt(item.Stack.Type) !== 0 ? item.Stack.ItemIdentifier : item.Stack.ProductCode.Value;
return productVariant;
}
}
});
};
function inverseInfoExpander() {
$('.moreInfoExpander').hide();
$('.hideInfoExpander').hide();
$('div[class*="hide-ps-details"]').show();
}
function resetInfoExpander() {
$('.moreInfoExpander').show();
$('.hideInfoExpander').hide();
$('div[class*="hide-ps-details"]').hide();
}
$this.init = function () {
vm = Dell.Services.DataModel ? Dell.Services.DataModel.Stacks || Dell.Services.DataModel.Stack || (Dell.Services.DataModel.AnavFilterModel ? Dell.Services.DataModel.AnavFilterModel.Results.Stacks : []) : [];
if (vm.length > 0) {
om = JSON.parse(JSON.stringify(vm));
} else {//compare page
var compareCategories = Dell.Services.DataModel ? Dell.Services.DataModel.CompareCategories : [];
for (var i in compareCategories) {
if (compareCategories.hasOwnProperty(i)) {
var containers = compareCategories[i].Containers;
for (var container in containers) {
if (containers.hasOwnProperty(container))
vm.push(containers[container]);
}
}
}
if (vm.length > 0)
om = JSON.parse(JSON.stringify(vm));
}
$this.ipr = Dell.Services.productstack.getItemsPerRow();
//$('.compare-checkbox input:checked').each(function () {
// //$(this).prop('checked', false);
// //$(this).click();
//});
$this.vueMixins();
var firstRowIPR = $('stackrow:first .ups-title').length;
var iprIncorrect = (firstRowIPR > $this.ipr || ($this.ipr > firstRowIPR && vm.length > firstRowIPR)); //check to see if ITEMS PER ROW is incorrectly caluclated and too many/little items are displayed per row
if (((isMultiOc && iprIncorrect) || ($('#accessoryResults').length > 0 && $this.ipr !== firstRowIPR)) || (isDeals && $this.ipr < firstRowIPR) || ($this.ipr > 1 && SHOP.Transactional.Breakpoint.isPhone()))
$this.updateStacks(vm);
else if (resultsPage && !$this.mapPersonalization)
$this.renderDiecut(vm);
else
$this.determineLayout();
checkComo();
$document.trigger('bootstrapChk');
bindLinks();
bindPersonalized();
//trigger correct behavior for clearing pd anav
var pd = document.getElementById('product-details');
if (pd !== null && typeof shopApp !== 'undefined') {
$document.ready(function () {
var $s = angular.element('#product-details').scope();
if ($s !== undefined && $s !== null)
$s.$apply(function () {
$s.$on('updateOriginalModel',
function (event, originalModel) {
om = originalModel;
});
$s.$on('resetAnav',
function () {
if (om !== undefined)
$this.updateStacks(om);
});
});
});
}
/*if ($scope.$parent.DataModel && $scope.$parent.DataModel.ModuleGroups) {
$scope.moduleIndex = $scope.$parent.getProductStackIndex();
$scope.DataModel.Stacks = $scope.$parent.DataModel.ModuleGroups[$scope.moduleIndex].Items;
}
if ($scope.DataModel)
$scope.modelStacks = angular.copy($scope.DataModel.Stacks);
$scope.determineLayout();
if ($rootScope.IsAnalyticsConfigurator) {
$rootScope.metricsClass = "dellmetrics-browseconfig";
}*/
$document.trigger('ngRepeatFinished');
};
$this.determineLayout = function () {
$this.setViewPort();
$this.ipr = Dell.Services.productstack.getItemsPerRow();
/*if ($('#featuredItems').length > 0 || ($('.recommendations-container').length > 0 && !($(window).width() < 768))) {
$this.ipr = $scope.modelStacks.length;
}*/
if (isCompare) { $this.ipr = vm.length; }
$this.rows = $('#polaris-pd #multipleConfigsController').length === 0 && ((!isCompare && !isRec) || $this.isMobile) ? Dell.Services.productstack.getNumberOfRows(vm) : 1;
};
$this.updatePagination = function () {
if (isMultiOc) {
$this.ipr = Dell.Services.productstack.getItemsPerRow();
var start = (curPg - 1) * $this.ipr + 1;
var max = vm.length > 0 ? (vm.length < (start + $this.ipr - 1) ? vm.length : (start + $this.ipr - 1)) : $this.ipr;
$('#current-item-range').text(start + '-' + max); // TODO: localize item range
}
}
$this.setViewPort = function () {
$this.isMobile = SHOP.Transactional.Breakpoint.isPhone();
$this.isTablet = SHOP.Transactional.Breakpoint.isTablet();
$this.isDesktop = SHOP.Transactional.Breakpoint.isDesktop();
};
$this.toggleMoreHide = function (t, hide) {
var $t = $(t);
var id = $(t).attr('data-target').split(' ').join('.');
var $more = $('.more-' + id);
if (!hide) {
$more.toggle();
$('.hide-' + id).toggle();
$t.closest('.product-stack-row').find('*[class*="hide-ps-details"]').slideToggle();
} else if (hide && !$more.is(':visible')) {
$more.show();
$('.hide-' + id).hide();
$t.closest('.product-stack-row').find('*[class*="hide-ps-details"]').hide();
}
};
$this.goToCompare = function () {
var orderCodeUrl = Dell.Services.productstack.goToCompare();
window.location.href = $scope.$parent.DataModel.Stacks[0].Stack.Links.CompareLink.Url + orderCodeUrl;
};
$this.expandRow = function (e) {
var parentRow = $(e).closest('.tech-spec-row-group');
$(parentRow).find('.tech-spec-value').each(function (i) {
$(this).find('#show-hide-tech-specs').collapse('toggle');
$(this).find('a').toggleClass('collapsed');
});
};
$this.fullDateString = new Date();
$document.on('click', '.special-offers-modal-jump', function (e) {
e.preventDefault();
var modal_id = e.target.id;
if (modal_id !== undefined) {
var unique_scope_id = $(this).closest(".modal").attr('id');
var modal_id_array = "";
if ($(this).closest(".modal").attr('aria-labelledby') == 'specialOffersModal') {
modal_id_array = unique_scope_id.split('special-offers-modal-');
unique_scope_id = modal_id_array[1];
$('#special-offers-modal-' + unique_scope_id + ' .modal-body').animate({
scrollTop: $('#' + modal_id + '-' + unique_scope_id).offset().top
- ($('#special-offers-modal-' + unique_scope_id).offset().top + 50)
}, 10);
}
}
});
$this.addAndUpdateZipCodeProductStack = function () {
var cfcZipCode = $.cookie('cfcZipCode');
locationCookie = $.cookie('location');
if (typeof locationCookie !== 'undefined' && locationCookie !== "") {
locationCookie = JSON.parse(locationCookie);
}
if ($('.cfcDates').length > 0) {
if (typeof locationCookie !== 'undefined' && typeof locationCookie["zipcode"] !== 'undefined') {
var locationZipCode = locationCookie["zipcode"];
$('.cfcDates:not(:contains("' + locationZipCode + '"))').find('.cfcZipCode').html(' - ' + locationZipCode);
} else if (cfcZipCode) {
$('.cfcDates:not(:contains("' + cfcZipCode + '"))').find('.cfcZipCode').html(' - ' + cfcZipCode);
}
}
};
$window.resize(function () {
if (!resize) {
resize = true;
//check if items per row has changed for non carousel based rows (compare, candy aisle can have multiple stacks in separate carousels)
if (!(isCompare || isRec) && $this.ipr !== Dell.Services.productstack.getItemsPerRow())
$this.updateStacks(vm);
if (($scope.isDesktop && ($('.device-sm').is(':visible') || $('.device-xs').is(':visible'))) ||
($scope.isTablet && $('.device-xs').is(':visible'))) {
$('div[class*="hide-ps-details"]').show();
$('#ProductStackContainer').hide();
} else if ($scope.isMobile && $('.device-xs').is(':hidden')) {
$('div[class*="hide-ps-details"]').hide();
}
Vue.nextTick(function () {
resize = false;
});
}
//$document.trigger('ngRepeatFinished');
/*$scope.waitForFinalEvent(function () {
$scope.determineLayout();
$('.popover-' + $rootScope.popoverId).popover('hide');
$scope.$apply();
$('#ProductStackContainer').show();
$('.productstack-box #ProductStackContainer').show();
addToCompareService.universalAlreadyExistsInStore($scope.modelStacks);
}, 200, $this.fullDateString.getTime());*/
})
.scroll(function () {
if (scrollFired) {
//limit this from being called for every scroll event triggered
$document.trigger('ngRepeatFinished');
setTimeout(function () { scrollFired = false; }, 250);
}
});
if (isSingleOc || isRec) {
//store the selectionState to handle server side and load the correct selectionState on back/forward history change
//(overrides old URL param if cookie is present and does not match the URL param of the given page)
//server side will remove this cookie once used
$window.on('beforeunload', function storeSelectionsOnNavigate() {
var state = !isRec ? (Dell.Services.DataModel.Stacks[0] && Dell.Services.DataModel.Stacks[0].ConfigurableItem ? Dell.Services.DataModel.Stacks[0].ConfigurableItem.SelectionState : Dell.Services.location.search().selectionState) :
Dell.Services.DataModel.SelectionCode;
Dell.util.setCookie('lastKnownSelectionState', state, '.dell.com', '/');
})
.on('unload', function removeSelectionsOnNavigate() {
Dell.util.setCookie('lastKnownSelectionState', '', '.dell.com', '/');
});
}
$('.backToRoot').on('click.vmReset', function () {
if (SHOP.Transactional.Breakpoint.isPhone())
vm = [];
});
/*$('body').click(function (e) {
if (!$(e.target).is('.popover, .popover-title, .popover-content')) {
$('.popover-' + $rootScope.popoverId).popover('destroy');
}
if ($(e.target).attr('data-ng-click') === "goToCompare()") {
$scope.goToCompare();
}
});*/
if ($pStack.length > 0) {
defineComponents();
$document.ready(function () { $this.init(); });
if (resultsPage)
$document.trigger('updateMerchTiles');
}
}).call(Dell.Controllers.productstack);
})(jQuery, window, document, History);
;
var Dell = window.Dell || {};
Dell.Controllers = Dell.Controllers || {};
Dell.Controllers.comparectrl = {};
var SHOP = window.SHOP || {};
SHOP.Transactional = SHOP.Transactional || {};
SHOP.Transactional.Compare = SHOP.Transactional.Compare || {};
(function ($, window, document) {
(function () {
'use strict';
var $this = this,
om = [],
vm = [],
$document = $(document),
$stackScope = $('#ProductStackContainer.vuePOC'),
$scope = $('#comparectrl'),
categories = $('ul.dropdown-menu[data-category]'), // Add all Specs for each Category, to category specific arrays
optionsByCategory = {};
$this.groupId = '';
$this.groupIndex = 0;
categories.toArray().forEach(function (el) {
var cat = $(el),
catName = cat.data('category');
optionsByCategory[catName] = cat.find('a[data-value]').toArray().map((function (el) { return $(el).data('value'); }));
});
$this.scrollNavSize = function () {
var carouselWidth = $('#ProductStackContainer').width();
//$('.compare-scrolling-nav').width(carouselWidth);
};
$document.ready(function () {
$this.scrollNavSize();
var ALLSPECS = 'ALLSPECS';
// Jump To Navigation
$('.category-group a').click(function (e) {
e.preventDefault();
var href = $(this).attr("href");
var $el = $(href);
if ($el.length > 0)
$('html, body').animate({
scrollTop: $el.offset().top
}, 1000);
});
function toggleAllSpecs(el, options) {
var optionsCount = 0,
optionFound = options.indexOf(ALLSPECS) > -1,
allSpecsInput;
el.closest('ul').find('li').each(function (i, li) {
if ($(li).find('a').attr('data-value') === ALLSPECS) {
allSpecsInput = $(li).find('input');
}
optionsCount++;
});
var toggleCheckbox = (!optionFound ? optionsCount - 1 : optionsCount) === options.length;
if (toggleCheckbox) {
if (!optionFound) {
options.push(ALLSPECS);
}
} else {
if (optionFound) {
options.splice(options.indexOf(ALLSPECS), 1);
}
}
setTimeout(function () {
allSpecsInput.prop('checked', toggleCheckbox)
}, 0);
}
// Tech Spec Dropdown
$('.compare-spec-controls-section .dropdown-menu a').on('click', function (event) {
var $target = $(event.currentTarget),
val = $target.attr('data-value'),
$inp = $target.find('input'),
idx,
cat = $(this).closest('ul').attr('data-category'),
options = optionsByCategory[cat],
isChecked = options.indexOf(val) > -1,
specCount;
if (val === ALLSPECS) {
isChecked = !isChecked;
$(this).closest('ul').find('li').each(function (i, li) {
var input = $(li).find('input'),
dataValue = $(li).find('a').attr('data-value'),
singleOption = $('.ts-' + cat).find("[data-spec-code='" + dataValue + "']"),
optionFound = options.indexOf(dataValue) > -1;
if (isChecked) {
if (!optionFound) {
options.push(dataValue);
}
singleOption.show();
} else {
if (optionFound) {
options.splice(options.indexOf(dataValue), 1);
}
singleOption.hide();
}
setTimeout(function () {
input.prop('checked', isChecked)
}, 0);
});
} else {
if ((idx = options.indexOf(val)) > -1) {
options.splice(idx, 1);
setTimeout(function () {
$inp.prop('checked', false)
}, 0);
$('.ts-' + cat).find("[data-spec-code='" + val + "']").hide();
toggleAllSpecs($(this), options);
} else {
options.push(val);
setTimeout(function () {
$inp.prop('checked', true)
}, 0);
$('.ts-' + cat).find("[data-spec-code='" + val + "']").show();
toggleAllSpecs($(this), options);
}
}
var specCount = options.indexOf(ALLSPECS) > -1 ? options.length - 1 : options.length;
$('#category-' + cat + ' span.spec-total').html(specCount);
return false;
});
// Removing a Product from the carousel by click the X
$document.on('click', '.compare-page-carousel .remove-product span', function (e) {
var pid = $(this).attr('data-id');
var product = Dell.Controllers.productstack.getProduct({ id: pid, noSpaces: true }, Dell.Services.DataModel.Stacks);
$this.removeOrderCode(e, (product.Stack.Type !== 2 ? product.Stack.ItemIdentifier : product.Stack.Sku.Value));
});
$('button.slick-next').on('click', function (e) { $this.swippingLeft(e) });
$('button.slick-prev').on('click', function (e) { $this.swippingRight(e) });
$('.touch-scroll').on('swipeleft', function (e) { $this.swippingLeft(e) })
.on('swiperight', function (e) { $this.swippingRight(e) });
$document.on('updateProductStacks', function (e) {
var $specsfilter = $('.compare-spec-controls-section .dropdown-menu a');
$specsfilter.find('input').not(':checked').each(function() {
$(this).trigger('click');
});
});
});
// Local Resize Event Listener
$(window).resize(function () {
$this.scrollNavSize();
});
// Local Orientation Change Event Listener
$(window).on('orientationchange', function () {
$this.scrollNavSize();
});
$this.getProductStackIndex = function () {
var currentCount = $rootScope.psCount;
$rootScope.psCount = $rootScope.psCount + 1;
return currentCount;
};
$this.disableNextButton = function (list, id) {
$('.ca-next-' + id).prop('disabled', true);
return list.length;
};
$this.swippingLeft = function (e) {
var lastItem = e.currentTarget.childElementCount === 0 ? e.currentTarget.getAttribute('data-count') : e.currentTarget.childElementCount;
var id = e.currentTarget.getAttribute('data-id');
$this.moveCandyCarouselRight(id, lastItem);
$this.loadImage();
};
$this.swippingRight = function (e) {
var lastItem = e.currentTarget.childElementCount === 0 ? e.currentTarget.getAttribute('data-count') : e.currentTarget.childElementCount;
var id = e.currentTarget.getAttribute('data-id');
$this.moveCandyCarouselLeft(id, lastItem);
$this.loadImage();
};
$this.moveCandyCarouselRight = function (id, last) {
var $candyCarousel = $('.ts-' + id);
var $scrollbar = $('.ts-' + id + ' .compare-scrolling-nav');
$candyCarousel.animate({ scrollLeft: $candyCarousel.scrollLeft() + $candyCarousel.width() }, 500);
$scrollbar.animate({ scrollLeft: $scrollbar.scrollLeft() + $scrollbar.width() }, 500);
$('.ca-prev-' + id).prop('disabled', false);
if (($candyCarousel.width() * 2 + $candyCarousel.scrollLeft()) >= $candyCarousel[0].scrollWidth) {
$('.ca-next-' + id).prop('disabled', true);
var firstItem = $('.device-sm').is(':visible') ? parseInt(last) - 2 : parseInt(last) - 3;
$('.last-visible-item-' + id).html(last);
$('.first-visible-item-' + id).html(firstItem);
} else {
$this.determinePosition(id, last);
}
};
$this.moveCandyCarouselLeft = function (id, last) {
var $candyCarousel = $('.ts-' + id);
var $scrollbar = $('.ts-' + id + ' .compare-scrolling-nav');
$candyCarousel.animate({ scrollLeft: $candyCarousel.scrollLeft() - $candyCarousel.width() }, 500);
$scrollbar.animate({ scrollLeft: $scrollbar.scrollLeft() - $scrollbar.width() }, 500);
$('.ca-next-' + id).prop('disabled', false);
if (($candyCarousel.scrollLeft() - $candyCarousel.width()) <= 0) {
//return to initial state
$('.ca-prev-' + id).prop('disabled', true);
$('.first-visible-item-' + id).html(1);
$('.last-visible-item-' + id).html($('.device-sm').is(':visible') ? 3 : 4);
} else {
$this.determinePosition(id, last);
}
};
$this.loadImage = function() {
//lazy load images when position realigned due to scroll, swipe etc
setTimeout(function() {
$('img.lazy').lazyload();
},600);
};
$this.determinePosition = function (id, count) {
var $candyCarousel = $('.ts-' + id);
var offset = Math.abs($candyCarousel.scrollLeft() - $candyCarousel.width());
var hiddenColumns = offset === $candyCarousel.width() ? 0 : Math.round(offset / $candyCarousel.width());
var first = hiddenColumns + 1;
var last = $('.device-sm').is(':visible') ? first + 2 : first + 3;
last = last > count ? count : last;
//(first === 1) ? $('.ca-prev-' + id).prop('disabled', true) : $('.ca-prev-' + id).prop('disabled', false);
//(last === count) ? $('.ca-next-' + id).prop('disabled', true) : $('.ca-next-' + id).prop('disabled', false);
$('.first-visible-item-' + id).html(first);
$('.last-visible-item-' + id).html(last);
};
$this.syncToAmplify = function () {
if (window.location.search === "" || window.location.search === "?ocs=") {
if (amplify.store('productOC:size') > 0) {
$this.loadAmplifyOrderCodes();
}
} else {
if (vm.length === 0 && window.location.search.indexOf('ocs=') >= 0) {
var queryString = window.location.search;
var splitQueryString = queryString.split('?ocs=');
var orderCodes = splitQueryString[1].split(',');
var ocs = amplify.store('productOC');
if (typeof ocs !== 'undefined' && ocs != null) {
$.each(ocs,
function(id) {
var remove = false;
$.each(orderCodes,
function(ocs) {
if (id === ocs) {
remove = true;
}
});
if (remove) {
SHOP.Transactional.Compare.removeProduct(id, "ups");
}
});
}
if (amplify.store('productOC:size') > 0) {
$this.loadAmplifyOrderCodes();
}
} else if (vm.length > 0) {
var ocs = amplify.store('productOC');
if (typeof ocs !== 'undefined' && ocs != null) {
$.each(ocs,
function(id) {
var remove = true;
$.each(vm,
function(i, categories) {
$.each(categories.Containers,
function(ix, stacks) {
var compareIdentifier =
stacks.Stack.Type !== 2
? stacks.Stack.ItemIdentifier
: stacks.Stack.Sku.Value;
if (id === compareIdentifier) {
remove = false;
}
});
});
if (remove) {
SHOP.Transactional.Compare.removeProduct(id, "ups");
}
});
}
}
var ocquerystring = Dell.Services.location.search().ocs.split(','),
storedOcs = amplify.store('productOC'),
storedOcsLength = amplify.store('productOC:size'),
queryStringIds = '',
separator = '';
if (ocquerystring.length !== storedOcsLength) {
$.each(ocquerystring, function (i, oc) {
if (storedOcs !== undefined && storedOcs[oc]) {
queryStringIds += separator + oc;
if(i < ocquerystring.length)
separator = ',';
}
});
var uri = Dell.Services.location.search('ocs', queryStringIds);
History.replaceState({ cmpstacks: queryStringIds }, document.title, uri);
//$this.updateCmpStacks($this.getOCStacks(queryStringIds, true));// remove ocs from url that are not in amplify
}
}
};
$this.loadAmplifyOrderCodes = function () {
var amplifyOrderCodes = [],
ids = "";
var ocs = amplify.store('productOC');
if (typeof ocs !== 'undefined' && ocs != null) {
$.each(ocs,
function(oc) {
amplifyOrderCodes.push(oc);
});
}
for (var i = 0; i < amplifyOrderCodes.length; i++) {
ids += (i === 0) ? amplifyOrderCodes[i] : "," + amplifyOrderCodes[i];
}
History.replaceState({ cmpstacks: ids }, document.title, ("?ocs=" + ids));
//window.location.href = location.pathname + returnUrl;
};
$this.addOCStacks = function (ocs) {
var ocArray = ocs.split(','),
addProdObj = {};
$.each(ocArray, function (i, oc) {
$.each(om, function (k, categories) {
$.each(categories.Containers, function (ix, stacks) {
var localId = stacks.Stack.Type !== 2 ? stacks.Stack.ItemIdentifier : stacks.Stack.Sku.Value;
if (!amplify.store(localId)) { // add products to amplify with history state changes
addProdObj.productId = localId;
addProdObj.title = stacks.Stack.Title.Value;
addProdObj.image = stacks.Stack.ProductImage.Value;
addProdObj.showMarketPrice = stacks.Stack.Pricing.MarketValue.Value;
addProdObj.dellPrice = stacks.Stack.Pricing.DellPrice.Value;
addProdObj.pdUrl = stacks.Stack.Links.ViewDetailsLink.Value + '?ref=fromchatdrawer';
addProdObj.showclicktoseeprice = stacks.Stack.Pricing.ShowClickToSeePrice;
addProdObj.showPricingTooltip = stacks.Stack.Pricing.ShowPricingTooltip;
addProdObj.pricingTooltipTitle = stacks.Stack.Pricing.PricingTooltipTitle.Value;
addProdObj.pricingTooltipDescription = stacks.Stack.Pricing.PricingTooltipDescription.Value;
amplify.store(localId, addProdObj);
SHOP.Transactional.Compare.persistProduct(localId);
}
});
});
});
};
$this.getOCStacks = function (ocs,removeoc) {
var ocArray = ocs.split(','),
tempStacks = [],
merchStack = {};
$.each(ocArray, function (i, oc) {
$.each(om[$this.groupIndex].Containers,function(ix, stacks) {
var localId = stacks.Stack.Type !== 2 ? stacks.Stack.ItemIdentifier : stacks.Stack.Sku.Value;
if (localId === oc) {
tempStacks.push(stacks);
} else if ($.isEmptyObject(merchStack) && stacks.IsMerchandisingContainer) {
merchStack = stacks;
}
});
});
if (!$.isEmptyObject(merchStack))
tempStacks.push(merchStack); // push merch last
return [tempStacks];
};
$this.removeOrderCode = function ($event, id) {
var closeX = $event.target;
var catId = $this.groupId = $(closeX).closest('div[data-id]').attr('data-id');
var catIndex = $this.groupIndex = parseInt($(closeX).closest('div[data-group]').attr('data-group'));
//remove from amplify storage
SHOP.Transactional.Compare.removeProduct(id, "ups");
//remove from DataModel.Stacks and rebind UI
var tempStacks = [];
var tempStackCount = [];
var queryStringIds = "";
var stackCount = 0;
var productsInCompare = "";
$.each(vm[catIndex].Containers, function (ix,stacks) {
var localId = stacks.Stack.Type !== 2 ? stacks.Stack.ItemIdentifier : stacks.Stack.Sku.Value;
if (localId !== id) {
tempStacks.push(stacks);
}
if (localId !== id && localId !== "") {
tempStackCount.push(stacks);
}
});
$.each(vm, function (i,categories) {
if (i === 0) {
$.each(categories.Containers, function (ix, stacks) {
var localId = stacks.Stack.Type !== 2 ? stacks.Stack.ItemIdentifier : stacks.Stack.Sku.Value;
// This statement is needed to prevent the "Merchandizing Tile" from being added to the URL. The Merchandizing tile has no ItemIdentifier.
if (localId !== id && localId !== "") {
queryStringIds += (stackCount === 0) ? localId : "," + localId;
if (stacks.Stack.ProductCode.Value == "") {
productsInCompare += (stackCount === 0) ? stacks.Stack.Sku.Value : "|" + stacks.Stack.Sku.Value;
} else {
productsInCompare += (stackCount === 0) ? stacks.Stack.ProductCode.Value : "|" + stacks.Stack.ProductCode.Value;
}
stackCount++;
}
});
} else {
$.each(categories.Containers, function (ix,stacks) {
var localId = stacks.Stack.Type !== 2 ? stacks.Stack.ItemIdentifier : stacks.Stack.Sku.Value;
// This statement is needed to prevent the "Merchandizing Tile" from being added to the URL. The Merchandizing tile has no ItemIdentifier.
if (localId !== id && localId !== "") {
queryStringIds += (queryStringIds) ? "," + localId : localId;
if (stacks.Stack.ProductCode.Value == "") {
productsInCompare += (stackCount === 0) ? stacks.Stack.Sku.Value : "|" + stacks.Stack.Sku.Value;
} else {
productsInCompare += (stackCount === 0) ? stacks.Stack.ProductCode.Value : "|" + stacks.Stack.ProductCode.Value;
}
stackCount++;
}
});
}
});
// Update Conversant
if (typeof MasterTmsUdo !== 'undefined') {
MasterTmsUdo.CJ.PRODUCT = productsInCompare;
MasterTmsUdo.CJ.ORDERCODE = queryStringIds.replace(/,/g, '|');
}
// Update URL Query String
var uri = Dell.Services.location.search('ocs', queryStringIds);
History.replaceState({ cmpstacks: queryStringIds, removeoc: true }, document.title, uri);
//$this.updateCmpStacks([tempStacks]);
//var jumpCat = 'a[href="#category-' + catId + '"] span.category-group-count';
//var headerCat = 'div#category-' + catId + ' .category-header-group-count';
//$(jumpCat).html(tempStackCount.length);
//$(headerCat).html(tempStackCount.length);
if (tempStacks.length === 1) {
var compareControls = 'div#category-' + catId;
var compareCarousel = 'div#carousel-' + catId;
var jumpTitle = 'span#nav-' + catId;
$(compareControls).hide();
$(compareCarousel).hide();
$(jumpTitle).hide();
}
if (stackCount === 0) {
$('.category-navigation').addClass('hidden');
$('#no-products').show();
}
};
$this.updateCmpStacks = function (d) {
var tempStackCount = [],
noprodshow = true,
catIndex = $this.groupIndex;
$.each(d[0], function (ix, stacks) {
var localId = stacks.Stack.Type !== 2 ? stacks.Stack.ItemIdentifier : stacks.Stack.Sku.Value;
if (localId !== "") {
tempStackCount.push(stacks);
}
});
var compareControls = '#category-'+$this.groupId;
var compareCarousel = '#carousel-'+$this.groupId;
var jumpTitle = '#nav-' + $this.groupId;
if (catIndex >= 0) {
vm[catIndex].Containers = d[0];
}
$.each(vm, function (k, categories) {
if (categories.Containers.length > 1)
noprodshow = false;
});
if (!noprodshow) {
$('#no-products').hide();
$(compareControls).find('.category-header-group-count').html(tempStackCount.length);
$('a[href="#category-' + $this.groupId + '"] span.category-group-count').html(tempStackCount.length);
$(compareCarousel).find('.slick-arrow').attr('data-count', tempStackCount.length);
$(compareControls).show();
$(compareCarousel).show();
$(jumpTitle).show();
} else if ($scope.length > 0 && noprodshow) {
$('#no-products').show();
$(compareControls).hide();
$(compareCarousel).hide();
$(jumpTitle).hide();
}
$document.trigger('updateCompare', d);
};
var updateCompareBtn = function () {
$('.compare-checkbox input').prop('checked', false).val(false);
var ocs = amplify.store('productOC');
if (typeof ocs !== 'undefined' && ocs != null) {
$.each(ocs,
function (oc) {
var lwrOc = oc.split(' ').join('-').toLowerCase();
$('span.add-to-compare-' + lwrOc).addClass('hidden');
//updateCompareCount($('a.addToCompare-' + oc).removeClass('hidden'));
$('a.addToCompare-' + lwrOc).removeClass('hidden');
var $chk = $('.checkbox-' + lwrOc);
if (typeof $chk !== 'undefined' && $chk.length > 0)
$('.checkbox-' + lwrOc)[0].checked = true;
});
}
};
var toggleCheckMark = function (e) {
var $elem = $(this);
var productId = $elem.attr('class').indexOf('-') > -1 ? $elem.attr('class').split('-').slice(1).join('-') : $elem.attr('class'); //we have symbol "-" in order code
var product = Dell.Controllers.productstack.getProduct({ id: productId, noSpaces: true });
var compareObj = new Object();
compareObj.productId = product.Stack.Type !== 2 ? product.Stack.ItemIdentifier : product.Stack.Sku.Value;
compareObj.title = product.Stack.Title.Value;
compareObj.image = product.Stack.ProductImage.Value;
compareObj.showMarketPrice = product.Stack.Pricing.ShowMarketPrice;
compareObj.marketPrice = product.Stack.Pricing.MarketValue.Value;
compareObj.dellPrice = product.Stack.Pricing.DellPrice.Value;
compareObj.pdUrl = product.Stack.Links.ViewDetailsLink.Value + '?ref=fromchatdrawer';
compareObj.showclicktoseeprice = product.Stack.Pricing.ShowClickToSeePrice;
compareObj.snpStockStatus = product.Stack.SnpStock.Status;
compareObj.showPricingTooltip = product.Stack.Pricing.ShowPricingTooltip;
compareObj.pricingTooltipTitle = product.Stack.Pricing.PricingTooltipTitle.Value;
compareObj.pricingTooltipDescription = product.Stack.Pricing.PricingTooltipDescription.Value;
//var productIdCssClass = productId.split(' ').join('.');//split and join added to handle when have space in the OC.
if (this.checked) {
amplify.store(compareObj.productId, compareObj);
SHOP.Transactional.Compare.persistProduct(compareObj.productId);
if (!SHOP.Transactional.Breakpoint.isPhone() && amplify.store('productOC:size') > 1)
SHOP.Transactional.CompareDrawer.openDrawer();
//Display Compare CTA
$('span.add-to-compare-' + productId).addClass('hidden');
$('a.addToCompare-' + productId).removeClass('hidden');
} else {
amplify.store(compareObj.productId, null);
SHOP.Transactional.Compare.removeProduct(compareObj.productId);
//Remove Compare CTA
$('a.addToCompare-' + productId).addClass('hidden');
$('span.add-to-compare-' + productId).removeClass('hidden');
}
};
var goToCompare = function (e, t) {
var orderCodeUrl = Dell.Services.productstack.goToCompare();
var compareUrl = $(t).attr('data-href');
compareUrl = (compareUrl) ? compareUrl : $('#compare-drawer .compare-btn a').attr('href');
window.location.href = compareUrl + orderCodeUrl;
};
$this.initCompareBtn = function() {
if (typeof $stackScope !== 'undefined' && $stackScope.length > 0) {
$document.off('click.compare', '.compare-checkbox input').on('click.compare', '.compare-checkbox input', toggleCheckMark);
$document.off('click.compare', '.compare-checkbox a.btn, .goToCompare').on('click.compare', '.compare-checkbox a.btn, .goToCompare', function (e) { goToCompare(e, this) });
$document.on('updateProductStacks', updateCompareBtn);
updateCompareBtn();
}
};
$this.init = function () {
vm = Dell.Services.DataModel ? Dell.Services.DataModel.CompareCategories || [] : [];
$this.initCompareBtn();
if ($scope.length > 0) {
$this.psCount = -1;
var queryStringIds = "";
var categoryIds = "";
var productVariants = "";
var tempStacks = [];
$.each(vm, function (ix, categories) {
if (ix === 0) {
categoryIds += categories.Id;
$.each(categories.Containers, function (i, stacks) {
// This statement is needed to prevent the "Merchandizing Tile" from being added to the URL. The Merchandizing tile has no ItemIdentifier.
if (stacks.Stack.ItemIdentifier != "") {
if (stacks.Stack.Type == 2) {
queryStringIds += (i === 0) ? stacks.Stack.Sku.Value : "," + stacks.Stack.Sku.Value;
} else {
queryStringIds += (i === 0) ? stacks.Stack.ItemIdentifier : "," + stacks.Stack.ItemIdentifier;
}
if (stacks.Stack.ProductCode.Value == "") {
productVariants += (i === 0) ? stacks.Stack.Sku.Value : ";" + stacks.Stack.Sku.Value;
} else {
productVariants += (i === 0) ? stacks.Stack.ProductCode.Value : ";" + stacks.Stack.ProductCode.Value;
}
}
});
} else {
categoryIds += ';' + categories.Id;
$.each(categories.Containers, function (i,stacks) {
// This statement is needed to prevent the "Merchandizing Tile" from being added to the URL. The Merchandizing tile has no ItemIdentifier.
if (stacks.Stack.ItemIdentifier != "") {
if (stacks.Stack.Type == 2) {
queryStringIds += "," + stacks.Stack.Sku.Value;
} else {
queryStringIds += "," + stacks.Stack.ItemIdentifier;
}
if (stacks.Stack.ProductCode.Value == "") {
productVariants += ";" + stacks.Stack.Sku.Value;
} else {
productVariants += ";" + stacks.Stack.ProductCode.Value;
}
}
});
}
$this.psCount++;
});
tempStacks = om = vm;
Dell.Metrics.sc.productid = queryStringIds.replace(/\,/g, ';');
Dell.Metrics.sc.categoryid = categoryIds;
Dell.Metrics.sc.productvariant = productVariants;
if (!amplify.store('productOC:size') || queryStringIds.split(',').length != amplify.store('productOC:size')) {
$this.addOCStacks(queryStringIds);
}
var uri = Dell.Services.location.search('ocs', queryStringIds);
History.replaceState({ cmpstacks: queryStringIds }, document.title, uri);
History.Adapter.bind(window, 'statechange', function (e) {
var state = History.getState();
if (typeof state.data.cmpstacks !== 'undefined' && (state.data.removeoc || state.data.cmpstacks !== Dell.Services.location.search().ocs)) {
$this.updateCmpStacks($this.getOCStacks(state.data.cmpstacks,state.data.removeoc));
}
});
//do not call syncToAmplfiy before slick slider is initialized on compare drawer slider
$('.compare-product-slider').one('init', function () {
$this.syncToAmplify();
});
}
};
$this.initCompareBtn();
if (Dell.Services.DataModel !== undefined) {
$this.init();
} else {
$document.one('Dell.Services.DataModel', $this.init);
}
}).call(Dell.Controllers.comparectrl);
})(jQuery, window, document);;
var Dell = Dell || {};
Dell.Controllers = Dell.Controllers || {};
Dell.Controllers.financeCalculator = {};
(function ($, window, document) {
(function () {
'use strict';
var defaultRate = "24.99",
key = 'financeCalculator',
defaultAdditionalPayment = "50.0",
$document = $(document),
fullDateString = new Date(),
$siteWrapper = $('#site-wrapper'),
$scope = {},
$dfsModal = $('#dfs-modal'),
minimumPayment = "0.0",
dfsRequestUrl = '{0}financeschedule/getCalculator?financedPrice={1}';
var showPsSpinner = function (show) {
// Load spinnner deals/category/franchise (.seriesFamilyTablet) candy aisle spinner (.recommendations-container), singleOC (.product-configurator)
$siteWrapper.attr('data-state', show ? 'iconSpinner' : '');
$('#loaderDivImage').eq(0).toggle(show);
}
function calculateNewFieldValues() {
getAdditionalDD();
getSubTotal();
getMinimumValues();
getAdditionalValues();
}
function getAdditionalDD() {
$scope.dfsModel.dropDownOptions = [];
if (typeof $scope.dfsModel.Content !== 'undefined') {
$.each($scope.dfsModel.Content.AdditionalPaymentOptions, function (index) {
var option = $scope.dfsModel.Content.AdditionalPaymentOptions[index];
$scope.dfsModel.dropDownOptions.push({
Label: option.DisplayText,
Key: option.Value
});
});
}
}
function getSubTotal() {
if (typeof $scope.dfsModel.FinancedAmountDisplay !== 'undefined') {
var subtotal = $scope.dfsModel.FinancedAmountDisplay.split('$');
$scope.dfsModel.subTotalString = subtotal[1];
}
}
function getMinimumValues() {
getMinimumPaymentValues(defaultRate);
}
function getAdditionalValues() {
getAdditionalPaymentValues(defaultAdditionalPayment, defaultRate);
}
function updateAdditionalPayments(percentage) {
var amount = $('#financingCalculatorTermOptions').val().toString() + ".0";
//selectedTermIndex = $('#financingCalculatorTermOptions option:selected').index();
getAdditionalPaymentValues(amount, percentage);
}
function updatePayments(percentage) {
if (typeof percentage == 'undefined') {
percentage = $("#shopCalculator")[0].value;
}
getMinimumPaymentValues(percentage);
updateAdditionalPayments(percentage);
}
function getMinimumPaymentValues(percentage) {
if (typeof $scope.dfsModel.Schedule !== 'undefined') {
var rewardsString = $scope.dfsModel.Content.ChartRewardsFormat;
$scope.dfsModel.minimumMonthlyPayment = $scope.dfsModel.Schedule[minimumPayment][percentage].FormattedMinimumPayment;
$scope.dfsModel.minimumPayoffTerm = $scope.dfsModel.Schedule[minimumPayment][percentage].PayoffTerm;
$scope.dfsModel.minimumTotalInterest = $scope.dfsModel.Schedule[minimumPayment][percentage].FormattedFinalAmount;
$scope.dfsModel.minimumRewards = rewardsString.format($scope.dfsModel.Schedule[minimumPayment][percentage].Rewards);
}
}
function getAdditionalPaymentValues(amount, percentage) {
if (typeof $scope.dfsModel.Schedule !== 'undefined') {
var rewardsString = $scope.dfsModel.Content.ChartRewardsFormat;
$scope.dfsModel.additionalMonthlyPayment = $scope.dfsModel.Schedule[amount][percentage].FormattedMinimumPayment;
$scope.dfsModel.additionalPayoffTerm = $scope.dfsModel.Schedule[amount][percentage].PayoffTerm;
$scope.dfsModel.additionalTotalInterest = $scope.dfsModel.Schedule[amount][percentage].FormattedFinalAmount;
$scope.dfsModel.additionalRewards = rewardsString.format($scope.dfsModel.Schedule[amount][percentage].Rewards);
}
}
function waitForFinalEvent() {
var b = {};
return function (c, d, a) {
b[a] && clearTimeout(b[a]);
b[a] = setTimeout(c, d);
};
}
function initVueTemplate() {
//initialize the vue inline template with the current $scope.dfsModel
$dfsModal.removeClass('v-hide');
Dell.Controllers.vue.newComponent([
{
name: 'dfsmodal',
co: {
template: $('dfsModal')[0],
props: { dfsmodel: Object },
methods: {
estimatePayments: function (event) { updatePayments(); },
getRedirectUrl: function (url) {
var returnUrl = encodeURIComponent(window.location.href);
var newUrl = (url.indexOf("returnurl=") > -1) ?
url + returnUrl
: url.replace("returnurl%3d", "returnurl%3d" + encodeURIComponent(returnUrl));
window.location.href = newUrl;
}
}
},
register: true
}
]);
Dell.Controllers.vue.register(key, $dfsModal[0], $scope);
};
$document.on('financeCalculatorModalUpdate', function () {
$scope.dfsModel.showLoading = false;
showPsSpinner(true);
$("#shopCalculator").slider('refresh');
if (!Dell.Controllers.vue.isDefined(key))
initVueTemplate();
else
Dell.Controllers.vue.setVMData(key, 'dfsModel', $scope.dfsModel);
Vue.nextTick(function () {
showPsSpinner(false);
setHeight();
$('#financingCalculatorTermOptions option').eq(2).prop('selected', true);
$("#shopCalculator").slider({
formatter: function (value) {
return value + '%';
},
tooltip: 'always',
precision: 2
});
});
});
function bindDfsEvents() {
$dfsModal = $('#dfs-modal');
if ($dfsModal.length)
$document.off('click.dfsModal').on('click.dfsModal', 'a.dfsCalc', function () { loadDFSContent($(this)); });
$('#ProductStackContainer.vuePOC .installment-loan-tooltip').each(function (i, el) {
var $el = $(this);
var pid = $el.attr('data-id').replace('dpa-', '');
if (pid !== null && pid !== "") {
var item = Dell.Controllers.productstack.getProduct({ id: pid })
if (item) {
$el.popover({
content: item.Stack.FinanceMarketing.LoanPopupBody.Value,
title: item.Stack.FinanceMarketing.LoanPopupTitle.Value + " ",
container: 'body',
html: true,
trigger: 'focus',
placement: 'auto right'
}).on('hidden.bs.popover', function () {
$('#' + pid).closest('.popover').remove();
}).on('show.bs.popover', function () {
var id = $('.popover').find('a.close').attr('id');
$('a.installment-loan-tooltip.' + id).popover('toggle');
}).on('shown.bs.popover', function () {
if ($('.recommendations-price-stack-finance-section').length > 1 || $('.warranty-services-selections-container').length == 1) {
var $this = $('.popover');
$this.addClass("finance-popover-zindex");
if ($this.css("top").indexOf("-") > -1) {
$this.css("top", "10px");
}
}
});
}
}
});
};
function loadDFSContent($e) {
var dfsInputEle;
if ($('.dfs-input-value').length > 0) {
dfsInputEle = $('.dfs-input-value').get(0);
}
var apiUrl = serverUrls.apiServiceUrl || '/csbapi/' + Dell.Metrics.sc.language + '-' + Dell.Metrics.sc.country + '/';
var itemPrice = $e.attr('data-price');
var dfsInputVal = typeof dfsInputEle == "undefined" ? itemPrice : $(dfsInputEle).data('dfs-input');
$.ajax(dfsRequestUrl.format(apiUrl, dfsInputVal)).success(function (data) {
$('#dfs-modal').removeData('bs.modal');
$scope.dfsModel = data;
$scope.dfsModel.isDFSContentLoaded = true;
$scope.dfsModel.isDFSError = false;
calculateNewFieldValues();
$document.trigger('financeCalculatorModalUpdate', $scope.dfsModel);
}).error(function (e) {
$scope.dfsModel.isDFSContentLoaded = false;
$scope.dfsModel.isDFSError = true;
$scope.dfsModel.ErrorMessage = e.Message;
$document.trigger('financeCalculatorModalUpdate', $scope.dfsModel);
});
};
function setHeight() {
var height = $(window).innerHeight() * .8;
$('#dfs-modal').css('max-height', height);
}
$document
.on('newResultsReceived newStacksReceived', function () {
Vue.nextTick(bindDfsEvents);
})
.on('click', '#dfs-modal button.close', function () {
//$scope.dfsModel.showLoading = true;
$('#dfs-modal').hide();
$('.modal-backdrop').remove();
$('body').removeClass('modal-open');
})
.ready(bindDfsEvents);
}).call(Dell.Controllers.financeCalculator);
})(jQuery, window, document);;
(function ($) {
if ($('.responsive-table').length > 0) {
var waitForFinalEvent = function() {
var b = {};
return function(c, d, a) {
b[a] && clearTimeout(b[a]);
b[a] = setTimeout(c, d);
};
}();
var fullDateString = new Date();
var getScrollbarWidth = function() {
var scrollbarWidth = 0;
if (!scrollbarWidth) {
if (/msie/.test(navigator.userAgent.toLowerCase())) {
var $textarea1 = $('')
.css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body'),
$textarea2 = $('')
.css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body');
scrollbarWidth = $textarea1.width() - $textarea2.width() + 2; // + 2 for border offset
$textarea1.add($textarea2).remove();
} else {
var $div = $('
')
.css({ width: 100, height: 100, overflow: 'auto', position: 'absolute', top: -1000, left: -1000 })
.prependTo('body').append('').find('div')
.css({ width: '100%', height: 200 });
scrollbarWidth = 100 - $div.width();
$div.parent().remove();
}
}
return scrollbarWidth;
}
var bindScroll = function (table) {
var $self = table;
$self.bind('scroll', function() {
$('.fixedColumn table').css({ 'margin-top': -$self.scrollTop() });
$('.fixedHeader .table').css({ 'margin-left': -$self.scrollLeft() });
});
}
var equalizeTables = function() {
//we also need to "equalize" the row heights because text might wrap on extra lines changing the row height
var responsiveTableRows = $(".responsive-table table tbody tr");
$(".fixedColumn table tbody tr").each(function (index) { // go through each row in fixedColumn table
$(this).height(responsiveTableRows.eq(index).height() - 1); // and make them equal with the original table
// since the first cell has border and changing the row height is not sufficient, we need to make the cell height equal too
$(this).children("td").eq(0).height(responsiveTableRows.eq(index).children("td").eq(0).height() - 1);
});
// we also need to "equalize" the cell width in the header table
$(".fixedHeader table thead tr").eq(0).children('td').each(function (index) {
$(this).width(responsiveTableRows.children('td').eq(index).width());
});
}
$(window).resize(function () {
if ($('.responsive-table tbody')) {
waitForFinalEvent(function() {
$('.fixedColumn').css({ top: $('.responsive-table tbody').position().top + $('.responsive-table').position().top + 1 });
$('.fixedHeader').css({ top: $('.responsive-table thead').position().top + $('.responsive-table').position().top });
$('.responsiveTableBlock').height($('.fixedHeader .table').height() + 1);
$('.fixedHeader').width($('.responsive-table').width());
equalizeTables();
}, 50, fullDateString.getTime());
}
});
$('.responsive-table').clone().appendTo('.responsiveTable').addClass('fixedColumn').removeClass('responsive-table');
$('.fixedColumn').css({
position: 'absolute',
top: $('.responsive-table tbody').position().top + $('.responsive-table').position().top + 1,
'max-height': 600 - $('.responsive-table thead').height() - getScrollbarWidth()
});
$('.responsive-table').clone().appendTo('.responsiveTable').addClass('fixedHeader').removeClass('responsive-table');
$('.fixedHeader').css({
position: 'absolute',
top: $('.responsive-table thead').position().top + $('.responsive-table').position().top + 2
});
$('').appendTo('.fixedHeader');
$('.responsiveTableBlock').height($('.fixedHeader .table').height() + 1);
$('.fixedHeader').width($('.responsive-table').width());
$(document).ready(function () { equalizeTables(); });
bindScroll($('.responsive-table'));
}
})(jQuery);
;
var Dell = Dell || {};
Dell.Controllers = Dell.Controllers || {};
Dell.Controllers.fastDeliveryModal = {};
(function ($, window, document) {
(function () {
'use strict';
var $this = this,
$document = $(document),
$modal = $('#fast-delivery-modal'),
key = 'fastDeliveryModal',
autoRedirectTimeoutId = null,
fastDeliveryModel;
function cancelRedirect() {
if (typeof autoRedirectTimeoutId === 'number') {
window.clearTimeout(autoRedirectTimeoutId);
autoRedirectTimeoutId = null;
}
}
function initVueTemplate() {
Dell.Controllers.vue.newComponent([
{
name: 'fastdeliverymodal',
co: {
template: $('fastdeliverymodal')[0],
props: { fastdelivery: Object }
},
register: true
}
]);
Dell.Controllers.vue.register(key, $modal[0], { fastDeliveryModel: fastDeliveryModel });
}
function initFastDelivery() {
//$scope.showLoading = true;
autoRedirectTimeoutId = null;
$document.on('fastDeliveryModelData', function(event, data) {
if (typeof data !== 'undefined') {
fastDeliveryModel = data.fastDeliveryModel;
if (typeof fastDeliveryModel.snpRedirectTo3RdPartyWebsiteLinkUrl !== 'undefined' &&
fastDeliveryModel.snpRedirectTo3RdPartyWebsiteLinkUrl.Url !== "") {
fastDeliveryModel.continue3RdPartyWebsiteLinkUrl =
fastDeliveryModel.snpRedirectTo3RdPartyWebsiteLinkUrl.Url;
}
}
if (!Dell.Controllers.vue.isDefined(key))
initVueTemplate();
else
Dell.Controllers.vue.setVMData(key, 'fastDeliveryModel', fastDeliveryModel);
Vue.nextTick(function () {
$modal = $('#fast-delivery-modal');
$modal.find('.close-link, .close, .btn-success').on('click', function onPopupClose() {
$modal.modal('hide');
cancelRedirect();
});
});
});
$("[compu-pop-up]").on("show.bs.modal",
function (e) {
var $mod = $(this);
if (typeof fastDeliveryModel.fastDeliveryModalEnabled !== 'undefined' && !(fastDeliveryModel.fastDeliveryModalEnabled)) {
e.preventDefault();
e.stopPropagation();
$mod.modal('hide');
location.href = scope.fastDeliveryModel.continue3RdPartyWebsiteLinkUrl;
}
else if ((typeof fastDeliveryModel.modalTimer !== 'undefined')
&& (fastDeliveryModel.modalTimer !== 0)
&& (fastDeliveryModel.modalTimer !== "")) {
cancelRedirect();
autoRedirectTimeoutId = window.setTimeout(function () {
$mod.modal('hide');
window.location.href = fastDeliveryModel.continue3RdPartyWebsiteLinkUrl;
}, fastDeliveryModel.modalTimer);
}
});
//$('a.fastdelivery').off('click.fastdelivery').on('click.fastdelivery', function () { populateFastDelivery($(this).attr('data-index')); });
}
$document.ready(initFastDelivery);
}).call(Dell.Controllers.fastDeliveryModal);
})(jQuery, window, document);;
(function() {
'use strict';
var Dell = window.Dell || {};
Dell.Services = Dell.Services || {};
var TilesCategoryService = {},
$this = TilesCategoryService,
$location = Dell.Services.location;
$this.categoryPathPrefix = "/sc/";
$this.rootCategoryFormat = "/sc/{0}";
$this.dealsUrlFormat = "/deals/{0}";
$this.tileTitle = "";
$this.params = {
categoryTile: "",
rootCategory: "",
replaceStr: "",
rootDealId: "",
selectedDeal: ""
};
$this.showRootorSubCategoryXsView = function() {
if (SHOP.Transactional.Breakpoint.isPhone()) {
var slideSource = "#category-tiles";
var slideTarget = "#" + $this.params.categoryTile;
if ($this.isSubCategoryLocation()) {
SHOP.Transactional.OffCanvas.goToOffCanvasSlide(slideSource, slideTarget);
} else {
SHOP.Transactional.OffCanvas.backToMainSlide(slideSource, slideTarget);
}
}
};
$this.isSubCategoryLocation = function() {
try {
var split = $location.path().split($this.params.replaceStr)[1].split('/');
return (split.length == 2);
} catch (e) {
(typeof console !== 'undefined') ? console.log('no subcategory found') : '';
return false;
}
};
//return subcategory in this format - for eg laptops-inspiron-laptops
$this.formatCategoryPath = function(locationPath) {
var categoryPath = locationPath.replace(/.*(category\/|franchise\/)/ig, "");
categoryPath = categoryPath.indexOf("/") != -1 ? categoryPath.replace(/\//g, '-') : categoryPath;
//remove trailing dash if present
if (categoryPath.substr(-1) == '-') {
categoryPath = categoryPath.substr(0, categoryPath.length - 1);
}
return categoryPath;
};
$this.formatRootCategoryPath = function(rootCategoryId) {
return $this.rootCategoryFormat.format(rootCategoryId);
};
$this.isRootDeal = function() {
return $this.params.rootDealId === $this.params.selectedDeal;
};
$this.setDealsReplaceStr = function() {
$this.params.replaceStr = $this.isRootDeal() ? "/deals/" : "/";
};
$this.hasSubCategory = function(categoryUrl) {
var split = categoryUrl.replace('/', "").split('/');
return (split.length == 3);
};
$this.hasDeals = function(categoryUrl) {
var split = categoryUrl.replace('/', "").split('/');
return (split.length == 2);
};
$this.setUDOFamily = function() {
if (typeof MasterTmsUdo !== 'undefined' && $this.hasSubCategory($location.path())) {
MasterTmsUdo.CJ.FAMILY = $location.path().replace('/', "").split('/')[2];
} else if (typeof MasterTmsUdo !== 'undefined') {
MasterTmsUdo.CJ.FAMILY = "";
}
};
$this.setUDOFamilyEmpty = function() {
MasterTmsUdo.CJ.FAMILY = "";
};
$this.setUDODealId = function() {
if (typeof MasterTmsUdo !== 'undefined' && $this.hasDeals($location.path())) {
MasterTmsUdo.CJ.DEALS = $location.path().replace('/', "").split('/')[1];
}
};
$this.getCategoryUrl = function (baseUrl, categoryUrl) {
var locationUrl = window.location.pathname.replace(baseUrl, "/");
if (locationUrl === categoryUrl) return categoryUrl;
var splitLocationUrl = locationUrl.replace('/', "").split('/');
var splitCategoryUrl = categoryUrl.replace('/', "").split('/');
if (splitLocationUrl != null && splitLocationUrl.length > 0 &&
splitCategoryUrl != null && splitCategoryUrl.length > 0 &&
categoryUrl.indexOf($this.categoryPathPrefix) != -1) {
splitCategoryUrl[0] = splitLocationUrl[0];
return splitCategoryUrl.join('/');
} else if (splitLocationUrl != null && splitLocationUrl.length > 3) {
if (splitCategoryUrl != null && splitCategoryUrl.length > 2 && splitLocationUrl[3] !== splitCategoryUrl[2]) {
splitLocationUrl.pop();
}
}
return splitLocationUrl.join('/');
};
Dell.Services.TilesCategoryService = TilesCategoryService;
})();;
(function(window) {
'use strict';
var Dell = window.Dell || {};
Dell.Services = Dell.Services || {};
var TilesApiService = {},
$this = TilesApiService;
$this.productSeriesApiUrl = function (apiUrl, locationPath) {
return '{0}productseries{1}'.format(apiUrl, locationPath);
};
$this.dealsResultsApiUrl = function (apiUrl) {
var dealsPath = $location.path().replace("/deals/", "");
var sortBy = Dell.Controllers.sortOptions ? Dell.Controllers.sortOptions.sortBy() : '';
var pageNum = AnavResultsService.getPageNum();
return '{0}category/deals/{1}?sortby={2}&page={3}'.format(apiUrl, dealsPath, sortBy, pageNum);
};
$this.dieCutApiUrl = Dell.Controllers.diecut.dieCutApiUrl;
Dell.Services.TilesApiService = TilesApiService;
})(window);;
var Dell = window.Dell || {};
Dell.Services = Dell.Services || {}
Dell.Services.AnavResultsService = {};
(function ($, window, doc) {
(function () {
'use strict';
var $this = this,
$location = Dell.Services.location,
$scope = $('[data-scope]'),
$productStacks = document.getElementById('ProductStackContainer'),
apiUrl = Dell.Services.apiUrl,
req = null,
TilesCategoryService = Dell.Services.TilesCategoryService,
aborted = false,
parentCategoryId = $scope.attr('data-parent-category-id'),
isMerchandizingCategory = $scope.attr('data-merchandize-category'),
rootCategory = $scope.attr('data-category-id'),
isDealsCategory = Dell.Metrics.sc.wacontroller === "deals";
$this.skipRefiner = false;
$this.init = function () {
Dell.Services.DataModel.AnavFilterViewModel = Dell.Services.DataModel.AnavFilterViewModel || Dell.Services.DataModel.AnavFilterModel;
$(document).on('anavFilterWithoutRefiners', function (e) {
$this.skipRefiner = true;
$this.getAnavResults(e);
});
$(document).on('anavFilter', function (e) {
$this.skipRefiner = false;
$this.getAnavResults(e);
});
$(document).on('anavPagination', function (e) {
$this.getMoreAnavResults();
});
$(document).on('updateAnavResultsCount', function (e) {
if (isDealsCategory && Dell.Services.AnavResultsService.getAppliedRefinements().length <= 0) {
$(document).trigger('dealsSortResults');
} else {
$this.updateAnavResultsCount();
}
});
};
var handleError = function () {
if (!aborted)
$scope.attr('data-state', 'anavError');
else
aborted = false;
};
$this.cancelRequest = function () {
aborted = (req != null && req.readyState < 4);
if (aborted)
req.abort();
};
$this.getAnavResults = function (e) {
rootCategory = $scope.attr('data-category-id') || rootCategory;
Dell.Controllers.filters.pageNum = 1;
var hasFilters = Dell.Controllers.filters.hasSelectedFilters();
var resultsPage = $('[data-state=resultsPage]').length;
var directLoad = (e.type === 'anavFilter' || e.type === 'click' || e.type === 'readystatechange' || !resultsPage) ? false : true;
var url = isMerchandizingCategory ? snpResultsApiUrl(rootCategory, parentCategoryId, isMerchandizingCategory) : systemResultsApiUrl(rootCategory);
if (url != null && !directLoad) {
$this.cancelRequest();
if ($this.isDealsCategory) {
$scope.attr('data-state', 'getDealsResults');
$('[data-off-canvas="content"]').attr('data-state', 'getDealsResults');
}
else
$scope.attr('data-state', 'getAnavResults');
$(document).trigger('bootstrapChk');
req = Dell.Services.httpGetService.getData(url)
.success(function (data) {
var isVue = $('#ProductStackContainer.vuePOC').length !== 0;
if (!isVue) {
var $stackScope = angular.element($productStacks).scope();
$stackScope.$apply(function () {
$this.mapAnavResultsData(data, $stackScope);
});
} else {
$(document).triggerHandler('newResultsReceived', [(data.Results ? data.Results : data), false]);
$(document).trigger('newFilterData', [data]);
if (isDealsCategory) {
$(document).trigger('newDealsAnavData', [data]);
}
}
if (resultsPage && !hasFilters) {
Dell.Controllers.filters.updateRefiners(data.Filters.Refiners);
}
}).error(handleError);
}
};
$this.mapAnavResultsData = function (data, sc, concat) {
sc.$parent = sc.$parent || {};
sc.DataModel = sc.$parent.DataModel = sc.DataModel || {};
if (!concat)
sc.modelStacks = sc.$parent.DataModel.Stacks = sc.DataModel.Stacks = data.Results.Stacks;
else
sc.modelStacks = sc.$parent.DataModel.Stacks = sc.DataModel.Stacks = (angular.isDefined(sc.DataModel.Stacks) ? sc.DataModel.Stacks.concat(data.Results.Stacks) : data.Results.Stacks);
// Need Stacks in Dell.Services.DataModel.Stacks for Compare functionality
Dell.Services.DataModel.Stacks = sc.modelStacks;
sc.$broadcast('newResultsReceived');
$(document).trigger('newFilterData', [data]);
};
//Pagination load more results
$this.getMoreAnavResults = function () {
rootCategory = $scope.attr('data-category-id') || rootCategory;
$scope.attr('data-state', 'getMoreAnavResults');
var url = isMerchandizingCategory ? snpResultsApiUrl(rootCategory, parentCategoryId, isMerchandizingCategory) : systemResultsApiUrl(rootCategory);
Dell.Services.httpGetService.getData(url)
.success(function (data) {
var isVue = $('#ProductStackContainer.vuePOC').length !== 0;
if (!isVue) {
var $stackScope = angular.element($productStacks).scope();
$stackScope.$apply(function () {
$this.mapAnavResultsData(data, $stackScope, true);
});
} else {
$(document).triggerHandler('newResultsReceived', [(data.Results ? data.Results : data), true]);
$(document).trigger('newFilterData', [data]);
}
Dell.Controllers.filters.setCommonVisualStateAfterAjaxRequest();
}).error(handleError);
};
$this.setSortBy = function () {
};
//Gets filters results count to display in XS breakpoint before applying filter
$this.updateAnavResultsCount = function () {
rootCategory = $scope.attr('data-category-id') || rootCategory;
$('#anavFilterResultsCount').hide();
$('.showResultsCountSpinner').show();
Dell.Services.httpGetService.getData(isDealsCategory ? $this.getDealsApiUrl() : anavResultsCountApiUrl(rootCategory)).success(function (data) {
$(document).trigger('newResultCountData', [data]);
$('#anavFilterResultsCount').show();
$('.showResultsCountSpinner').hide();
}).error(function () {
$('#anavFilterResultsCount').show();
$('.showResultsCountSpinner').hide();
});
};
var systemResultsApiUrl = function (rootCategoryId) {
if (isDealsCategory) {
return $this.getDealsApiUrl();
}
else {
var categoryPath = typeof Dell.Services.DataModel.AnavFilterViewModel !== 'undefined'
? Dell.Services.DataModel.AnavFilterViewModel.CategoryPath
: $("meta[name=CategoryPath]").attr("content");
var sortBy = Dell.Services.location.search().sortBy || Dell.Controllers.sortOptions
? (Dell.Controllers.sortOptions.sortBy() !== 'selectedSort'
? Dell.Controllers.sortOptions.sortBy()
: 'price-ascending')
: '';
var appliedRefinements = $this.getAppliedRefinements();
var pageNum = Dell.Controllers.filters ? Dell.Controllers.filters.pageNum : 1;
if (appliedRefinements != null && appliedRefinements.length > 0)
return '{0}anavfilter/GetSystemsResults?categorypath={1}&sortby={2}&appliedRefinements={3}&page={4}&categoryid={5}'
.format(apiUrl, categoryPath, sortBy, appliedRefinements, pageNum, rootCategoryId);
else if ($this.skipRefiner) {
return '{0}anavfilter/GetSystemsResults?categorypath={1}&sortby={2}&page={3}&categoryid={4}'
.format(apiUrl, categoryPath, sortBy, pageNum, rootCategoryId);
}
else
return null;
}
};
var snpResultsApiUrl = function (rootCategoryId, parentCategoryId, isMerchandizingCategory) {
var categoryPath = Dell.Services.DataModel.AnavFilterViewModel.CategoryPath;
var sortBy = Dell.Services.location.search().sortBy || (Dell.Controllers.sortOptions ? (Dell.Controllers.sortOptions.sortBy() !== 'selectedSort' ? Dell.Controllers.sortOptions.sortBy() : 'sort-relevance') : '');
var appliedKey = Dell.Services.location.search().appliedRefinements;
var appliedRefinements = appliedKey ? appliedKey : '';
var pageNum = Dell.Controllers.filters ? Dell.Controllers.filters.pageNum : 1;
return '{0}anavfilter/GetSnPResults?categorypath={1}&sortby={2}&appliedRefinements={3}&page={4}&categoryid={5}&parentCategoryId={6}&isMerchandizingCategory={7}'
.format(apiUrl, categoryPath, sortBy, appliedRefinements, pageNum, rootCategoryId, parentCategoryId, isMerchandizingCategory);
};
var anavResultsCountApiUrl = function (rootCategoryId) {
var categoryPath = Dell.Services.DataModel.AnavFilterViewModel.CategoryPath;
var sortBy = Dell.Controllers.sortOptions ? Dell.Controllers.sortOptions.sortBy() : '';
var appliedKey = Dell.Services.location.search().appliedRefinements;
var appliedRefinements = appliedKey ? appliedKey : '';
return '{0}anavfilter/GetResultCount?categorypath={1}&sortby={2}&appliedRefinements={3}&categoryid={4}'
.format(apiUrl, categoryPath, sortBy, appliedRefinements, rootCategoryId);
};
//For now just overwriting the Ordercode and Product values with new 12 results per page
this.setConversantData = function (ordercodes, products) {
if (typeof MasterTmsUdo !== 'undefined') {
MasterTmsUdo.CJ.ORDERCODE = ordercodes;
MasterTmsUdo.CJ.PRODUCT = products;
}
};
$this.getAppliedRefinements = function () {
return Dell.Controllers.filters && Dell.Controllers.filters.getSelectedFilters
? Dell.Controllers.filters.getFiltersList()
: null;
};
$this.isDealsCategory = isDealsCategory;
$this.getDealsApiUrl = function () {
var appliedRefinements = $this.getAppliedRefinements();
if (appliedRefinements != null && appliedRefinements.length > 0) {
var sortBy = Dell.Controllers.sortOptions ? (Dell.Controllers.sortOptions.sortBy() !== 'selectedSort' ? Dell.Controllers.sortOptions.sortBy() : 'sort-relevance') : '';
return '{0}productanavfilter/GetSystemsResults?productCode=&subCategoryId={1}&appliedRefinements={2}&page={3}&sortBy={4}&originator=deals'
.format(apiUrl, Dell.Controllers.tiles.selectedTile.CategoryCode, appliedRefinements, Dell.Controllers.filters ? Dell.Controllers.filters.pageNum : 1, sortBy);
}
}
$(document).one('Dell.Services.DataModel', function () {
$this.init();
});
}).call(Dell.Services.AnavResultsService);
})(jQuery, window, document);;
var Dell = window.Dell || {};
Dell.Controllers = Dell.Controllers || {}
Dell.Controllers.tiles = {};
(function ($, window, document) {
(function () {
'use strict';
var $this = this,
$dealspage,
TilesCategoryService = Dell.Services.TilesCategoryService,
$rootScope = $('[data-scope]'),
$baseUrl = $('base').attr('href'),
$scope = $('#category-tiles'),
categoryName = $rootScope.attr('data-cat-name'),
subCategory = $rootScope.attr('data-subcategory-id'),
$tiles = $('#category-tiles').find('.category-tile'),
$series = $rootScope.find(".series-Family"),
$title = $('#sharedPdPageProductTitle'),
$displayOffCanvas = $('#display-off-canvas'),
$mainContent = $rootScope,
$moodboardImage = $('.mood-board-image'),
$dealsmoodBoard = $('.deals-mood-board'),
$moodboardMessage = $('.mood-board-text');
$this.selectedTile = $tiles.filter('.active').find('a').data('click');
$this.updateMoodboard = function (tile) {
if (typeof tile.Moodboard !== 'undefined' && tile.Moodboard.IsVisible) {
var imageAltText = tile.Moodboard.DealBannerSkinny.AltText,
imageTitle = tile.Moodboard.DealBannerSkinny.TitleText,
imageUri = tile.Moodboard.DealBannerSkinny.Url,
message = tile.Moodboard.DealGreatFor;
if (typeof imageUri !== 'undefined') {
var imgHtml = ' 0) {
if (($dealspage.length == 0))
$rootScope.attr('data-state', 'getBrandSeries');
$this.setActiveTile($match);
if (tile.UseExternalUrl === true) {
window.location.href = tile.ExternalUrl;
return;
}
$this.selectedTile = tile;
if ($dealspage.length > 0) { //enable moodboard only for deals page
$this.updateMoodboard(tile);
}
if (SHOP.Transactional.Breakpoint.isPhone()) {
var $sel = $series.filter('[data-categorycode=' + tile.CategoryCode + ']');
if ($sel.length != 0 && tile.CategoryCode != categoryName) {
$series.addClass('hide');
$sel.removeClass('hide');
$displayOffCanvas.attr('data-show-offcanvas', 'true');
} else {
$series.removeClass('hide');
$displayOffCanvas.attr('data-show-offcanvas', 'false');
}
SHOP.Transactional.OffCanvas.setupTransition();
}
//categoryPathChange event
if($rootScope.length){
TilesCategoryService.params.categoryTile = $this.categoryTile;
TilesCategoryService.params.replaceStr = "/sc/";
TilesCategoryService.showRootorSubCategoryXsView();
$this.displayBrandSeries();
if ($('#deals-page.razor').length == 0)
$rootScope.attr('data-state', '');
}
TilesCategoryService.setUDOFamily();
}
};
$this.displayBrandSeries = function () {
var $brand = $series.filter('.' + $this.selectedTile.CategoryCode).removeClass('hide');
if (!SHOP.Transactional.Breakpoint.isPhone())
$title.text($this.selectedTile.TileTitle);
$series.filter(':visible').addClass('hide');
if ($brand.length != 0)
$brand.removeClass('hide');
else
$series.removeClass('hide'); // the default
$scope.triggerHandler('category.tileDataReceived');
};
var dieCutApiUrl = Dell.Controllers.diecut.dieCutApiUrl;
$this.getComoDieCuts = Dell.Controllers.diecut.getComoDieCuts;
$this.mobileTransition = function () {
try {
if (SHOP.Transactional.Breakpoint.isPhone()) {
$mainContent.removeClass('hide hidden-xs');
}
} catch (e) { }
};
//handle empty tiles due to data issue
$this.hideEmptytiles = function(tileObj) {
var currCatcode = tileObj.CategoryCode,
currCatpath = tileObj.CategoryPath,
currUseExternal = tileObj.UseExternalUrl;
$('.affix-error').addClass('hide');
$('.showErrorMessage').removeClass('show');
if ($('.' + currCatcode).length === 0 && !currUseExternal && (currCatcode !== currCatpath)) {
//$(this).addClass('hide'); // hide empty tiles
if (SHOP.Transactional.Breakpoint.isPhone()) {
$('.backToRoot').parent('div').addClass('affix-back-btn');
$('.affix-error').removeClass('hide');
$('[data-off-canvas=content]').show().css('height', 'auto');
} else { $('.showErrorMessage').addClass('show'); $series.addClass('hide'); }
if (typeof console !== 'undefined') {
console.error('Brand Series data not found for '+currCatcode);
}
}
};
$this.init = function () {
$dealspage = $('#deals-page.razor');
/*if ($dealspage.length < 1) {
$this.hideEmptytiles($this.selectedTile);
}*/
$tiles.find('a').on('click.tile', function (e) {
var tileObj = $(this).data('click');
if ($this.selectedTile.CategoryCode != tileObj.CategoryCode && !tileObj.UseExternalUrl)
History.pushState({ tile: tileObj }, tileObj.TileTitle, ($baseUrl + tileObj.CategoryUrl).replace('//', '/'));
else if (tileObj.UseExternalUrl)
window.location.href = tileObj.ExternalUrl;
});
$('.backToRoot').on('click.rootCategory', function () {
$tiles.eq(0).find('a').triggerHandler('click.tile');
});
var state = History.getState();
var data = state.data || {};
var uParams = state.url.indexOf('?') != -1 ? state.url.substr(state.url.indexOf('?')) : '';
//don't replace active tile for deals on default
if ($dealspage.length < 1) {
data.tile = $this.selectedTile;
data.tile.TileTitle = $title.text();
var unmodifiedCategoryUrl = TilesCategoryService.getCategoryUrl($baseUrl, $this.selectedTile.CategoryUrl);
History.replaceState(data, $this.selectedTile.TileTitle, ($baseUrl + unmodifiedCategoryUrl + uParams).replace('//', '/'));
} else if ($this.selectedTile) {
$this.updateMoodboard($this.selectedTile);
}
$(document).ready(function () {
if (!$('#accessoryResults').length && $this.categoryName !== "")
$this.getComoDieCuts();
$this.mobileTransition();
$('.eBrands').removeClass('hide');
});
History.Adapter.bind(window, 'statechange', function (e) {
$('.affix-error').addClass('hide');
$('.showErrorMessage').removeClass('show');
var state = History.getState();
if (typeof state.data.tile !== 'undefined') {
$this.onTileSelect(state.data.tile);
//don't apply for deals
/*if ($dealspage.length < 1) {
$this.hideEmptytiles($this.selectedTile);
}*/
}/*else if (state.data.currentFilters === null) {
if ($dealspage.length < 1) {
$this.hideEmptytiles($this.selectedTile);
}
}*/
});
};
if ($scope.length > 0)
$this.init();
}).call(Dell.Controllers.tiles);
})(jQuery, window, document);;
var Dell = window.Dell || {};
Dell.Controllers = Dell.Controllers || {}
Dell.Controllers.sortOptions = {};
(function ($, window, document) {
(function () {
'use strict';
var $scope = this,
$sort = $('#sort'),
$selected = $('#selectedSort'),
$filterState = !SHOP.Transactional.Breakpoint.isPhone() ? $('#top-content') : $('#search-refiners').length > 0 ? $('#search-refiners') : $('#top-content'),
$location = Dell.Services.location,
$options = null,
isSnpResults = Boolean($('#accessoryResults').length) && Boolean($('.product-stack-row').length);
$scope.$showSortXs = $sort.find('div.showSortXs');
$scope.key = 'sortBy';
var initSort = function () {
$options = $sort.find('.sortOption');
$options.unbind('click.' + $scope.key).bind(('click.' + $scope.key), function (e) { e.preventDefault(); onSortOptionSelect(this.id) });
$(document).on('click.sortXs', '#sortXs', function (e) {
e.preventDefault();
$scope.$showSortXs.show();
});
$('.anavSortCloseButton').unbind('click.closeSortXs').bind('click.closeSortXs', function () {
$scope.$showSortXs.hide();
$filterState.attr('data-state', '');
});
$(document).on('anavFilter', function () {
$scope.$showSortXs.hide();
});
if ((Dell.Services.location.search())[$scope.key])
$scope.onHistoryUpdate((Dell.Services.location.search())[$scope.key]);
$(document).ready(function () {
History.Adapter.bind(window, 'statechange', function (e) {
var state = History.getState();
$scope.onHistoryUpdate(state.data.sort);
//prevent sort data from triggering anav results call for mobile when anav filters are visible
if (state.data.sort && (!SHOP.Transactional.Breakpoint.isPhone() || (SHOP.Transactional.Breakpoint.isPhone() && $('[data-state="showAnavFilters"]').length === 0))) {
var appliedRefinements = Dell.Services.AnavResultsService.getAppliedRefinements();
if (Dell.Services.AnavResultsService.isDealsCategory) {
if (appliedRefinements != null && appliedRefinements.length > 0)
$(document).trigger('anavFilter');
else
$(document).trigger('dealsSortResults');
}
else {
if ($("#category-page").length == 1 && Dell.Services.DataModel.BrandAnav) {
$(document).trigger('anavFilterWithoutRefiners');
}
else {
$(document).trigger('anavFilter');
}
}
}
});
});
};
$scope.onHistoryUpdate = function (id) {
//set ID via history back/forward event/initial load
$scope.updateSort((typeof id !== 'undefined' && id != null) ? id : $options.first().attr('id'));
};
$scope.updateSort = function (id) {
var $opt = $options.filter('#' + id);
if ($opt.length > 0) {
$scope.$showSortXs.hide();
$selected.text($opt.first().text()).attr('id', id);
$options.removeClass('selected-item');
$opt.addClass('selected-item');
}
};
var onSortOptionSelect = function (id) {
$filterState.attr('data-state', '');
//set ID via user selection & update the history via $location.pushParam
if (id != $selected.attr('id'))
History.pushState({ sort: id }, null, $location.search($scope.key, id));
};
$scope.closeSortOptionsXs = function () {
$scope.$showSortXs.hide();
};
$scope.sortBy = function () {
return $selected.length > 0 ? $selected.attr('id') : "";
};
if ($sort.length > 0) {
$(document).ready(initSort);
} else {
$('#sortXs').hide();
}
}).call(Dell.Controllers.sortOptions);
})(jQuery, window, document);
;
var Dell = window.Dell || {};
Dell.Controllers = Dell.Controllers || {}
Dell.Controllers.filters = {};
(function ($, window, document, History) {
(function () {
'use strict';
var $this = Dell.Controllers.filters,
$scope = $('#anavFilter'),
$rootScope = $('[data-scope]'),
$refiners = $scope.find('.refiner'),
currentFilters = [],
$filterState = !SHOP.Transactional.Breakpoint.isPhone() ? $('#top-content') : $('#search-refiners').length > 0 ? $('#search-refiners') : $('#top-content'),
$pgBtn = $('a.load-more-button'),
updateHistory = true,
anavClick = false,
om,
vm,
$location = Dell.Services.location,
vueDefined = false,
resultsPage = $('[data-state=resultsPage]').length;
$this.pageNum = 1;
$this.key = 'appliedRefinements';
$this.init = function () {
Dell.Services.DataModel.AnavFilterViewModel = Dell.Services.DataModel.AnavFilterViewModel || Dell.Services.DataModel.AnavFilterModel;
if (Dell.Services.DataModel.AnavFilterViewModel.Pagination.TotalPages === 1)
$pgBtn.css('display', 'none');
//bind events and assign history watch on url param for filters
$(document).off('click.anav').on('click.anav', '.dropdown-menu .anavRef, .mobRefinementList a.anavRef, .left-anav-menu .anavRef', function (e) {
if (!$(this).hasClass('DISABLED')) {
anavClick = true;
var chkbox = $(this).find("input[type\x3dcheckbox]");
if (e.target.nodeName.toLowerCase() !== 'input') {
chkbox.prop('checked', !chkbox.prop('checked'));
}
$this.setSelectedFilters(this.id);
if (!SHOP.Transactional.Breakpoint.isPhone() && $('#accessoryCategory').length == 0) {
if (!$this.hasSelectedFilters()) {
$this.resetRefinementStates();
$(document).trigger('updateAnavResultsCount');
} else {
$(document).trigger('anavFilter');
}
}
if (window.systemCategoryLeftAnav) {
var leftAnavOffsetTop = 0;
if ($("#leftAnavContainer") && $("#leftAnavContainer").length > 0) {
if ($("#leftAnavContainer").offset())
leftAnavOffsetTop = $("#leftAnavContainer").offset().top;
if ($(window).scrollTop() > leftAnavOffsetTop) {
$("html, body").animate({
scrollTop: leftAnavOffsetTop
},
800);
}
}
}
anavClick = false;
}
});
$pgBtn.on('click.pagination', function (e) {
e.preventDefault();
if (Dell.Services.AnavResultsService.isDealsCategory) {
var appliedRefinements = Dell.Services.AnavResultsService.getAppliedRefinements();
if (appliedRefinements != null && appliedRefinements.length > 0)
$this.paginationClicked();
}
else
$this.paginationClicked();
});
$(document).on('click.clearall', '.clearallrefiners', function (e) {
e.preventDefault();
$this.clearAllSelectedFilters();
$(document).trigger('updateAnavResultsCount');
});
$(document).on('click.refine', '.refinementFilter', function (e) {
e.preventDefault();
$this.setSelectedFilters($(this).attr('data-id'));
if (!$this.hasSelectedFilters()) {
$this.resetRefinementStates();
$(document).trigger('updateAnavResultsCount');
} else {
$(document).trigger('anavFilter');
}
});
$(document).on('click.filterbtn', '#showanavfilters, #anavFiltersXs', function (e) {
e.preventDefault();
$this.showAnavFilters();
});
$(document).on('click.sortbtn', '#sortsansanavXs', function (e) {
e.preventDefault();
$this.showSortXs();
});
$(document).on('click.closebtn', '.anavCloseButtonHook', function (e) {
e.preventDefault();
$this.closeFilters();
});
$(document).on('click.accordionicon', 'div.accordion-header a', function (e) {
e.preventDefault();
$(this).find('.accordion-icon').toggleClass('icon-ui-minus');
});
$(document).on('click.reset', '.anavResetButtonHook', function (e) {
e.preventDefault();
$this.resetRefinersXs();
});
$(document).on('click.apply', '.anavApplyButtonHook', function (e) {
e.preventDefault();
$rootScope.attr('data-state', 'getAnavResults');
$filterState.attr('data-state', '');
var state = History.getState();
var data = state.data || {};
data.r = window.Math.random();
data.currentFilters = currentFilters;
data.mobileApply = true;
History.replaceState(data, state.title, state.url);
});
$(document).on('anavFilter', function () {
if (resultsPage)
$filterState.attr('data-state', '');
});
$(document).on('newFilterData', function (e, d) {
if (d) {
if (d.Pagination && ((d.Pagination.TotalPages - d.Pagination.CurrentPage) > 0))
$pgBtn.css('display', 'block');
else
$pgBtn.hide();
if (d.TotalResultCount)
$rootScope.find('.resultsCount').text(d.TotalResultCount);
//VUE Refresh
if (d.Filters && d.Filters.Refiners)
$this.updateRefiners(d.Filters.Refiners);
}
$this.setCommonVisualStateAfterAjaxRequest();
});
$(document).on('newResultCountData', function (e, d) {
if (d && d.TotalResultCount)
$rootScope.find('.resultsCount').text(d.TotalResultCount);
if (Dell.Services.DataModel.AnavFilterViewModel.TotalResultCount !== d.TotalResultCount && !SHOP.Transactional.Breakpoint.isPhone())
$(document).trigger('anavFilter');
});
$(document).on('inXtraSmallBreakpoint, inMediumBreakpoint::inLargeBreakpoint', function (event) {
$this.setCommonVisualStateAfterAjaxRequest();
if ($this.hasSelectedFilters() && (Dell.Controllers.sortOptions && Dell.Controllers.sortOptions.showSortXs))
Dell.Controllers.sortOptions.showSortXs.hide();
});
om = om === undefined ? JSON.parse(JSON.stringify(Dell.Services.DataModel.AnavFilterViewModel.Filters.Refiners)) : om; //clone original object
vm = Dell.Services.DataModel.AnavFilterViewModel.Filters.Refiners;
var state = History.getState();
var uFilters = (state.url.indexOf($this.key) != -1) ? $location.search(null, null, state.url.substr(state.url.indexOf($this.key)))[$this.key] : [];
var data = state.data || {};
data.currentFilters = uFilters;
data.mobileApply = true;
if (uFilters && uFilters.length > 0)
data.r = window.Math.random();
History.Adapter.bind(window, 'statechange', function (e) {
var state = History.getState();
if (typeof state.data.currentFilters !== 'undefined') {
if (state.data.currentFilters != null && state.data.currentFilters.length > 0) {
$this.onHistoryUpdate(state.data.currentFilters);
if ((!SHOP.Transactional.Breakpoint.isPhone() && !anavClick) || (SHOP.Transactional.Breakpoint.isPhone() && state.data.mobileApply))
$(document).trigger('anavFilter');
} else if (vueDefined && (state.data.currentFilters == null || state.data.currentFilters.length === 0)) {
$this.resetRefinementStates();
Dell.Services.AnavResultsService.cancelRequest();
}
if (SHOP.Transactional.Breakpoint.isPhone() && !state.data.mobileApply) {
if ($this.hasSelectedFilters()) {
$this.showAnavFilters();
$(document).trigger('updateAnavResultsCount');
$this.setXsBtns();
} else {
$this.resetRefinersXs();
}
}
}
});
var sortBy = Dell.Services.location.search().sortBy;
if (resultsPage && (data.currentFilters.length > 0 || sortBy !== undefined)) {
if (data.currentFilters.length > 0)
$this.onHistoryUpdate(data.currentFilters);
else
$(document).trigger('anavFilter');
} else {
History.replaceState(data, '', state.url);
}
if (uFilters && uFilters.length === 0) {
$this.applyVisitorPersistance();
}
};
$this.applyVisitorPersistance = function (key) {
try {
key = Dell.Transactional.SearchStateManager.Storage.GetCleanKey(key);
if (Dell.Transactional.SearchStateManager.Storage.FeatureEnabled) {
var appliedVistorPersistance = false;
var searchPersistUrl = Dell.Transactional.SearchStateManager.Storage.GetPersistUrlByKey(key);
if (searchPersistUrl) {
var sfilters = (searchPersistUrl.indexOf($this.key) > -1) ? $location.search(null, null, searchPersistUrl.substr(searchPersistUrl.indexOf($this.key)))[$this.key] : [];
if (sfilters && sfilters.length > 0) {
Dell.Controllers.filters.setSelectedFilters(sfilters, true);
appliedVistorPersistance = true;
}
}
if (!appliedVistorPersistance) {
Dell.Transactional.SearchStateManager.Storage.Set();
}
return appliedVistorPersistance;
}
} catch (e) {
}
return false;
}
$this.resetAnavData = function (d) {
Dell.Services.DataModel.AnavFilterModel = Dell.Services.DataModel.AnavFilterViewModel = d;
om = JSON.parse(JSON.stringify(Dell.Services.DataModel.AnavFilterViewModel.Filters.Refiners));
};
$this.getSelectedFilters = function () {
return currentFilters;
};
$this.getFiltersList = function () {
return currentFilters.length > 1 ? currentFilters.join(',') : currentFilters.length == 1 ? currentFilters[0] : '';
};
$this.hasSelectedFilters = function () {
return (currentFilters.length > 0);
};
$this.paginationClicked = function () {
$this.pageNum = $this.pageNum + 1;
$pgBtn.hide();
$(document).trigger('anavPagination');
};
$this.setCommonVisualStateAfterAjaxRequest = function () {
var isResultsPage = ($('.razor.results').length) ? 'resultsPage' : '';
if (Dell.Services.AnavResultsService.isDealsCategory) {
$rootScope.attr('data-state', 'dealsData');
$('[data-off-canvas="content"]').attr('data-state', 'dealsData');
}
else if (Dell.Services.AnavResultsService.skipRefiner) {
$rootScope.attr('data-state', 'hasSelectedRefinements');
} else {
$rootScope.attr('data-state', ($this.hasSelectedFilters() ? 'hasSelectedRefinements' : isResultsPage));
}
};
$this.updateRefiners = function (d) {
if (d && d.length > 0) {
vm = JSON.parse(JSON.stringify(d));
if (!vueDefined)
initVue({ Refiners: vm });
else
Dell.Controllers.vue.setVMData($this.key, 'Refiners', vm);
}
};
$this.setSelectedFilters = function (id, triggerLoad) {
var ids = typeof id !== 'string' ? id : id.split(',');
var update = typeof triggerLoad !== 'undefined' ? triggerLoad : true;
var refinerExists = false;
for (var i = 0; i < vm.length; i++) {
for (var ri = 0; ri < vm[i].Refinements.length; ri++) {
if (Dell.Services.arrayIndexOf(ids, vm[i].Refinements[ri].Id) != -1) {
if (vm[i].Refinements[ri].State === 'UNCHECKED') {
vm[i].Refinements[ri].State = 'CHECKED';
currentFilters.push(vm[i].Refinements[ri].Id);
} else if (vm[i].Refinements[ri].State === 'CHECKED' && update) {
vm[i].Refinements[ri].State = 'UNCHECKED';
var idx = Dell.Services.arrayIndexOf(currentFilters, vm[i].Refinements[ri].Id);
if (idx != -1)
currentFilters.splice(idx, 1);
} else if (!update) {
currentFilters.push(vm[i].Refinements[ri].Id);
om[i].Refinements[ri].State = 'UNCHECKED';
}
refinerExists = true;
}
}
}
if (!currentFilters.length && ids.length && !refinerExists) { // set this deeplinking in SNP
currentFilters = ids;
}
if (update && updateHistory) {
var sort = Dell.Services.location.search().sortBy;
var data = (sort) ? { currentFilters: currentFilters, sort: sort } : { currentFilters: currentFilters };
var fl = $this.getFiltersList();
if (fl == "") {
Dell.Transactional.SearchStateManager.Storage.RemoveCurrent();
}
History.pushState(data, '', $location.search($this.key, $this.getFiltersList()));
}
$this.updateRefiners(vm);
/* S&P Category Page */
if ($('#accessoryCategory').length > 0) {
setTimeout($this.routeResultsPage, 15);
}
Dell.Transactional.SearchStateManager.Storage.Set();
};
$this.routeResultsPage = function () {
var url = window.location.toString();
window.location = url.replace('/ac/', '/ar/');
};
$this.onHistoryUpdate = function (ids) {
var uParams = ($location.search())[$this.key] ? ($location.search())[$this.key].split(',') : [];
var i = 0;
updateHistory = false;
var curRefs = currentFilters;
if (curRefs.length == 0 || (curRefs.length == 1 && (curRefs[0] == null || curRefs[0].length == 0)) || $location.onReady) {
$this.setSelectedFilters(ids, false);
} else {
//check for new / removed options --> history vs current state
for (i = 0; i < curRefs.length; i++) {
if (Dell.Services.arrayIndexOf(ids, curRefs[i]) == -1) {
if (SHOP.Transactional.Breakpoint.isPhone())
$this.setSelectedFilters(curRefs[i]);
else
$this.setSelectedFilters(curRefs[i]);
}
}
for (i = 0; i < ids.length; i++) {
if (Dell.Services.arrayIndexOf(curRefs, ids[i]) == -1) {
if (SHOP.Transactional.Breakpoint.isPhone())
$this.setSelectedFilters(ids[i]);
else
$this.setSelectedFilters(ids[i]);
}
}
}
updateHistory = true;
}
$this.showSortXs = function () {
$filterState.attr('data-state', 'showSort');
Dell.Controllers.sortOptions.$showSortXs.show();
$this.setXsBtns();
};
$this.showAnavFilters = function () {
$filterState.attr('data-state', 'showAnavFilters');
$this.setXsBtns();
if ($('#root-canvas.canvas-content.transition') && (!Dell.Services.AnavResultsService.isDealsCategory)) {
$('#root-canvas.canvas-content').removeClass("transition");
}
};
$this.setXsBtns = function () {
if ($this.hasSelectedFilters()) {
$('.anavResetButtonHook').show();
$('.anavApplyButtonHook').show();
$('.anavCloseButtonHook').hide();
} else if (typeof ($location.search())[$this.key] === 'undefined') {
$('.anavCloseButtonHook').show();
$('.anavResetButtonHook').hide();
$('.anavApplyButtonHook').hide();
}
}
$this.closeFilters = function () {
$filterState.attr('data-state', '');
};
$this.clearAllSelectedFilters = function () {
if (updateHistory && !SHOP.Transactional.Breakpoint.isPhone())
History.pushState({ currentFilters: null }, '', '?');
else
$this.resetRefinementStates();
};
$this.resetRefinementStatesWithoutPersistance = function () {
$this.pageNum = 1;
currentFilters = [];
if (resultsPage)
$rootScope.attr('data-state', 'resultsPage');
if (resultsPage && Dell.Services.DataModel.AnavFilterModel.Pagination.TotalPages > 1)
$pgBtn.show();
if (!SHOP.Transactional.Breakpoint.isPhone())
$filterState.attr('data-state', '');
$this.updateRefiners(om);
$(document).trigger('originalstacks');
}
$this.resetRefinementStates = function () {
$this.pageNum = 1;
currentFilters = [];
$rootScope.attr('data-state', (resultsPage ? 'resultsPage' : ''));
if (resultsPage && Dell.Services.DataModel.AnavFilterModel.Pagination.TotalPages > 1)
$pgBtn.show();
if (!SHOP.Transactional.Breakpoint.isPhone())
$filterState.attr('data-state', '');
$this.updateRefiners(om);
$(document).trigger('originalstacks');
Dell.Transactional.SearchStateManager.Storage.Set();
};
$this.resetRefinersXs = function (e) {
$this.resetRefinementStates();
History.pushState({ currentFilters: null }, '', '?');
$(document).trigger('updateAnavResultsCount');
$(document).trigger('anavFilter');
$this.setXsBtns();
$('div.accordion-inner').addClass('collapse').removeClass('in');
$('div.accordion-header').find('.accordion-icon').removeClass('icon-ui-minus');
};
$this.toggleRefinerAccordionState = function (refiner) {
refiner.ShowRefinements = !refiner.ShowRefinements;
};
$(document).on('inXtraSmallBreakpoint', function (event) {
$filterState.attr('data-state', '');
});
var initVue = function (d) {
vueDefined = true;
//shared methods for templates via global mixin
Vue.mixin({
methods: {
refinerCount: function (i) {
var l = i ? i.Refinements.filter(function (obj) {
return obj.State === 'CHECKED';
}).length : 0;
return (l > 0) ? ' (' + l + ')' : '';
},
getAnavOptionMetrics: function (i, r) {
if (i && r)
return JSON.stringify({ 'anav_caption_option': r.Name, 'anav_caption': i.Name });
return {};
},
selected: function (n) {
var a = [];
if (typeof n === 'undefined' || n === null || n.length === 0)
return a;
for (var i = 0; i < n.length; i++) {
a = a.concat(n[i].Refinements.filter(function (o) { return o.State === 'CHECKED'; }));
}
this.$nextTick(function () {
if ($('a.refinementFilter').length > 0)
$('.clearallrefiners').removeClass('hide');
else
$('.clearallrefiners').addClass('hide');
});
return a;
}
}
});
//create componenets and register parents
Dell.Controllers.vue.newComponent([
{
name: 'refinementlist',
co: { template: $('.refinementList')[0], props: { refinements: Array, item: Object } }
},
{
name: 'mobrefinementlist',
co: { template: $('.mobRefinementList')[0], props: { refinements: Array, item: Object } }
},
{
name: 'selectedfilter',
co: { template: $('.selectedFilter')[0], props: { filter: Object } }
},
{
name: 'mobfilterlist',
co: {
template: $('.mobFilterList > ul')[0],
props: { refiners: Array, refinements: Array },
components: ['mobrefinementlist']
},
register: true
},
{
name: 'filterlist',
co: {
template: $('.filterList > div')[0],
props: { item: Object, refiners: Array, refinements: Array },
components: ['refinementlist']
},
register: true
},
{
name: 'anavcontroller',
co: {
template: $('anavcontroller')[0],
props: { refiners: Array, refinements: Array, item: Object },
components: ['filterlist', 'mobfilterlist', 'selectedfilter']
},
register: true
}
]);
//create a vuew instance leveraging pre defined components
Dell.Controllers.vue.register($this.key, $('#anavFilter')[0], d);
if (SHOP.Transactional.Breakpoint.isPhone())
Vue.nextTick(function () {
var refs = Dell.Services.location.search().appliedRefinements;
if (refs) {
var ar = refs.split(',');
for (var i = 0; i < ar.length; i++) {
var $ref = $('#Anav a#' + ar[i]).closest('.refiner');
$ref.find('.accordion-inner').removeClass('collapse').addClass('in');
$ref.find('.accordion-icon').attr('class', 'accordion-icon icon-ui-minus icon-ui-plus');
}
}
});
}
if ($scope.length > 0 || $rootScope.length) {
$(document).ready($this.init);
} else { // handle deep linking for non-anav pages
var state = History.getState();
var data = state.data || {};
History.replaceState(data, '', state.url);
}
}).call(Dell.Controllers.filters);
})(jQuery, window, document, History);;
var Dell = Dell || {};
Dell.Services = Dell.Services || {};
Dell.Controllers = Dell.Controllers || {};
Dell.Controllers.deals = {};
(function ($, window, document) {
(function () {
'use strict';
var TilesCategoryService = Dell.Services.TilesCategoryService,
TilesController = Dell.Controllers.tiles,
$location = Dell.Services.location,
$baseUrl = $('base').attr('href'),
$productStacks = document.getElementById('ProductStackContainer'),
apiUrl = Dell.Services.apiUrl,
$this = this,
req = null,
$title = $('#sharedPdPageProductTitle'),
$tiles = $('#category-tiles').find('.category-tile'),
$displayOffCanvas = $('#display-off-canvas'),
$dealspage = $('#deals-page.razor'),
$pgBtn = $('.seriesFamilyTablet').find('a.load-more-button'),
isVue = Boolean($('#ProductStackContainer.vuePOC').length),
$scope = $('[data-scope]'),
isDeals = Boolean($('#deals-results-container').length),
$document = $(document);
$this.selectedTile = $tiles.filter('.active').find('a').data('click');
$this.pageNum = 1;
Dell.Services.apiUrl = $scope.attr('data-api');
$this.rootDeal = $scope.attr('data-catid');
$this.subCategoryId = $scope.attr('data-subcatid');
$this.categoryTile = $this.subCategoryId;
$this.paginationClicked = function (e) {
var appliedRefinements = Dell.Services.AnavResultsService.getAppliedRefinements();
if (!(appliedRefinements != null && appliedRefinements.length > 0)) {
e.preventDefault();
$this.pageNum = $this.pageNum + 1;
$pgBtn.hide();
$document.trigger('dealsPagination');
}
};
$pgBtn.on('click.pagination', $this.paginationClicked);
var dealsResultsApiUrl = function () {
var dealsPath = TilesController.selectedTile.CategoryCode;
var sortBy = Dell.Controllers.sortOptions ? (Dell.Controllers.sortOptions.sortBy() !== 'selectedSort' ? Dell.Controllers.sortOptions.sortBy() : 'sort-relevance') : '';
//var sortBy = Dell.Controllers.sortOptions ? (Dell.Controllers.sortOptions.sortBy() !== 'selectedSort' ? Dell.Controllers.sortOptions.sortBy() : 'price-ascending') : '';
var pageNum = Dell.Controllers.deals ? Dell.Controllers.deals.pageNum : 1;
return '{0}category/deals/{1}?sortby={2}&page={3}'.format(apiUrl, dealsPath, sortBy, pageNum);
};
$this.getDealsResults = function () {
//check scope again it shifts in mobile view
try {
var key = ($baseUrl + TilesController.selectedTile.CategoryUrl).replace('//', '/');
var vpUrl = Dell.Transactional.SearchStateManager.Storage.GetPersistUrlByKey(key);
if (vpUrl && vpUrl.length > 0) {
return;
}
}
catch (e) {
console.error(e);
}
$scope = $('[data-scope]');
Dell.Controllers.deals.pageNum = 1;
var url = dealsResultsApiUrl();
if (url != null) {
if (req != null && req.readyState < 4)
req.abort();
$scope.attr('data-state', 'getDealsResults');
$document.trigger('bootstrapChk');
req = Dell.Services.httpGetService.getData(url)
.success(function (data) {
if (!isVue) {
var $stackScope = angular.element($productStacks).scope();
$stackScope.$apply(function () {
$this.mapDealsResultsData(data, $stackScope);
});
} else {
$document.triggerHandler('newResultsReceived', (data.Results ? data.Results : data));
$document.trigger('newDealsData', [data]);
$scope.attr('data-state', 'dealsData');
}
}).error(function () {
$scope.attr('data-state', 'dealsError');
if (SHOP.Transactional.Breakpoint.isPhone())
$('.error-message.showErrorMessage').css('margin', '50% auto');
});
}
};
$this.mapDealsResultsData = function (data, sc, concat) {
sc.$parent = sc.$parent || {};
sc.DataModel = sc.$parent.DataModel = sc.DataModel || {};
if (!concat)
sc.modelStacks = sc.$parent.DataModel.Stacks = sc.DataModel.Stacks = data.Stacks;
else
sc.modelStacks = sc.$parent.DataModel.Stacks = sc.DataModel.Stacks = (angular.isDefined(sc.DataModel.Stacks) ? sc.DataModel.Stacks.concat(data.Stacks) : data.Stacks);
sc.$broadcast('newResultsReceived');
$document.trigger('newDealsData', [data]);
};
//Pagination load more results
$this.getMoreDealsResults = function () {
//check scope again it shifts in mobile view
$scope = $('[data-scope]');
$scope.attr('data-state', 'getMoreDealsResults');
Dell.Services.httpGetService.getData(dealsResultsApiUrl())
.success(function (data) {
if (!isVue) {
var $scope = angular.element($productStacks).scope();
$scope.$apply(function () {
$this.mapDealsResultsData(data, $scope, true);
});
} else {
$document.triggerHandler('newResultsReceived', [(data.Results ? data.Results : data), true])
$document.trigger('newDealsData', [data]);
$('[data-scope]').attr('data-state', 'dealsData');
}
}).error(function () {
$scope.attr('data-state', 'dealsError');
});
};
$document.on('dealsPagination', function () {
$this.getMoreDealsResults();
});
$this.getProducts = function () {
$(".shop-more-cta-for-deals").addClass("hidden");
$this.getDealsResults();
TilesCategoryService.setUDODealId();
if (SHOP.Transactional.Breakpoint.isPhone()) {
$displayOffCanvas.attr('data-show-offcanvas', 'true');
SHOP.Transactional.OffCanvas.setupTransition();
$('#tile-content').removeClass('hidden');
}
};
$this.checkPagination = function (d) {
if (d) {
if (d.Pagination && ((d.Pagination.TotalPages - d.Pagination.CurrentPage) > 0))
$pgBtn.css('display', 'block');
else
$pgBtn.hide();
if (d.ResultsCount) {
$('.resultsCount').text(d.ResultsCount);
}
}
};
$this.showAnavFilters = function () {
if (Dell.Services.DataModel.AnavFilterViewModel.Filters.Refiners.length > 1) {
$(".hideAnavResults #top-content").css('display', 'block');
$("#top-content").removeClass("hidden");
if (SHOP.Transactional.Breakpoint.isPhone())
$(".deals-result-count.hideAnavResults").css("display", "none");
} else {
$(".hideAnavResults #top-content").css('display', 'none');
$(".deals-result-count.hideAnavResults").css("display", "block");
}
};
$this.getActiveTileText = function () {
var activeTile = $('#deals-page .category-tile.active h4');
if (activeTile) {
$("#activeTileText").text(activeTile.text());
}
};
$this.toggleShopMoreCta = function (shopMoreModel) {
var loadMore = false; // for desktop making default false
if (SHOP.Transactional.Breakpoint.isPhone()) {
loadMore = $pgBtn.is(":visible");
} else {
$this.getActiveTileText();
}
if (loadMore) {
$(".shop-more-cta-for-deals").addClass("hidden");
}
else if (window.showShopMoreCta) {
if (shopMoreModel && shopMoreModel.Caption && shopMoreModel.Url) {
$(".shop-more-cta-for-deals").removeClass("hidden");
$(".shop-more-cta").text(shopMoreModel.Caption);
$(".shop-more-cta").attr("href", shopMoreModel.Url);
}
}
};
$this.init = function () {
$('#deals-page .category-tile').find('a').on('click.deals',
function () {
var tileObj = $(this).data('click');
if (!tileObj.UseExternalUrl) {
var uri = ($baseUrl + tileObj.CategoryUrl).replace('//', '/');
Dell.Controllers.filters.resetRefinementStatesWithoutPersistance();
var appliedVistorPersistance = Dell.Controllers.filters.applyVisitorPersistance(uri);
if (!appliedVistorPersistance) {
History.pushState({ tile: tileObj }, tileObj.TileTitle, uri);
}
} else if (tileObj.UseExternalUrl)
window.location.href = tileObj.ExternalUrl;
$('html, body').animate({
scrollTop: 0
},
800);
});
$("a.all-deals-subcategory-load-more").on("click",
function () {
$("#category-tiles a#productCategoryTiles-" + $(this).data('target')).trigger("click");
});
$this.toggleShopMoreCta(window.shopMoreCtaModel);
$document.on('dealsSortResults',
function () {
var appliedRefinements = Dell.Services.AnavResultsService.getAppliedRefinements();
if (appliedRefinements != null && appliedRefinements.length > 0) {
$document.trigger('anavFilter');
} else {
$this.getProducts();
}
});
$document.on('newDealsData',
function (e, d) {
$scope.attr('data-state', 'dealsData');
$this.checkPagination(d);
Dell.Services.DataModel.AnavFilterModel = Dell.Services.DataModel.AnavFilterViewModel = d.AnavFilterModel;
$this.showAnavFilters();
if (d !== 'undefined' && d.AnavFilterModel !== 'undefined' && d.AnavFilterModel.Filters !== 'undefined') {
Dell.Controllers.filters.updateRefiners(d.AnavFilterModel.Filters.Refiners);
}
$this.toggleShopMoreCta(d.ShopMoreLink);
$(document).trigger("updateAllDeals", [d]);
});
$(document).on("updateAllDeals", function (e, d) {
try {
var selectedTileData = $('#category-tiles').find('.category-tile.active a').data("click");
if (selectedTileData && d.AllDealsCategories &&
Object.keys(d.AllDealsCategories).length > 0 &&
selectedTileData.CategoryRawPath &&
selectedTileData.CategoryRawPath.split("/").length == 2) {
Dell.Services.DataModel.AllDealsCategories = d.AllDealsCategories;
$(".all-deals-toggle").addClass("sub-category-content");
$("#all-deals-tab-content").removeClass("hidden-lg hidden-md hidden-sm");
$(".all-deals-subcategory-products").each(function (index, elem) {
var k = $(elem).data("category");
if (k) {
var data = d.AllDealsCategories[k].Results.Stacks;
if (data) {
data.VueIndex = index + 1;
data.Source = "deals";
$document.triggerHandler('newResultsReceived', [(data), false]);
}
}
});
} else {
$(".all-deals-toggle").removeClass("sub-category-content");
$("#all-deals-tab-content").addClass("hidden-lg hidden-md hidden-sm");
}
if (!SHOP.Transactional.Breakpoint.isPhone() && $this.AllSealsLoadMoreSource) {
$('html, body').animate({
scrollTop: 0
},
500);
}
$this.AllSealsLoadMoreSource = false;
} catch (e) {
console.error(e);
}
});
$document.on('newResultCountData',
function (e, d) {
if (d && d.TotalResultCount)
$('.resultsCount').text(d.TotalResultCount);
});
$(document).on('newDealsAnavData', function (e, d) {
try {
var key = ($baseUrl + TilesController.selectedTile.CategoryUrl).replace('//', '/');
var vpUrl = Dell.Transactional.SearchStateManager.Storage.GetPersistUrlByKey(key);
if (vpUrl && vpUrl.length > 0) {
$(".all-deals-toggle").removeClass("sub-category-content");
$("#all-deals-tab-content").addClass("hidden-lg hidden-md hidden-sm");
}
if (d && d.Filters && d.Filters.Refiners) {
if (d.Filters.Refiners.length > 1) {
$(".hideAnavResults #top-content").css('display', 'block');
$("#top-content").removeClass("hidden");
if (SHOP.Transactional.Breakpoint.isPhone())
$(".deals-result-count.hideAnavResults").css("display", "none");
} else {
$(".hideAnavResults #top-content").css('display', 'none');
$(".deals-result-count.hideAnavResults").css("display", "block");
}
}
} catch (e) {
console.error(e);
}
});
$(document).ready(function () {
$this.showAnavFilters();
}
);
if (window.enableZombieBar && $('#tile-content').length > 0 && $(".hideCategoryTiles").length > 0 && $("#footer").length > 0) {
$(window).scroll(function () {
try {
if (!SHOP.Transactional.Breakpoint.isPhone()) {
var tileContentOffSetTop = $('#tile-content').offset().top;
var moodBoardElement = $(".deals-mood-board");
var stickyBar = tileContentOffSetTop + $(".title").height();
var $tilesElement = $(".hideCategoryTiles");
var windowScrollTop = $(window).scrollTop();
var footerOffSetTop = $("#footer").offset().top;
if ($(window).scrollTop() > stickyBar) {
if (footerOffSetTop < (windowScrollTop + $tilesElement.height())) {
$tilesElement.css("top", -((windowScrollTop + $tilesElement.height()) - footerOffSetTop));
} else {
$tilesElement.css("top", "0");
$tilesElement.addClass('affix');
if (moodBoardElement && moodBoardElement.length > 0) {
$("#tile-content").css("padding-top", $tilesElement.height());
}
else {
$("#tile-content").css("padding-bottom", $tilesElement.height());
}
$tilesElement.css('width', $('#tile-content').outerWidth());
$(".scroll-container").css('background-color', "white");
$tilesElement
.animate($tilesElement.addClass('deals-tiles-affix'),
1000,
function () {
});
}
} else {
if ($tilesElement.hasClass("deals-tiles-affix")) {
$("#tile-content").removeAttr("style");
$(".scroll-container").css("background-color", "");
$tilesElement.removeClass('affix').removeClass('deals-tiles-affix');
}
}
}
} catch (e) {
console.error(e);
}
});
$(window).resize(function () {
try {
var $tilesElement = $("div[data-controller='tilesController']");
$tilesElement.css('width', $('#tile-content').outerWidth());
} catch (e) {
console.error(e);
}
});
}
$('.dealsPageSortButton').on('click', function (e) {
e.preventDefault();
$('.showSortXs').show();
});
if (SHOP.Transactional.Breakpoint.isPhone()) {
$('[data-scope]').removeAttr('data-scope');
$('.seriesFamilyTablet').attr('data-scope', '').addClass('razor');
//shift scope to mobile view
$scope = $('[data-scope]').attr('data-state', 'dealsData');
if (isVue) {
//setup offCanvas if vueStacks are rendered
$displayOffCanvas.attr('data-show-offcanvas', 'true');
SHOP.Transactional.OffCanvas.setupTransition();
$('#tile-content').removeClass('hidden');
}
}
$('.backToRoot').on('click.rootCategory', function () {
var state = History.getState(),
data = state.data || {};
data.dealsroot = true;
History.pushState(state.data, $title.text(), ($baseUrl + '/deals').replace('//', '/'));
$('#tile-content').removeClass('hidden-xs');
if (isVue)
$('#top-content').removeClass('hidden-xs');
});
try {
if (Dell.Metrics.sc.categoryid !== 'deals' || !SHOP.Transactional.Breakpoint.isPhone()) {
var tileObj = $this.selectedTile;
if (!isVue) {
TilesController.onTileSelect(tileObj);
History.pushState({ tile: tileObj },
tileObj.TileTitle,
($baseUrl + tileObj.CategoryUrl + location.search)
.replace('//', '/')); // push along with query string
$this.getProducts(); //initial fetch for landing on subcat
}
} else {
$('#tile-content').removeClass('hidden-xs');
}
} catch (e) {
console.error(e);
}
History.Adapter.bind(window, 'statechange', function (e) {
var state = History.getState();
var tileObj = state.data.tile;
if ((typeof state.data.dealsroot === 'undefined') || !SHOP.Transactional.Breakpoint.isPhone()) {
if (typeof tileObj !== 'undefined') {
$scope.attr('data-state', 'getDealsResults');
$this.getProducts();
}
} else if (isVue && !state.data.dealsroot && SHOP.Transactional.Breakpoint.isPhone()) {
$('#top-content').addClass('hidden-xs');
}
});
};
if (isDeals)
$this.init();
}).call(Dell.Controllers.deals);
})(jQuery, window, document);;
var Dell = Dell || {};
Dell.Services = Dell.Services || {};
Dell.Controllers = Dell.Controllers || {};
Dell.Controllers.category = {};
(function ($, window, document) {
(function () {
'use strict';
var $scope = $('[data-scope]'),
$this = this;
$this.AdjustAnav = function () {
if (SHOP.Transactional.Breakpoint.isPhone()) {
if ($("#mobileAnavContainer") && $("#mobileAnavContainer").html() && $("#mobileAnavContainer").html().trim() === "")
$("#top-content").appendTo("#mobileAnavContainer");
}
else {
if ($("#top-content") && $("#top-content").html() && $("#top-content").html().trim() !== "") {
$("#top-content").appendTo("#leftAnavContainer");
}
}
};
$this.UpdateAnav = function (tileObj) {
if (!tileObj.UseExternalUrl && Dell.Services.DataModel.BrandAnav && tileObj.CategoryRawPath && Dell.Services.DataModel.AllBrandsAnavFilterModel) {
Dell.Controllers.filters.resetRefinementStatesWithoutPersistance();
Dell.Controllers.filters.resetAnavData(
Dell.Services.DataModel.AllBrandsAnavFilterModel[tileObj.CategoryRawPath]);
Dell.Controllers.filters.updateRefiners(Dell.Services.DataModel.AnavFilterViewModel.Filters.Refiners);
}
$(".brand-links li").removeClass("active");
$(".brand-links li[data-code='" + tileObj.CategoryCode + "']").addClass("active");
$scope.attr('data-category-id', tileObj.CategoryCode);
};
$this.init = function () {
$('#category-page .category-tile').find('a').on('click', function () {
if (Dell.Services.DataModel.BrandAnav && !SHOP.Transactional.Breakpoint.isPhone()) {
try {
var tileObj = $(this).data('click');
if (Dell.Services.DataModel.AllBrandsAnavFilterModel[tileObj.CategoryRawPath] == null || !Dell.Services.DataModel.AllBrandsAnavFilterModel[tileObj.CategoryRawPath].ShowAnavFilters) {
$scope.attr('data-state', '');
$("#anavFilter").hide();
Dell.Controllers.filters.clearAllSelectedFilters();
}
else {
$("#anavFilter").show();
$this.UpdateAnav(tileObj);
}
} catch (e) {
console.error(e);
}
}
});
$(".brand-links a.brand-tile").on("click",
function () {
if (Dell.Services.DataModel.BrandAnav && !SHOP.Transactional.Breakpoint.isPhone()) {
var tileObj = $(this).data('click');
$(".category-tile[data-code='" + tileObj.CategoryCode + "'] a").trigger("click");
if ($("#anavFilter:visible").length > 0 && !Dell.Controllers.filters.applyVisitorPersistance()) {
$(document).trigger('anavFilterWithoutRefiners');
}
}
});
$("#backToSeriesView").on("click", function () {
$scope.attr('data-state', '');
Dell.Controllers.filters.resetRefinementStates();
Dell.Controllers.filters.clearAllSelectedFilters();
});
$(document).ready(function () {
try {
if ($("#category-page").length > 0) {
var path = "";
var categoryCode = "";
$("#leftAnavContainer").removeClass("hide-brand-anav");
if (!Dell.Services.DataModel.AnavFilterViewModel.ShowAnavFilters) {
$scope.attr('data-state', '');
$("#anavFilter").hide();
}
if (Dell.Services.DataModel.BrandAnav && SHOP.Transactional.Breakpoint.isPhone()) {
for (var i = 0; i < Dell.Services.DataModel.Tiles.length; i++) {
if (Dell.Services.DataModel.Tiles[i].CategoryRawPath.split("/").length === 2) {
path = Dell.Services.DataModel.Tiles[i].CategoryRawPath;
categoryCode = Dell.Services.DataModel.Tiles[i].CategoryCode;
break;
}
}
$scope.attr('data-category-id', categoryCode);
if (Dell.Services.DataModel.AllBrandsAnavFilterModel[path] == null || !Dell.Services.DataModel.AllBrandsAnavFilterModel[path].ShowAnavFilters) {
$scope.attr('data-state', '');
$("#anavFilter").hide();
}
else {
Dell.Controllers.filters.resetAnavData(
Dell.Services.DataModel.AllBrandsAnavFilterModel[path]);
Dell.Controllers.filters.updateRefiners(Dell.Services.DataModel.AnavFilterViewModel.Filters.Refiners);
}
}
}
} catch (e) {
console.error(e);
}
$(window).resize(function () {
if (window.systemCategoryLeftAnav) {
$this.AdjustAnav();
}
});
if (window.systemCategoryLeftAnav)
$this.AdjustAnav();
});
};
$this.init();
}).call(Dell.Controllers.category);
})(jQuery, window, document);;
$('#featuredImageCarousel').on('slid.bs.carousel', function () {
var $this = $('.carousel-inner .item');
var $left = $('.carousel .carousel-control.left');
var $right = $('.carousel .carousel-control.right');
var lastItem = $this.length - 1;
$.each($this, function (ix, item) {
if ($(item).hasClass('active')) {
if (ix === 0) {
$left.removeClass('activeBtnState').addClass('inactiveBtnState');
$right.removeClass('inactiveBtnState').addClass('activeBtnState');
}
else if (ix === lastItem) {
$left.removeClass('inactiveBtnState').addClass('activeBtnState');
$right.removeClass('activeBtnState').addClass('inactiveBtnState');
}
else {
$left.removeClass('inactiveBtnState').addClass('activeBtnState');
$right.removeClass('inactiveBtnState').addClass('activeBtnState');
}
}
});
});
(function ($, window, document) {
'use strict';
var Dell = window.Dell || {};
Dell.Services = Dell.Services || {};
Dell.Controllers = Dell.Controllers || {}
Dell.Controllers.franchise = {};
var initService = Dell.Services.initService,
$location = Dell.Services.location,
$scope = $('#franchise');
(function (response) {
'use strict';
var $this = Dell.Controllers.franchise,
createDataModelService = Dell.Services.createDataModelService;
$this.init = function (response) {
try {
$(document).on('click', '.right.carousel-control', function (e) {
e.preventDefault();
var carousel2Slide = $(e.target.getAttribute("href"));
$this.moveFrachiseCarouselRight(carousel2Slide);
});
$(document).on('click', '.left.carousel-control', function (e) {
e.preventDefault();
var carousel2Slide = $(e.target.getAttribute("href"));
$this.moveFrachiseCarouselLeft(carousel2Slide);
});
$this.swippingLeft = function () {
$this.moveFrachiseCarouselRight();
};
$this.swippingRight = function () {
$this.moveFrachiseCarouselLeft();
};
$this.moveFrachiseCarouselRight = function (carousel2Slide) {
var $franchiseCarousel = carousel2Slide.find(".touch-scroll"); //$('.touch-scroll');
$franchiseCarousel.animate({ scrollLeft: $franchiseCarousel.scrollLeft() + $franchiseCarousel.width() }, 500);
//$('.left.carousel-control').css('color', '#007db8');
carousel2Slide.find('.left.carousel-control').css('color', '#007db8');
if (($franchiseCarousel.width() * 2 + $franchiseCarousel.scrollLeft()) >= $franchiseCarousel[0].scrollWidth) {
carousel2Slide.find('.carousel-control.right').css('color', '#cce7f3');
} else {
carousel2Slide.find('.carousel-control.right').css('color', '#007db8');
}
};
$this.moveFrachiseCarouselLeft = function (carousel2Slide) {
var $franchiseCarousel = carousel2Slide.find(".touch-scroll"); //$('.touch-scroll');
$franchiseCarousel.animate({ scrollLeft: $franchiseCarousel.scrollLeft() - $franchiseCarousel.width() }, 500);
carousel2Slide.find('.right.carousel-control').css('color', '#007db8');
if (($franchiseCarousel.scrollLeft() - $franchiseCarousel.width()) <= 0) {
carousel2Slide.find('.carousel-control.left').css('color', '#cce7f3');
}
};
$(document).on('click', '.responsiveTable tbody td div h4', function (e) {
if ($(window).width() < 768) {
$('html, body').animate({
scrollTop: $('#franchise-tiles').offset().top
}, 1000);
} else {
$('html, body').animate({
scrollTop: $('.franchise-series-section').offset().top
}, 1000);
}
});
if ($(window).width() < 768) {
var isTabClicked = false;
var isBackButtonClicked = false;
// Tab/Section in Mobile
$('.scroll-item a').click(function () {
var tab = $(this).attr('data-slide-target').replace('#', '');
var slideSource = $(this).parent().attr('data-slide-source');
var slideTarget = $(this).parent().attr('data-slide-target');
var updatedURL = window.location.href.split('?')[0] + '/' + tab + window.location.search;
isTabClicked = true;
History.pushState({ slideSource: slideSource, slideTarget: slideTarget }, document.title, updatedURL);
});
// OffCanvas Back Button
$('.affix-back-btn').click(function () {
var tab = '/' + window.location.href.split('?')[0].substr(window.location.href.split('?')[0].lastIndexOf('/') + 1);
var randomObj = Math.random();
var basePdPageUrl = window.location.href.split('?')[0].replace(tab, '');
isBackButtonClicked = true;
History.pushState({ randomObj: randomObj }, document.title, basePdPageUrl);
});
History.Adapter.bind(window, 'statechange', function (e) {
var state = History.getState();
if (!(isTabClicked || isBackButtonClicked)) {
SHOP.Transactional.OffCanvas.backToMainSlide(state.data.slideSource, state.data.slideTarget);
$('.affix-back-btn').removeClass('affix-back-btn');
$('#root-canvas').removeClass('transition');
}
isTabClicked = false;
isBackButtonClicked = false;
});
}
$this.DataModel = createDataModelService.InitScope($this, response);
$this.apiUrl = $scope.attr('data-api');
$this.categoryId = $scope.attr('data-category-id');
$this.hidePageTitle = $('div.hidePageTitle');
} catch (e) {
Dell.Shop.Debug('warn', 'init Exception - ' + e);
}
};
if ($scope.length) {
$this.init(response);
}
})({
data: (typeof initService === "undefined" || initService === null ? "" : initService.Get())
});
})(jQuery, window, document);;
var Dell = window.Dell || {};
Dell.Transactional = Dell.Transactional || {};
Dell.Transactional.SearchStateManager = Dell.Transactional.SearchStateManager || {};
Dell.Transactional.SearchStateManager.Storage = (function () {
var getParameterByName = function (name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
var getByKey = function (id) {
try {
if (featureEnabled() && localStorage.AnavState && id) {
id = getCleanKey(id);
var existingState = JSON.parse(localStorage.AnavState);
if (validateAnavStorageJson(existingState)) {
var pathname = id;
var data = existingState[pathname];
if (data && validateCurrent(pathname, data)) {
return data;
}
}
}
} catch (e) {
}
return null;
};
var get = function () {
try {
var pathname = window.location.pathname;
return getByKey(pathname);
} catch (e) { }
return null;
};
var getAll = function () {
if (featureEnabled()) {
if (localStorage.AnavState) {
var existingState = JSON.parse(localStorage.AnavState);
if (validateAnavStorageJson(existingState)) {
return existingState;
}
}
}
return null;
};
var remove = function () {
if (localStorage.AnavState) {
localStorage.removeItem("AnavState");
}
};
var getUrlSearch = function (id) {
try {
id = getCleanKey(id);
if (featureEnabled() && id) {
var state = getByKey(id);
if (state) {
return state.search;
}
}
} catch (e) {
}
return null;
};
var getPersistUrlByKey = function (key) {
try {
key = getCleanKey(key);
if (featureEnabled() && key) {
var state = getByKey(key);
if (state) {
return state.location;
}
}
} catch (e) {
}
return null;
};
var getPersistUrl = function () {
if (featureEnabled()) {
var state = get();
if (state) {
return state.location;
}
}
return null;
};
var removeCurrent = function () {
try {
if (featureEnabled()) {
if (localStorage.AnavState) {
var existingState = JSON.parse(localStorage.AnavState);
var pathname = getCleanKey(window.location.pathname);
if (existingState[pathname]) {
delete existingState[pathname];
}
localStorage.AnavState = JSON.stringify(existingState);
}
}
} catch (e) {
}
};
var set = function () {
if (featureEnabled() && window.location.search && window.location.search.length > 0) {
var ar = getParameterByName("appliedRefinements", window.location.href);
if (ar && ar.length > 0) {
var pathname = getCleanKey(window.location.pathname);
var created = new Date($.now());
if (localStorage.AnavState) {
var existingState = JSON.parse(localStorage.AnavState);
existingState[pathname] = { "location": window.location.href, "search": window.location.search, "created": created };
localStorage.AnavState = JSON.stringify(existingState);
} else {
var state = {};
state[pathname] = { "location": window.location.href, "search": window.location.search, "created": created };
localStorage.AnavState = JSON.stringify(state);
}
return;
}
}
removeCurrent();
};
var setStateByKeyAndValue = function (id, state) {
try {
if (featureEnabled() && id && id.length > 0 && state) {
if (localStorage.AnavState) {
var existingState = JSON.parse(localStorage.AnavState);
existingState[id] = state;
localStorage.AnavState = JSON.stringify(existingState);
} else {
var nstate = {};
nstate[id] = state;
localStorage.AnavState = JSON.stringify(nstate);
}
}
} catch (e) {
}
};
function validateAnavStorageJson(state) {
if (state && Object.keys(state).length > 0 && state[Object.keys(state)[0]] && state[Object.keys(state)[0]].location) {
return true;
}
return false;
}
function validateCurrent(uri, state) {
if (uri && state && state.location && window.shopAnavVisitorPersistenceExpiresInDays && window.shopAnavVisitorPersistenceExpiresInDays > 0) {
var createdDate = new Date(state.created);
var expires = new Date();
expires.setDate(createdDate.getDate() + window.shopAnavVisitorPersistenceExpiresInDays);
var currentDate = new Date();
if (currentDate <= expires) {
return true;
}
}
return false;
};
function featureEnabled() {
try {
if (typeof (Storage) !== "undefined" && window.shopAnavVisitorPersistent && window.shopAnavVisitorPersistenceExpiresInDays && window.shopAnavVisitorPersistenceExpiresInDays > 0) {
return true;
}
} catch (e) {
console.log("shopEnableAnavVisitorPersistent is Missing");
}
return false;
}
function getCleanKey(key) {
try {
if (!key || key.length === 0)
key = window.location.pathname;
if (key.endsWith("/")) {
var ar = key.split("/");
ar.pop();
key = ar.join("/");
}
return key;
} catch (e) {
}
return window.location.pathname;
}
return {
FeatureEnabled: featureEnabled,
GetCleanKey: getCleanKey,
Get: get,
GetByKey: getByKey,
GetAll: getAll,
GetUrlSearch: getUrlSearch,
GetPersistUrlByKey: getPersistUrlByKey,
SetStateByKeyAndValue: setStateByKeyAndValue,
Set: set,
GetPersistUrl: getPersistUrl,
Remove: remove,
RemoveCurrent: removeCurrent
};
})();
;
var Dell = window.Dell || {};
Dell.Controllers = Dell.Controllers || {};
Dell.Controllers.youtube = {};
(function ($, window, document) {
(function () {
'use strict';
var videos = document.querySelectorAll('.youtube-wrapper');
var vendorUrl = '//www.youtube.com/embed/';
var videoThumbnailResolution = '/maxresdefault.jpg';
if (SHOP.Transactional.Breakpoint.isPhone()) {
videoThumbnailResolution = '/mqdefault.jpg';
}
var analyticsCall = function (key, value) {
if (typeof dellmetrics_trackvalue == 'function') {
dellmetrics_trackvalue(key, value);
}
};
for (var i = 0; i < videos.length; i++) {
var thumbnailImagesource = videos[i].dataset.thumbnailUrl;
if (!thumbnailImagesource) {
thumbnailImagesource = 'https://img.youtube.com/vi/' + videos[i].dataset.videoId + videoThumbnailResolution;
}
var image = new Image();
image.src = thumbnailImagesource;
image.className = 'img-responsive';
image.addEventListener('load', function () {
videos[i].appendChild(image);
}(i));
videos[i].addEventListener('click', function (e) {
var iframe = document.createElement('iframe');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowfullscreen', '');
iframe.setAttribute('src', vendorUrl + this.dataset.videoId + '?autoplay=1&hl=' + this.dataset.language + '&loop=' + this.dataset.loop + '&modestbranding=' + this.dataset.modestbranding + '&rel=' + this.dataset.rel + '&start=' + this.dataset.start);
this.innerHTML = '';
this.appendChild(iframe);
analyticsCall('youtubeplay', e.currentTarget.dataset.videoId);
});
}
}).call(Dell.Controllers.youtube);
})(jQuery, window, document);;
var Dell = window.Dell || {};
Dell.Controllers = Dell.Controllers || {};
Dell.Controllers.youku = {};
(function ($, window, document) {
(function () {
'use strict';
var videos = document.querySelectorAll('.youku-wrapper');
var youkuApi = '//player.youku.com/jsapi';
var youkuClientId = '699bf17c39c022b1';
var videoStatusDic = {};
var analyticsCall = function (key, value) {
if (typeof dellmetrics_trackvalue == 'function') {
dellmetrics_trackvalue(key, value);
}
};
function checkVideoHasBeenPlayed(videoElementId) {
if (videoStatusDic[videoElementId] == undefined) {
videoStatusDic[videoElementId] = true;
return false;
}
return true;
}
for (var i = 0; i < videos.length; i++) {
var thumbnailImagesource = videos[i].dataset.thumbnailUrl;
if (thumbnailImagesource) {
var image = new Image();
image.src = thumbnailImagesource;
image.className = 'img-responsive';
image.addEventListener('load', function () {
videos[i].appendChild(image);
}(i));
}
else {
videos[i].classList.add('youku-default-thumbnail');
}
videos[i].addEventListener('click', function (e) {
var youkuWrapper = this.id;
var videoId = this.dataset.videoId;
if (checkVideoHasBeenPlayed(youkuWrapper)) {
return;
}
function loadScript(url, callback) {
var script = document.createElement("script");
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState === "loaded" || script.readyState === "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function () {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript(youkuApi, function () {
var player = new YKU.Player(youkuWrapper, {
styleid: '0',
client_id: youkuClientId,
vid: videoId,
autoplay: true,
newPlayer: true,
events: {
onPlayerReady: function () {
if (YKP == 'undefined' && YKP.isPC == 'undefined') {
return;
}
if (YKP.isPC) {
document.querySelectorAll('#' + youkuWrapper + ' .play-button')[0].style.display = 'none';
}
else {
/*Here are some tricky logic need be clarified
* 1. why use interval:
* in Mobile scenario, when onPlayerReady is called ,video-button still not
* be generated, so we could not directly code like:
* document.querySelectorAll('#' + youkuWrapper + ' .x-video-button')[0].style.display = 'none'
* 2.var counter = 2;
* style of 'x-video-button' is handled by youku api, display is set to 'block' twice during
* youku loading, so set a counter, decrease it ,when counter equal to 0, remove interval
*/
var checkButton = setInterval(function () {
var counter = 2;
var ele = document.querySelectorAll('#' + youkuWrapper + ' .x-video-button')[0];
if (ele.style.display == 'block') {
ele.style.display = 'none';
counter -= 1;
if (counter == 0) {
clearInterval(checkButton);
}
}
}, 50);
}
}
}
});
analyticsCall('youkuplay', videoId);
});
});
}
}).call(Dell.Controllers.youku);
})(jQuery, window, document);;