Skip to content

Instantly share code, notes, and snippets.

@dg3feiko
Created December 6, 2016 03:10
Show Gist options
  • Save dg3feiko/831f82fb18f497e7bd6bb9cfa10d53bf to your computer and use it in GitHub Desktop.
Save dg3feiko/831f82fb18f497e7bd6bb9cfa10d53bf to your computer and use it in GitHub Desktop.
var RESPONSIVE_BREAKPOINT_WIDTH = 770;
var mileStone, home, master, productListing, productListDropdown;
var isResponsive = false;
var pagePos = 0;
var storeLocator;
var featuredPhotoArr = [];
var isMobile = checkMobile();
if (!Object.keys) {
Object.keys = (function() {
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function(obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
}
if (!Array.prototype.map) {
Array.prototype.map = function(callback, thisArg) {
var T, A, k;
if (this == null) {
throw new TypeError(' this is null or not defined');
}
// 1. Let O be the result of calling ToObject passing the |this|
// value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal
// method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 1) {
T = thisArg;
}
// 6. Let A be a new array created as if by the expression new Array(len)
// where Array is the standard built-in constructor with that name and
// len is the value of len.
A = new Array(len);
// 7. Let k be 0
k = 0;
// 8. Repeat, while k < len
while (k < len) {
var kValue, mappedValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal
// method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];
// ii. Let mappedValue be the result of calling the Call internal
// method of callback with T as the this value and argument
// list containing kValue, k, and O.
mappedValue = callback.call(T, kValue, k, O);
// iii. Call the DefineOwnProperty internal method of A with arguments
// Pk, Property Descriptor
// { Value: mappedValue,
// Writable: true,
// Enumerable: true,
// Configurable: true },
// and false.
// In browsers that support Object.defineProperty, use the following:
// Object.defineProperty(A, k, {
// value: mappedValue,
// writable: true,
// enumerable: true,
// configurable: true
// });
// For best browser support, use the following:
A[k] = mappedValue;
}
// d. Increase k by 1.
k++;
}
// 9. return A
return A;
};
}
jQuery(document).ready(function(e) {
// jQuery('body').prepend('<div>'+navigator.userAgent.toLowerCase()+'</div>');
var hasHiddenField = false;
if ( typeof step !== "undefined") {
if (step == 2) {
hasHiddenField = true;
}
}
if (!hasHiddenField)
jQuery('input, textarea').placeholder();
/* Main Menu Functions */
if (jQuery(window).width() < RESPONSIVE_BREAKPOINT_WIDTH && !belowIE8)
isResponsive = true;
else
isResponsive = false;
if(belowIE8)
{
jQuery('body').addClass('isIE8');
}
if(isMobile)
{
jQuery('body').addClass('isMobile');
}
jQuery(window).resize(function(e) {
if (jQuery(window).width() > RESPONSIVE_BREAKPOINT_WIDTH && isResponsive) {
//console.log('des');
jQuery('body,html').css('overflow', '');
isResponsive = false;
master.reinit();
mileStone.reInit();
if (jQuery('#map').length > 0)
storeLocator.initDesktop();
jQuery('#form').attr('style', '');
/*Checkout Product List */
if (jQuery('.itemGallery').length > 0) {
// console.log('test');
jQuery('.basicItemMover').css({
left : 30
});
productDevPos = 0;
}
} else if (jQuery(window).width() < RESPONSIVE_BREAKPOINT_WIDTH && !isResponsive) {
//console.log('resize');
isResponsive = true;
master.reinit();
jQuery('#form').attr('style', '');
if (jQuery('#map').length > 0)
storeLocator.initResponsive();
/*Checkout Product List */
if (jQuery('.itemGallery').length > 0) {
jQuery('.basicItemMover').css({
left : 30
});
productDevPos = 0;
}
jQuery('body,html').scrollLeft(0);
}
if (jQuery('#cartWrapper.productListing').length > 0) {
if (isResponsive) {
productListing.destroy();
productListing.init();
} else
productListing.destroy();
}
if(productListWidgetArr.length > 0)
{
for(var i in productListWidgetArr)
{
if (isResponsive) {
productListWidgetArr[i].productListEngine.destroy();
productListWidgetArr[i].productListEngine.init();
} else
productListWidgetArr[i].productListEngine.destroy();
}
}
/*Checkout Product List */
if (jQuery('.itemGallery').length > 0) {
var productCount = jQuery('.cartItemTab').length;
var productWidth = 150;
if ((isResponsive && productCount * productWidth < jQuery(window).width() - 60) || (!isResponsive && productCount <= 3)) {
jQuery('.basicItemLeft').hide();
jQuery('.basicItemRight').hide();
} else {
jQuery('.basicItemLeft').show();
jQuery('.basicItemRight').show();
}
totalDevPos = isResponsive ? Math.ceil(productCount - (jQuery(window).width() - 60) / productWidth) : productCount - 3;
}
});
master = new menuSetup();
master.init();
mileStone = new milestoneSetup();
mileStone.init();
jQuery('.featuredPhoto').each(function(i){
featuredPhotoArr.push(new featuredPhotoSetup(jQuery(this),i));
});
//home = new homepageSetup();
//jQuery('.categoryFilter').jScrollPane({showArrows: true,animateScroll: true});
if (jQuery('#map').length > 0) {
storeLocator = new storeLocatorEngine();
storeLocator.init();
if (isResponsive)
storeLocator.initResponsive();
}
if (jQuery('#cartWrapper.productListing').length > 0) {
productListing = new listFixHeight(['.myProduct .thumbnail', '.myProduct .productTitle', '.myProduct .productPrice']);
if (isResponsive)
productListing.init();
}
initCheckBox();
});
jQuery(window).load(function(e) {
if (featuredPhotoArr.length > 0) {
for(var i=0;i<featuredPhotoArr.length;i++)
{
featuredPhotoArr[i].init();
}
featuredPhotoArr[0].getProductArray();
//home.init();
//home.initResponsive();
}
//Hard Code on 21/1/2015
hardCodeAddArticleBanner();
})
/** Main menu Toggle **/
var menuSetup = function() {
var self = this;
self.init = function() {
jQuery('#headerContainer>.header .subNav > ul li.mainSectionName').each(function(i) {
if (jQuery(this).parent().find('li:not(.mainSectionName)').length > 0) {
jQuery(this).addClass('hvSubmenu');
}
});
jQuery('#footerContainer>.footerUpper .footerNavToggle').click(function(e) {
if (jQuery('#footerContainer>.footerUpper .footerNav').hasClass('active'))
jQuery('#footerContainer>.footerUpper .footerNav').removeClass('active')
else
jQuery('#footerContainer>.footerUpper .footerNav').addClass('active')
});
self.reinit();
};
self.reinit = function() {
jQuery('#headerContainer>.header .subNav').removeClass('active').attr('style', '');
jQuery('#headerContainer>.header .headerBarBottom ul.mainNav').unbind('mouseenter mouseleave');
jQuery('#headerContainer>.header .subNav').unbind('mouseenter mouseleave');
jQuery('#headerContainer .menuToggle,#headerContainer>.header .subNav > ul:not(.CitysuperSeasonalSpecialSectionPage) li.mainSectionName a').unbind('click');
jQuery('#headerContainer>.header .subNav > ul li.mainSectionName').unbind('click');
if (!isResponsive) {
jQuery('#headerContainer>.header .headerBarBottom ul.mainNav').hover(function(e) {
self.openMainMeun();
}, function(e) {
self.closeMainMeun();
});
jQuery('#headerContainer>.header .subNav').hover(function(e) {
e.stopPropagation();
self.openMainMeun();
}, function(e) {
e.stopPropagation();
self.closeMainMeun();
});
} else {
jQuery('#headerContainer .menuToggle').click(function(e) {
if (jQuery('#headerContainer>.header .subNav').hasClass('active')) {
jQuery('#headerContainer>.header .subNav').removeClass('active');
self.closeMainMeun();
} else {
jQuery('#headerContainer>.header .subNav').addClass('active');
self.openMainMeun();
}
});
jQuery('#headerContainer>.header .subNav > ul:not(.CitysuperSeasonalSpecialSectionPage) li.mainSectionName a').click(function(e) {
if (jQuery(this).parent().parent().hasClass('active')) {
e.preventDefault();
jQuery(this).parent().parent().removeClass('active')
} else if (jQuery(this).parent().parent().find('li:not(.mainSectionName)').length > 0) {
e.preventDefault();
jQuery('#headerContainer>.header .subNav > ul').removeClass('active');
jQuery(this).parent().parent().addClass('active')
}
});
}
}
self.openMainMeun = function() {
if (!isResponsive) {
jQuery('#headerContainer>.header .subNav').stop().show().animate({
height : 215
});
} else {
jQuery('#headerContainer>.header .subNav').stop().slideDown();
}
};
self.closeMainMeun = function() {
if (!isResponsive) {
jQuery('#headerContainer>.header .subNav').stop().animate({
height : 0
}, function() {
jQuery('#headerContainer>.header .subNav').hide()
});
} else {
jQuery('#headerContainer>.header .subNav').stop().slideUp();
}
};
};
/** Featured Photo Widgets Functions **/
var POPUP_WIDTH = 448;
var POPUP_HEIGHT = 285;
var viewPortWidth = 950;
var featuredPhotoSetup = function(visualContainer,photoId) {
var self = this;
self.id = photoId;
var homepageVisualButton = jQuery('');
var container = visualContainer ? jQuery(visualContainer) : jQuery('.featuredPhoto').eq(0);
var productListContainer;
var currentProductID = 0;
var itemJson;
var itemList = [];
var timer;
self.inited = false;
self.itemArr = [];
self.isLoading = false;
self.init = function() {
//self.getProductArray();
var HTML = '<div class="detailsPopup loading">';
HTML += '<div class="productContent">';
HTML += '<a class="closeBtn"></a>'
HTML += '<div class="image"></div>';
HTML += '<div class="desc">';
HTML += '<div class="name"></div>';
HTML += '<div class="price"><span class="currency">HKD$</span>123</div>';
HTML += '<div class="text"></div>';
HTML += '</div>';
HTML += '<a href="#" class="moreDetails">'+dictionary["featuredPhoto"].popup.moreDetails[lang]+'</a>';
HTML += '<a href="#" class="addToCart">'+dictionary["featuredPhoto"].popup.addToCart[lang]+'</a>';
HTML += '</div>';
HTML += '</div>';
jQuery(container).append(HTML);
jQuery(container).find('.detailsPopup').hide();
jQuery(container).find('.detailsPopup .closeBtn').click(function(e) {
jQuery(container).find('.detailsPopup').fadeOut();
jQuery(container).find('a').removeClass('active');
});
jQuery(container).children('a').each(function(i) {
if(typeof jQuery(this).attr('data-item') == "undefined")
return;
var orderID = parseInt(jQuery(this).attr('data-item').replace('items_',''),10);
itemList.push(orderID);
if(typeof quickViewItemJson.Items[orderID].photoList === "undefined")
{
quickViewItemJson.Items[orderID].photoList = new Array();
quickViewItemJson.Items[orderID].photoList.push(self.id);
}
else
{
quickViewItemJson.Items[orderID].photoList.push(self.id);
}
jQuery(this).click(function(e) {
//console.log(quickViewItemJson.Items[i]);
if ( typeof quickViewItemJson === "undefined" || quickViewItemJson.Items[orderID].ItemType != "product")
return;
e.preventDefault();
if (quickViewItemJson.Items[orderID].ItemType == "product" && !jQuery(this).hasClass('active')) {
e.preventDefault();
jQuery(container).children('a').removeClass('active');
jQuery(this).addClass('active');
jQuery(container).find('.detailsPopup').addClass('loading');
var top = jQuery(this).offset().top;
var left = jQuery(this).offset().left - jQuery('#contentContainer > .content').offset().left;
var relativeTop = jQuery(this).position().top;
var relativeLeft = jQuery(this).position().left;
jQuery(container).find('.detailsPopup').removeClass('top').removeClass('bottom').removeClass('left').removeClass('right');
if (top - POPUP_HEIGHT < jQuery('#headerContainer').height()) {
jQuery(container).find('.detailsPopup').addClass('top');
} else {
jQuery(container).find('.detailsPopup').addClass('bottom');
}
//console.log(left + POPUP_WIDTH);
if (left + POPUP_WIDTH > viewPortWidth) {
jQuery(container).find('.detailsPopup').addClass('right');
} else {
jQuery(container).find('.detailsPopup').addClass('left');
}
if (jQuery(container).find('.detailsPopup').is(":visible")) {
jQuery(container).find('.detailsPopup').hide();
}
jQuery(container).find('.detailsPopup').css({
'top' : relativeTop,
'left' : relativeLeft
}).fadeIn();
currentProductID = orderID;
if (self.inited) {
clearInterval(timer);
self.openDetailsBox();
} else {
clearInterval(timer);
timer = setInterval(self.pendingLoading, 50);
}
} else {
jQuery(this).removeClass('active');
jQuery(container).find('.detailsPopup').fadeOut();
}
});
});
};
self.pendingLoading = function() {
if (self.inited) {
self.openDetailsBox();
clearTimeout(timer);
//console.log('inited');
}
//console.log('initing');
};
self.currentIndex = 0;
self.productDetailsArrPath = domainName + '/dcapi/productlist/product_list_by_skus.php';
self.getProductArray = function() {
if ( typeof quickViewItemJson === "undefined")
return;
var skuString = '';
for (var i in quickViewItemJson.Items) {
if (skuString == '' && quickViewItemJson.Items[i].Sku != '') {
skuString += quickViewItemJson.Items[i].Sku;
} else if (skuString != '' && quickViewItemJson.Items[i].Sku != '') {
skuString += '|' + quickViewItemJson.Items[i].Sku;
}
}
var postData;
if (jQuery.cookie('cookies_myCartID')) {
postData = JSON.stringify({
"storeViewId" : storeViewId,
"skus" : skuString,
"cartId" : myCartID
});
} else {
postData = JSON.stringify({
"storeViewId" : storeViewId,
"skus" : skuString
});
}
//console.log(postData);
jQuery.ajax({
url : self.productDetailsArrPath,
type : 'post',
dataType : 'json',
contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
processData : true,
crossDomain : true,
data : postData,
timeout : timeOutCount,
success : function(data, status, req) {
if (data[0].result == 1)
{
for(var i =0;i< data[0].product_list.length ; i++)
{
for(var j=0;j<quickViewItemJson.Items.length;j++)
{
//console.log(data[0].product_list[i].sku.toUpperCase()==quickViewItemJson.Items[j].Sku.toUpperCase());
if(data[0].product_list[i].sku.toUpperCase() == quickViewItemJson.Items[j].Sku.toUpperCase())
{
var productObj = data[0].product_list[i];
for(var g=0;g< quickViewItemJson.Items[j].photoList.length;g++)
{
var photoID = quickViewItemJson.Items[j].photoList[g];
featuredPhotoArr[photoID].addProductToPhotoList(productObj);
// console.log(i+" "+j+" "+g);
}
}
}
}
for(var i=0;i<featuredPhotoArr.length;i++)
{
featuredPhotoArr[i].updateItemArr();
}
//self.updateItemArr(data[0].product_list);
}
/*else if (data[0].result == 0)
alert('No Result Found');
else if (data[0].result == -1)
alert('Server Error');*/
},
error : function(error) {
}
});
};
self.reinitResponsive = function() {
jQuery(productListContainer).find('.productDetails').each(function(i) {
if (!self.itemArr[i].added_to_cart) {
jQuery(this).find('a.addToCart').unbind('click');
jQuery(this).find('a.addToCart').removeClass('added').find('span').text(dictionary["featuredPhoto"].popup.addToCart[lang]);
//console.log(self.itemArr[i].id);
jQuery(this).find('a.addToCart').bind('click', function(e) {
e.preventDefault();
if (!self.isLoading) {
self.isLoading = true;
jQuery(this).unbind('click');
jQuery(this).addClass('loading');
// console.log('featuredPhotoArr['+self.id+']');
addCart(self.itemArr[i].entity_id, 1,'featuredPhotoArr['+self.id+'].addedToCart(' + self.itemArr[i].entity_id + ',' + i + ')',true);
ga('ec:addProduct', {
'id': self.itemArr[index].sku,
'name': self.itemArr[index].name,
'price': self.itemArr[index].price,
'quantity': 1,
'dimension1': 'Product_icon'
});
ga('ec:setAction', 'add' ,{ 'list': 'Featured Photo : ' + window.location.pathname });
ga('send', 'event', 'Ecommerce', 'Add to Cart');
}
// alert('test');
// addCart(9, 1, 'home.addedToCart()');
});
} else {
jQuery(this).find('a.addToCart').unbind('click');
jQuery(this).find('a.addToCart').addClass('added').find('span').text(dictionary["featuredPhoto"].popup.addedToCart[lang]);
}
});
};
self.addProductToPhotoList = function(product) {
self.itemArr.push(product);
};
self.productPathPrefix = '/E-Shop/Product-Listing/#!/Product/';
self.productImagePathPrefix = domainName + '/media/catalog/product';
self.updateItemArr = function() {
if(jQuery(container).parent().find('.productListContainer').length == 0)
return;
productListContainer = jQuery(container).parent().find('.productListContainer').eq(0);
//jQuery(productListContainer).hide();
var dataArr = self.itemArr;
for (var i=0;i<dataArr.length;i++) {
var data = {};
data.image = dataArr[i].image;
data.name = dataArr[i].name;
data.price = dataArr[i].price;
data.desp = dataArr[i].description == null ? '' : dataArr[i].description;
data.id = dataArr[i].entity_id;
data.sku = dataArr[i].sku;
data.inStock = dataArr[i].stock_item.is_in_stock;
data.added_to_cart = dataArr[i].added_to_cart;
data.hasID = 0;
data.url = dataArr[i].url_key;
//self.itemArr.push(data);
//console.log(data);
var HTML = '<div class="productDetails clearfix">';
HTML += '<div class="productContent">';
HTML += '<a class="closeBtn"></a>'
HTML += '<div class="image"><img src="' + self.productImagePathPrefix + dataArr[i].image + '" /></div>';
HTML += '<div class="desc">';
HTML += '<div class="name">' + dataArr[i].name + '</div>';
HTML += '<div class="price"><span class="currency">HKD$</span>' + Number(dataArr[i].price).formatMoney(2,'') + '</div>';
HTML += '<div class="text">' + data.desp + '</div>';
HTML += '</div><span class="clearfix"></span>';
HTML += '<div class="btnContainer"><a href="' + self.productPathPrefix + dataArr[i].url_key + '" class="moreDetails"><span>'+dictionary["featuredPhoto"].popup.moreDetails[lang]+'</span></a>';
ga('ec:addImpression', { // Provide product details in an impressionFieldObject.
'id': data.sku, // Product ID (string).
'name': data.name, // Product name (string).
'list': 'Featured Photo : ' + window.location.pathname, // Product list (string).
'position': i, // Product position (number).
'price' : data.price
});
if (data.inStock == "1") {
HTML += '<a href="#" class="addToCart"><span>'+dictionary["featuredPhoto"].popup.addToCart[lang]+'</span></a></div>';
}
HTML += '</div>';
HTML += '</div>';
jQuery(productListContainer).append(HTML);
//console.log(HTML);
//console.log(jQuery(productListContainer));
}
ga('send', 'event', 'Ecommerce', 'View Product List');
jQuery(productListContainer).find('.loading').remove();
//console.log(jQuery(productListContainer).find('.productDetails').length);
if(jQuery(productListContainer).find('.productDetails').length != 0)
{
//jQuery(productListContainer).find('.title').show();
jQuery(productListContainer).children('*').show();
//return;
}
else
{
return;
}
//console.log('test');
if(self.itemArr.length == 0) return;
jQuery(productListContainer).find('.productDetails').each(function(i) {
if(typeof self.itemArr[i] === "undefined") return;
if (!self.itemArr[i].added_to_cart) {
jQuery(this).find('a.addToCart').unbind('click');
jQuery(this).find('a.addToCart').removeClass('added').find('span').text(dictionary["featuredPhoto"].popup.addToCart[lang]);
//console.log(self.itemArr[i].id);
jQuery(this).find('a.addToCart').bind('click', function(e) {
e.preventDefault();
if (!self.isLoading) {
self.isLoading = true;
jQuery(this).unbind('click');
jQuery(this).addClass('loading');
// console.log(self.itemArr[i].entity_id);
addCart(self.itemArr[i].entity_id, 1, 'featuredPhotoArr['+self.id+'].addedToCart(' + self.itemArr[i].entity_id + ',' + i + ')',true);
ga('require', 'ec');
ga('ec:addProduct', {
'id': self.itemArr[index].sku,
'name': self.itemArr[index].name,
'price': self.itemArr[index].price,
'quantity': 1,
'dimension1': 'Product_icon'
});
ga('ec:setAction', 'add' ,{ 'list': 'Featured Photo : ' + window.location.pathname });
ga('send', 'event', 'Ecommerce', 'Add to Cart');
//ga('send', 'event', 'Quick Item View', 'click', 'add to cart');
}
// alert('test');
// addCart(9, 1, 'home.addedToCart()');
});
} else {
jQuery(this).find('a.addToCart').unbind('click');
jQuery(this).find('a.addToCart').addClass('added').find('span').text(dictionary["featuredPhoto"].popup.addedToCart[lang]);
}
});
self.inited = true;
};
self.printDetailsBox = function() {
};
self.openDetailsBox = function() {
var index = -1;
for (var i in self.itemArr) {
if (self.itemArr[i].sku.toUpperCase() == quickViewItemJson.Items[currentProductID].Sku.toUpperCase()) {
index = i;
continue;
}
}
if (index != -1) {
jQuery(container).find('.detailsPopup').removeClass('loading');
jQuery(container).find('.detailsPopup').find('.image').html('<img src="' + self.productImagePathPrefix + self.itemArr[index].image + '" />');
jQuery(container).find('.detailsPopup').find('.name').html(self.itemArr[index].name);
jQuery(container).find('.detailsPopup').find('.price').html('<span class="currency">HKD$</span>' + Number(self.itemArr[index].price).formatMoney(2,''));
jQuery(container).find('.detailsPopup').find('.text').html(self.itemArr[index].desp);
jQuery(container).find('.detailsPopup').find('a.moreDetails').attr('href', self.productPathPrefix + self.itemArr[index].url_key);
ga('ec:addProduct', {
'id': self.itemArr[index].sku,
'name': self.itemArr[index].name,
'price': self.itemArr[index].price,
'quantity': 1,
'dimension1': 'Product_icon'
});
ga('ec:setAction', 'click', { 'list': 'Featured Photo : ' + window.location.pathname });
ga('send', 'event', 'Ecommerce', 'Clicking Products');
if (self.itemArr[index].stock_item.is_in_stock == 0) {
jQuery(container).find('.detailsPopup').find('a.addToCart').hide();
} else {
jQuery(container).find('.detailsPopup').find('a.addToCart').show();
if (!self.itemArr[index].added_to_cart) {
jQuery(container).find('.detailsPopup').find('a.addToCart').unbind('click');
jQuery(container).find('.detailsPopup').find('a.addToCart').removeClass('added').text(dictionary["featuredPhoto"].popup.addToCart[lang]);
jQuery(container).find('.detailsPopup').find('a.addToCart').bind('click', function(e) {
e.preventDefault();
if (!self.isLoading) {
jQuery(container).find('.detailsPopup').find('a.addToCart').unbind('click');
jQuery(container).find('.detailsPopup').find('a.addToCart').addClass('loading');
//console.log(self.itemArr[index].id);
//console.log('featuredPhotoArr['+self.id+']');
addCart(self.itemArr[index].entity_id, 1, 'featuredPhotoArr['+self.id+'].addedToCart(' + self.itemArr[index].entity_id + ',' + index + ')',true);
ga('ec:addProduct', {
'id': self.itemArr[index].sku,
'name': self.itemArr[index].name,
'price': self.itemArr[index].price,
'quantity': 1,
'dimension1': 'Product_icon'
});
ga('ec:setAction', 'add' ,{ 'list': 'Featured Photo : ' + window.location.pathname });
ga('send', 'event', 'Ecommerce', 'Add to Cart');
//ga('send', 'event', 'Quick Item View', 'click', 'add to cart');
}
// alert('test');
// addCart(9, 1, 'home.addedToCart()');
});
} else {
jQuery(container).find('.detailsPopup').find('a.addToCart').unbind('click');
jQuery(container).find('.detailsPopup').find('a.addToCart').addClass('added').text(dictionary["featuredPhoto"].popup.addedToCart[lang]);
}
}
}
};
self.addedToCart = function(id, order) {
myCartID = cartArray[0].cart_id;
var date = new Date();
date.setTime(date.getTime() + (30 * 60 * 1000));
jQuery.cookie('cookies_myCartID',myCartID,{ path: '/' ,expires: date});
if(jQuery.cookie('cookies_hasClassItem'))
jQuery.cookie('cookies_hasClassItem','true',{ path: '/' ,expires: date});
if (cartArray[0].result != 1) {
jQuery(container).find('.detailsPopup').find('a.addToCart').removeClass('loading').addClass('added').text(dictionary["featuredPhoto"].popup.outOfStock[lang]);
jQuery(productListContainer).find('.productDetails').eq(order).find('a.addToCart').removeClass('loading').addClass('added').find('span').text(dictionary["featuredPhoto"].popup.outOfStock[lang]);
} else {
updateCartNumber();
jQuery(container).find('.detailsPopup').find('a.addToCart').removeClass('loading').addClass('added').text(dictionary["featuredPhoto"].popup.addedToCart[lang]);
jQuery(productListContainer).find('.productDetails').eq(order).find('a.addToCart').removeClass('loading').addClass('added').find('span').text(dictionary["featuredPhoto"].popup.addedToCart[lang]);
self.itemArr[order].added_to_cart = true;
self.reinitResponsive();
}
self.isLoading = false;
};
};
/** Milestone Functions **/
var MILESTONE_MAXIMUN_IMAGE_WIDTH = 250;
var MILESTONE_ITEM_PADDING = 20;
var MILESTONE_LINE_PADDING = 30;
var MILESTONE_TOP_PADDING = 21 + 56 + 20;
var milestoneSetup = function() {
var self = this;
var threeYearContainer = jQuery('#contentContainer > .content .milestoneWrapper .threeYearGroup');
self.init = function() {
jQuery(threeYearContainer).each(function(i) {
var selfYearContainer = jQuery(this);
jQuery(this).find('.item:not(:has(.image))').addClass('plaintext');
jQuery(this).find('.milestoneMonth .item:odd').addClass('right');
jQuery(this).find('.threeYear').click(function(e) {
var parent = jQuery(this).parent();
if (!jQuery(parent).hasClass('inited') && !jQuery(parent).hasClass('active')) {
if (isResponsive) {
jQuery(parent).addClass('active').find('img').trigger("milestoneLoadImg");
} else {
jQuery(parent).addClass('active').addClass('inited').find('img').trigger("milestoneLoadImg");
jQuery(selfYearContainer).find('.milestoneMonth').each(function(g) {
jQuery(this).find('.item').each(function(h) {
//console.log(g+" "+h);
if (h == 0) {
if (jQuery(this).height() / 2 < MILESTONE_TOP_PADDING) {
jQuery(this).css('top', MILESTONE_TOP_PADDING - jQuery(this).height() / 2);
} else {
jQuery(this).css('top', 20);
}
} else {
var lineHeight = jQuery(this).hasClass('plaintext') ? jQuery(this).height() : jQuery(this).find('.image').height();
var prevElementIndex = h - 1 > 0 ? h - 1 : 0;
var prevElement = jQuery(selfYearContainer).find('.milestoneMonth').eq(g).find('.item').eq(prevElementIndex);
var prevElementLineHeight = jQuery(prevElement).hasClass('plaintext') ? jQuery(prevElement).height() : jQuery(prevElement).find('.image').height();
var offsetTop = parseInt(jQuery(prevElement).css('top'), 10) - (parseInt(lineHeight, 10) / 2 - parseInt(prevElementLineHeight, 10) / 2 - MILESTONE_LINE_PADDING)
if (Math.floor(h / 2) >= 1) {
var upperElementIndex = h - 2 > 0 ? h - 2 : 0;
var upperElement = jQuery(selfYearContainer).find('.milestoneMonth').eq(g).find('.item').eq(upperElementIndex);
var minimumOffsetTop = parseInt(jQuery(upperElement).css('top'), 10) + parseInt(jQuery(upperElement).height(), 10) + MILESTONE_ITEM_PADDING;
var newTop = offsetTop > minimumOffsetTop ? offsetTop : minimumOffsetTop;
// console.log(jQuery(upperElement).css('top')+" "+jQuery(upperElement).css('height'));
jQuery(this).css('top', newTop);
} else {
jQuery(this).css('top', offsetTop);
}
//jQuery(this).css('top',0);
}
});
var bottomLeftElementHeight = jQuery(this).find('.item:not(.right):last').length > 0 ? parseInt(jQuery(this).find('.item:not(.right):last').css('top'), 10) + jQuery(this).find('.item:not(.right):last').height() : 0;
var bottomRightElementHeight = jQuery(this).find('.item.right:last').length > 0 ? parseInt(jQuery(this).find('.item.right:last').css('top'), 10) + jQuery(this).find('.item.right:last').height() : 0;
var newHeight = bottomLeftElementHeight > bottomRightElementHeight ? bottomLeftElementHeight : bottomRightElementHeight;
jQuery(this).height(newHeight);
});
}
} else if (!jQuery(parent).hasClass('active'))
jQuery(parent).addClass('active');
else if (jQuery(parent).hasClass('active'))
jQuery(parent).removeClass('active');
});
jQuery(this).find('img').each(function(j) {
var width = GetURLParameterByString(jQuery(this).attr('data-original'), 'width');
var height = GetURLParameterByString(jQuery(this).attr('data-original'), 'height');
if (width > MILESTONE_MAXIMUN_IMAGE_WIDTH || width < MILESTONE_MAXIMUN_IMAGE_WIDTH) {
height *= MILESTONE_MAXIMUN_IMAGE_WIDTH / width;
width = MILESTONE_MAXIMUN_IMAGE_WIDTH;
}
jQuery(this).width(width);
jQuery(this).height(height);
var ext = GetURLParameterByString(jQuery(this).attr('data-original'), 'ext');
if (ext == '.png')
jQuery(this).parent().parent().addClass('png');
//console.log(jQuery(this).attr('data-original')+" "+width+" "+height);
}).lazyload({
event : "milestoneLoadImg",
effect : "fadeIn"
});
});
jQuery('.threeYear').eq(0).click();
};
self.reInit = function() {
jQuery(threeYearContainer).each(function(i) {
if (!jQuery(this).hasClass('inited') && jQuery(this).hasClass('active')) {
jQuery(this).find('.threeYear').click().click();
}
});
};
};
var listFixHeight = function(input) {
var self = this;
var elementArr = input;
self.init = function() {
if(jQuery(elementArr[0]).css('box-sizing') != 'border-box')
{
for (var i in elementArr) {
var maxHeight = 0;
jQuery(elementArr[i]).each(function(j) {
if (jQuery(this).height() > maxHeight) {
maxHeight = jQuery(this).height();
}
});
jQuery(elementArr[i]).css({
'height' : maxHeight
});
}
}
else
{
for (var i in elementArr) {
var maxHeight = 0;
jQuery(elementArr[i]).each(function(j) {
if (jQuery(this).innerHeight() > maxHeight) {
maxHeight = jQuery(this).innerHeight();
}
});
jQuery(elementArr[i]).css({
'height' : maxHeight
});
}
}
};
self.destroy = function() {
for (var i in elementArr) {
jQuery(elementArr[i]).css({
'height' : ''
});
}
}
}
var specialPromoSection = function() {
var self = this;
var hashPrefix = '!/';
self.currentPage = 0;
self.currentPageName = '';
self.sitemap = sitemap;
self.inited = false;
self.loading = false;
self.productLoading = false;
self.init = function() {
var hashArr = window.location.hash.split('/');
if (hashArr.length > 1) {
var pageName = hashArr[1];
var gotoPage = -1;
for (var i in self.sitemap) {
if (self.sitemap[i].id == pageName) {
gotoPage = i;
continue;
}
}
if (gotoPage != -1 && window.location.hash.search('/' + hProduct + '/') != -1 && !self.productLoading) {
self.productLoading = true;
self.currentPageName = self.sitemap[gotoPage].id;
jQuery(document).ready(function(e){showProductDetail("loadPromo", hashArr[hashArr.length - 1]);});
self.loadPage(gotoPage);
} else if (gotoPage != -1) {
self.loadPage(gotoPage);
} else {
self.loadPage(0);
}
} else {
self.loadPage(0);
}
/*self.currentPageName = window.location.hash == "#" || !window.location.hash ? '' : window.location.hash.replace('#'+hashPrefix,'');
jQuery('#contentContainer .contentSlider .contentList').empty();
if(self.currentPageName == '')
{
self.currentPageName = self.sitemap[0].id;
//self.currentPage = 0;
self.loadPage(0);
}
else
{
var gotoPage = 0;
for(var i in self.sitemap)
{
if(self.sitemap[i].id == self.currentPageName)
{
gotoPage = i;
continue;
}
}
self.loadPage(gotoPage);
}*/
//console.log(self.currentPage);
jQuery(window).bind('hashchange', function() {
var hashArr = window.location.hash.split('/');
if (hashArr.length > 1) {
var pageName = hashArr[1];
var gotoPage = -1;
for (var i in self.sitemap) {
if (self.sitemap[i].id == pageName) {
gotoPage = i;
continue;
}
}
if (gotoPage != -1 && window.location.hash.search('/' + hProduct + '/') != -1 && !self.productLoading) {
self.productLoading = true;
//console.log(hashArr[hashArr.length - 1]);
self.currentPageName = self.sitemap[gotoPage].id;
jQuery(document).ready(function(e){showProductDetail("loadPromo", hashArr[hashArr.length - 1]);});
self.loadPage(gotoPage);
} else if (gotoPage != -1) {
self.loadPage(gotoPage);
} else {
self.loadPage(0);
}
} else {
self.loadPage(0);
}
});
/*jQuery('#contentContainer').swipe( {
allowPageScroll : 'vertical',
swipeLeft:function(event, direction, distance, duration, fingerCount, fingerData) {
if(direction == "right" && self.currentPage != 0)
self.loadPage(self.currentPage - 1);
else if(direction == "left" && self.currentPage < self.sitemap.length - 1)
self.loadPage(self.currentPage + 1);
},swipeRight:function(event, direction, distance, duration, fingerCount, fingerData) {
if(direction == "right" && self.currentPage != 0)
self.loadPage(self.currentPage - 1);
else if(direction == "left" && self.currentPage < self.sitemap.length - 1)
self.loadPage(self.currentPage + 1);
},
threshold:75
});*/
};
self.loadPageFromURL = function(url) {
};
self.loadPage = function(pageID) {
if ((pageID == self.currentPage && self.inited ) || self.loading)
return;
window.location.hash = hashPrefix + sitemap[pageID].name;
self.loading = true;
jQuery('#contentContainer').addClass('ajax');
jQuery.ajax({
url : self.sitemap[pageID].link,
type : 'post',
dataType : 'html',
contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
processData : true,
timeout : timeOutCount,
success : function(data, status, req) {
data = data.split(' <!-- AJAX Starts -->');
data = data[1].split('<!-- AJAX Ends -->');
//console.log(data);
var content = data[0].split(' <!-- Content Starts -->');
content = content[1].split('<!-- Content Ends -->');
// jQuery("#contentContainer .contentSlider .contentList").empty().append(content[0]);
if (jQuery('#contentContainer .contentSlider .contentList > .content').length > 0) {
if (self.currentPage > pageID)
self.loadPrevPageAni(content[0]);
else
self.loadNextPageAni(content[0]);
jQuery('#contentContainer').removeClass('ajax');
} else {
productListWidgetArr.length = 0;
jQuery("#contentContainer .contentSlider .contentList").empty().append(content[0]);
for (var i in productListWidgetArr) {
productListWidgetArr[i].init();
}
self.loading = false;
jQuery('#contentContainer').removeClass('ajax');
}
self.currentPageName = self.sitemap[pageID].id;
self.currentPage = pageID;
var nav = data[0].split('<!-- Pagenav Starts -->');
nav = nav[1].split('<!-- Pagenav Ends -->');
if (jQuery(".pagenavContainer").length > 0) {
jQuery(".pagenavContainer").fadeOut(function() {
jQuery(".pagenavContainer").eq(0).remove();
});
jQuery("#contentContainer .contentSlider").before(nav[0]);
jQuery(".pagenavContainer").last().hide().fadeIn();
} else {
jQuery(".pagenavContainer").eq(0).remove();
jQuery("#contentContainer .contentSlider").before(nav[0]);
jQuery(".pagenavContainer").hide().fadeIn();
}
if (!self.inited) {
var menu = data[0].split('<!-- Menu Starts -->');
menu = menu[1].split('<!-- Menu Ends -->');
jQuery(".menuContainer").remove();
jQuery("#contentContainer .contentSlider").before(menu[0]);
self.inited = true;
self.initMenu();
}
},
error : function(error) {
// console.log(error);
jQuery('<div class="displayMsg">Cannot get product information, Please try again later.</div>').appendTo("#contentContainer").fadeIn();
}
})
};
self.loadNextPage = function() {
};
self.loadPrevPageAni = function(contentHTML) {
jQuery('.featuredPhotoContainer .background,#backgroundContainer,.bottomShadow').fadeOut(function() {
});
productListWidgetArr.length = 0;
var pageWidth = jQuery(window).width() >= 950 ? 950 : jQuery(window).width();
// console.log(pageWidth);
jQuery('.bottomShadow').eq(0).fadeOut(function() {
jQuery('.featuredPhotoContainer .background,#backgroundContainer,.bottomShadow').hide();
jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .contentSlider').css('overflow', 'hidden');
jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .contentSlider .contentList').css('marginLeft', -pageWidth).prepend(contentHTML).stop().animate({
'marginLeft' : 0
}, function() {
//console.log('prev');
jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .contentSlider .contentList').children('.content').last().remove();
for (var i in productListWidgetArr) {
productListWidgetArr[i].init();
}
jQuery('.featuredPhotoContainer .background,#backgroundContainer,.bottomShadow').fadeIn();
jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .contentSlider').css('overflow', 'visible');
self.loading = false;
});
});
}
self.loadNextPageAni = function(contentHTML) {
jQuery('.featuredPhotoContainer .background,#backgroundContainer,.bottomShadow').fadeOut(function() {
});
productListWidgetArr.length = 0;
var pageWidth = jQuery(window).width() >= 950 ? 950 : jQuery(window).width();
//console.log(pageWidth);
jQuery('.bottomShadow').eq(0).fadeOut(function() {
jQuery('.featuredPhotoContainer .background,#backgroundContainer,.bottomShadow').hide();
jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .contentSlider').css('overflow', 'hidden');
jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .contentSlider .contentList').css('marginLeft', 0).append(contentHTML).stop().animate({
'marginLeft' : -pageWidth
}, function() {
jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .contentSlider .contentList').css('marginLeft', 0).children('.content').eq(0).remove();
//console.log('next');
jQuery('.featuredPhotoContainer .background,#backgroundContainer,.bottomShadow').fadeIn();
for (var i in productListWidgetArr) {
productListWidgetArr[i].init();
}
jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .contentSlider').css('overflow', 'visible');
self.loading = false;
});
});
}
self.initMenu = function() {
var menuSlider = jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .menuContainer .menuSlider');
var menuList = jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .menuContainer .menu');
var item = jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .menuContainer .menu .list .item');
var list = jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .menuContainer .menu .list');
var listNumber = jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .menuContainer .menu .list').length;
var itemNumber = 0;
var listWidth = 0;
var menuToggle = jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .menuContainer .menuHolder .toggle');
jQuery(list).each(function(i) {
if (jQuery(this).find('.item').length > itemNumber)
itemNumber = jQuery(this).find('.item').length;
});
listWidth = 132 * itemNumber + 5;
jQuery(menuList).css({
'width' : listWidth,
'height' : 264 * listNumber
});
jQuery(menuSlider).css({
'height' : 264 * listNumber + 30
/*'top' : -((264* listNumber +30)/2)*/
});
jQuery(menuToggle).click(function(e) {
e.preventDefault();
if (jQuery(this).hasClass('active')) {
jQuery(this).removeClass('active');
jQuery(menuSlider).stop().animate({
'width' : 27
})
} else {
jQuery(this).addClass('active');
jQuery(menuSlider).stop().animate({
'width' : listWidth + 27
});
}
});
};
}
var productListWidgetArr = [];
var productListWidget = function(sku, type, catName) {
var self = this;
self.id = productListWidgetArr.length;
self.sku = sku;
self.type = type;
self.catName = catName;
self.data;
self.container;
self.productListEngine;
self.init = function() {
jQuery(document).ready(function() {
var curIndex = self.id;
if (jQuery(".relatedProduct:not(.noShop)").length > 1) curIndex = jQuery(".relatedProduct:not(.noShop)").length - 1;
self.container = jQuery(".relatedProduct:not(.noShop)").eq(curIndex);
jQuery(self.container).addClass('ajax');
if (self.type == "sku") {
getProductBySku(self.sku, function(obj) {
jQuery(self.container).removeClass('ajax');
if(typeof obj[0] != "undefined" && obj[0].result == 1)
{
self.data = obj[0].product_list;
if(obj[0].product_list.length > 0)
{
self.AppendProduct(obj[0].product_list);
}
else
{
self.errorHandling(dictionary["shoppingCart"].errorMsg.noResultsFound[lang]);
}
}else
{
self.errorHandling(dictionary["shoppingCart"].errorMsg.noResultsFound[lang]);
}
});
} else if (type == "categoryName") {
// console.log("Type: categoryName");
getProductByCatergory(self.catName, function(obj) {
jQuery(self.container).removeClass('ajax');
if(typeof obj[0] != "undefined" && obj[0].result == 1)
{
self.data = obj[0].product_list;
if(obj[0].product_list.length > 0)
{
self.AppendProduct(obj[0].product_list);
}else
{
self.errorHandling(dictionary["shoppingCart"].errorMsg.noResultsFound[lang]);
}
}
else
{
self.errorHandling(dictionary["shoppingCart"].errorMsg.noResultsFound[lang]);
}
});
}
});
};
self.AppendProduct = function(data) {
var folderPath = '/media/catalog/product';
//console.log(self.id);
var numOfRowInFourCol = Math.ceil(data.length /4);
var numOfRowInThreeCol = Math.ceil(data.length /3);
var numOfRowInTwoCol = Math.ceil(data.length /2);
jQuery(self.data).each(function(i) {
var itemClassName = 'item sku_'+ self.data[i].sku.replace(/[^a-zA-Z0-9]/g,'');
if(Math.ceil((i+1)/4) == numOfRowInFourCol)
itemClassName += ' lastRowInFour';
if(Math.ceil((i+1)/3) == numOfRowInThreeCol)
itemClassName += ' lastRowInThree';
if(Math.ceil((i+1)/2) == numOfRowInTwoCol)
itemClassName += ' lastRowInTwo';
var items = jQuery("<a href='javascript:showProductDetail(\"clickPromo\",\"" + self.data[i].url_key + "\");' class='"+itemClassName+"'>").appendTo(jQuery(self.container).find('.items')).hide().delay(50*i).fadeIn(function(e){
self.productListEngine.init();
});
var image;
if (self.data[i].image != '' && self.data[i].image != null && self.data[i].image != undefined) {
image = self.data[i].image;
} else {
image = self.data[i].small_image;
}
jQuery(self.container).find(".item.sku_" + self.data[i].sku.replace(/[^a-zA-Z0-9]/g,'')).append("<span class='image'><img src='" + domainName + folderPath + image + "' alt='" + self.data[i].name + "' /></span>");
jQuery(self.container).find(".item.sku_" + self.data[i].sku.replace(/[^a-zA-Z0-9]/g,'')).append("<span class='name'>" + self.data[i].name + "</span>");
var myOption = self.data[i].has_options;
var myCurrency = 'HK';
if(myOption>0){
if(lang=='en'){
jQuery(self.container).find(".item.sku_" + self.data[i].sku.replace(/[^a-zA-Z0-9]/g,'')).append('<span class="price"><span class="smallCurrenty">' + myCurrency + '$ </span>' + Number(self.data[i].price).formatMoney(2,'') + '</span>');
//jQuery('<div class="productPrice"><span class="smallCurrenty">From ' + myCurrency + '$ </span>' + tSep(self.data[i].price) + '</div>').appendTo(myProduct);
}else{
jQuery(self.container).find(".item.sku_" + self.data[i].sku.replace(/[^a-zA-Z0-9]/g,'')).append('<span class="price"><span class="smallCurrenty">' + myCurrency + '$</span>' + Number(self.data[i].price).formatMoney(2,'') + '<span class="smallCurrenty"></span></span>');
//jQuery('<div class="productPrice"><span class="smallCurrenty">' + myCurrency + '$</span>' + tSep(self.data[i].price) + '<span class="smallCurrenty">起</span></div>').appendTo(myProduct);
}
}else{
jQuery(self.container).find(".item.sku_" + self.data[i].sku.replace(/[^a-zA-Z0-9]/g,'')).append('<span class="price"><span class="smallCurrenty">' + myCurrency + '$</span>' + Number(self.data[i].price).formatMoney(2,'') + '</span>');
//jQuery('<div class="productPrice"><span class="smallCurrenty">' + myCurrency + '$</span>' + tSep(self.data[i].price) + '</div>').appendTo(myProduct);
}
ga('ec:addImpression', { // Provide product details in an impressionFieldObject.
'id': self.data[i].sku, // Product ID (string).
'name': self.data[i].name, // Product name (string).
'list': 'Special Promotion : ' + window.location.pathname, // Product list (string).
'position': i, // Product position (number).
'price' : self.data[i].price
});
//jQuery(self.container).find(".item.sku_" + self.data[i].sku).append("<span class='price'>HK$ " + tSep(self.data[i].price) + "");
});
ga('send', 'event', 'Ecommerce', 'View Product List');
//console.log(jQuery(self.container).html());
self.productListEngine = new listFixHeight([jQuery(self.container).find('.image'), jQuery(self.container).find('.name'), jQuery(self.container).find('.price')]);
//self.productListEngine.init();
};
self.errorHandling = function(errorMsg){
jQuery(self.container).removeClass('ajax');
jQuery(self.container).append('<p>'+errorMsg+'</p>');
};
if(typeof specialPromo === "undefined")
self.init();
//self.init();
}
function GetURLParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
function GetURLParameterByString(urlString, sParam) {
var sPageURL = urlString;
var sURLVariablesArr = sPageURL.split('?');
var sURLVariables = sURLVariablesArr[sURLVariablesArr.length - 1].split('&');
//console.log(sURLVariables);
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
function insertParam(url, key, value) {
key = encodeURI(key);
value = encodeURI(value);
var kvp = url.substr(1).split('&');
var i = kvp.length;
var x;
while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) {
kvp[kvp.length] = [key, value].join('=');
}
//this will reload the page, it's likely better to store this until finished
return kvp.join('&');
}
// JavaScript Document
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function randomNum(size) {
var a = new Array();
var b = new Array();
for (var i = 0; i < size; i++) {
a[i] = i;
}
for ( i = 0; i < size; i++) {
var ran = Math.floor(Math.random() * a.length);
b.push(a.splice(ran, 1));
}
return b;
}
function cookingClassFun() {
jQuery(document).ready(function() {
var ranNum1 = 0;
var ranNum2 = 0;
var ranSpecialNum1 = 0;
var ranNum1Array;
var ranNum2Array;
getUrlVars();
var searchTxt = getUrlVars()["q"];
if (searchTxt) {
} else {
var totalItem = jQuery('.cookingClassItem').length;
var totalSpecialItem = typeof recipeBoxArray != "undefined" ? recipeBoxArray.length : 0;
ranNum1 = randomNum(5);
ranNum2 = randomNum(10);
ranSpecialNum1 = randomNum(totalSpecialItem);
if (totalItem >= 5 && totalItem < 10 && totalSpecialItem > 0) {
appendSpecItem(ranSpecialNum1[0], ranNum1[0]);
}
if (totalItem == 10 && totalSpecialItem > 0) {
appendSpecItem(ranSpecialNum1[0], ranNum2[0]);
appendSpecItem(ranSpecialNum1[1], ranNum2[1]);
}
}
//append special Item
function appendSpecItem(num, order) {
var cookingClassSpecialItem = jQuery('<div/>', {
'class' : 'cookingClassSpecialItem'
});
var thumbnail = jQuery('<div/>', {
'class' : 'thumbnail'
});
var thumbnailA = jQuery('<a/>', {
'href' : recipeBoxArray[num].link,
'title' : recipeBoxArray[num].title
});
var thumbnailImg = jQuery('<img/>', {
'src' : recipeBoxArray[num].imgpath,
'alt' : recipeBoxArray[num].title
})
thumbnailA.append(thumbnailImg);
thumbnail.append(thumbnailA);
cookingClassSpecialItem.append(thumbnail);
jQuery(jQuery(".cookingClassItem")[order]).after(cookingClassSpecialItem);
}
});
}
function chefDetailFun() {
jQuery(document).ready(function() {
jQuery(".askQuestion a").attr('href', '#askQuestionForm');
jQuery(".askQuestion a").colorbox({
inline : true,
width : "562"
});
jQuery(".askQuestion a").click(function() {
var nameVal = jQuery('#tbName').attr('value');
var emailVal = jQuery('#tbEmail').attr('value');
var txtVal = jQuery('#tbMessage').attr('value');
jQuery('#tbName').attr('onfocus', 'if(this.value=="' + nameVal + '") this.value="";');
jQuery('#tbName').attr('onblur', 'if(this.value=="") this.value="' + nameVal + '";');
jQuery('#tbEmail').attr('onfocus', 'if(this.value=="' + emailVal + '") this.value="";');
jQuery('#tbEmail').attr('onblur', 'if(this.value=="") this.value="' + emailVal + '";');
jQuery('#tbMessage').attr('onfocus', 'if(this.value=="' + txtVal + '") this.value="";');
jQuery('#tbMessage').attr('onblur', 'if(this.value=="") this.value="' + txtVal + '";');
})
});
}
var myClassItemID = '';
function cookingClasssSignUpFun() {
jQuery(document).ready(function(e){
var mySKU = classSKU;
var hasID = true;
var productDetailArray;
// var productDetailPath = domainName+'/api/rest/productlist/collection/is_detail/1/product_id/'+myTargetID;
if(typeof mySKU != undefined && mySKU != undefined && mySKU != "")
{
var productDetailPath = domainName + '/dcapi/classes/productlist/product_list_by_skus.php';
var myData = JSON.stringify({
"storeViewId": storeViewId,
"skus": mySKU
});
jQuery.ajax({
url: productDetailPath,
type: 'post',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
processData: true,
crossDomain: true,
data: myData,
timeout: timeOutCount,
success: function(data, status, req) {
detailArray = data;
if(data[0].product_list.length == 0)
{
jQuery('.askQuestion').remove();
return;
}
myClassItemID = data[0].product_list[0].entity_id;
var isInStock = data[0].product_list[0].stock_item.is_in_stock;
if(data[0].product_list[0].expired == 1)
{
jQuery('.askQuestion').empty().removeClass('ajax').html(dictionary['cultureClub'].checkoutFlow.expiredtClassInfo[lang]);
}
else if(data[0].product_list[0].citysuper_class_mode == "Waitlist" && data[0].product_list[0].waitlist == 1)
{
jQuery('.askQuestion').empty().removeClass('ajax').html(dictionary["checkoutFlow"].uiMsg.event_expired[lang]);
}
else if(data[0].product_list[0].cutoff == 1)
{
jQuery('.askQuestion').empty().removeClass('ajax').html(dictionary["checkoutFlow"].uiMsg.event_expired[lang]);
}
else if (!jQuery.cookie('cookies_myCartID') && isInStock == 1 && data[0].product_list[0].citysuper_class_mode != "Waitlist") {
hasID = false;
initClassProduct();
}
else if(isInStock == 1 && data[0].product_list[0].citysuper_class_mode != "Waitlist")
{
var productDetailLink = domainName + '/dcapi/shoppingcart/cart_items_qty.php';
var myData = JSON.stringify({
"cartId": myCartID,
"productId": myClassItemID
});
jQuery.ajax({
url: productDetailLink,
type: 'post',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
processData: true,
crossDomain: true,
data: myData,
timeout: timeOutCount,
success: function(data, status, req) {
productDetailArray = data;
//console.log(productDetailArray)
initClassProduct();
},
error: function(error) {
jQuery('.askQuestion').empty().removeClass('ajax').text('error: ' + error.toString());
}
});
}
else if(data[0].product_list[0].citysuper_class_mode == "Waitlist")
{
jQuery('.askQuestion').empty().removeClass('ajax').html(dictionary['cultureClub'].checkoutFlow.waitlistClassInfo[lang]);
jQuery('.askQuestion').append("<br/><br/><a href='#askQuestionForm' target='_blank' class='btnTag singUp active' style='margin:0'>"+dictionary['cultureClub'].checkoutFlow.waitlistBtn[lang]+"</a>");
initWaitlistForm();
//jQuery('.askQuestion a.singUp').bind('click',openWaitlistForm);
}
else
{
jQuery('.askQuestion').empty().removeClass('ajax').html(dictionary['cultureClub'].checkoutFlow.outOfStock[lang]);
}
},
error: function(error) {
jQuery('.askQuestion').empty().removeClass('ajax').text('error: ' + error.toString());
}
})
}
var isSubmitting = false;
function initWaitlistForm()
{
var self = this;
var path = domainName + '/index.php/api_waitlist/waitlist/register'
self.openPopup = function(){
//jQuery('#askQuestionForm .formInner').removeClass('submitting');
jQuery('#askQuestionForm .formInner,#askQuestionForm .send').show();
jQuery('#askQuestionForm .successMsg').remove();
if(isResponsive)
{
jQuery('#askQuestionForm').height(jQuery(document).height());
jQuery(window).scrollTop(0);
}
jQuery('#askQuestionForm').fadeIn();
};
self.closePopup = function(){
jQuery('#askQuestionForm').fadeOut();
};
self.clearform = function(){
jQuery('#askQuestionForm input#p_lt_ddlBuyerTitle').val('');
jQuery('#askQuestionForm input#waitlistFirstName').val('');
jQuery('#askQuestionForm input#waitlistLastName').val('');
jQuery('#askQuestionForm input#waitlistMobilePhoneNo').val('');
jQuery('#askQuestionForm input#waitlistEmailAddress').val('');
jQuery('#askQuestionForm input#waitlistTotalParticipants').val('');
};
self.submitForm = function(){
var isValid = true;
var myPrefix = jQuery('#askQuestionForm #waitlistPrefix').val();
var myFirstName = jQuery('#askQuestionForm input#waitlistFirstName').val();
var myLastName = jQuery('#askQuestionForm input#waitlistLastName').val();
var myMobilePhoneNo = jQuery('#askQuestionForm input#waitlistMobilePhoneNo').val();
var myEmail = jQuery('#askQuestionForm input#waitlistEmailAddress').val();
var myQty = jQuery('#askQuestionForm input#waitlistTotalParticipants').val();
if(myFirstName.length <= 0 || /^\s+$/.test(myFirstName) == true || myLastName.length <= 0 || /^\s+$/.test(myLastName) == true )
{
jQuery('#askQuestionForm').find('.buyerName').find('.inValidMsg').remove();
jQuery('<div class="inValidMsg">'+dictionary["cultureClub"].waitlist.errorMsg.nameEmpty[lang]+'</div>').appendTo(jQuery('#askQuestionForm').find('.buyerName')).hide().fadeIn();
isValid = false;
}
else
{
jQuery('#askQuestionForm').find('.buyerName').find('.inValidMsg').remove();
}
if(myMobilePhoneNo.length <= 0 || /^\s+$/.test(myMobilePhoneNo) == true)
{
jQuery('#askQuestionForm').find('.phone').find('.inValidMsg').remove();
jQuery('<div class="inValidMsg">'+dictionary["cultureClub"].waitlist.errorMsg.mobilePhoneEmpty[lang]+'</div>').appendTo(jQuery('#askQuestionForm').find('.phone')).hide().fadeIn();
isValid = false;
}
else if(!jQuery.isNumeric(myMobilePhoneNo))
{
jQuery('#askQuestionForm').find('.phone').find('.inValidMsg').remove();
jQuery('<div class="inValidMsg">'+dictionary["cultureClub"].waitlist.errorMsg.mobilePhoneInvalid[lang]+'</div>').appendTo(jQuery('#askQuestionForm').find('.phone')).hide().fadeIn();
isValid = false;
}
else
{
jQuery('#askQuestionForm').find('.phone').find('.inValidMsg').remove();
}
var emailValid = validateEmail(myEmail);
if (myEmail.length <= 0 || /^\s+$/.test(myEmail) == true) {
jQuery('#askQuestionForm').find('.mail').find('.inValidMsg').remove();
jQuery('<div class="inValidMsg">'+dictionary["cultureClub"].waitlist.errorMsg.emailEmpty[lang]+'</div>').appendTo(jQuery('#askQuestionForm').find('.mail')).hide().fadeIn();
isValid = false;
}
else if(!emailValid){
jQuery('#askQuestionForm').find('.mail').find('.inValidMsg').remove();
jQuery('<div class="inValidMsg">'+dictionary["cultureClub"].waitlist.errorMsg.emailInvalid[lang]+'</div>').appendTo(jQuery('#askQuestionForm').find('.mail')).hide().fadeIn();
isValid = false;
}
else {
jQuery('#askQuestionForm').find('.mail').find('.inValidMsg').remove();
}
if(myQty.length <= 0 || /^\s+$/.test(myQty) == true)
{
jQuery('#askQuestionForm').find('.participants').find('.inValidMsg').remove();
jQuery('<div class="inValidMsg">'+dictionary["cultureClub"].waitlist.errorMsg.quantityEmpty[lang]+'</div>').appendTo(jQuery('#askQuestionForm').find('.participants')).hide().fadeIn();
isValid = false;
}
else if(!jQuery.isNumeric(myQty))
{
jQuery('#askQuestionForm').find('.participants').find('.inValidMsg').remove();
jQuery('<div class="inValidMsg">'+dictionary["cultureClub"].waitlist.errorMsg.quantityInvalid[lang]+'</div>').appendTo(jQuery('#askQuestionForm').find('.participants')).hide().fadeIn();
isValid = false;
}
else if(parseInt(myQty) < 1)
{
jQuery('#askQuestionForm').find('.participants').find('.inValidMsg').remove();
jQuery('<div class="inValidMsg">'+dictionary["cultureClub"].waitlist.errorMsg.quantityTooLess[lang]+'</div>').appendTo(jQuery('#askQuestionForm').find('.participants')).hide().fadeIn();
isValid = false;
}
else if(parseInt(myQty) > 99)
{
jQuery('#askQuestionForm').find('.participants').find('.inValidMsg').remove();
jQuery('<div class="inValidMsg">'+dictionary["cultureClub"].waitlist.errorMsg.quantityTooMany[lang]+'</div>').appendTo(jQuery('#askQuestionForm').find('.participants')).hide().fadeIn();
isValid = false;
}
else
{
jQuery('#askQuestionForm').find('.participants').find('.inValidMsg').remove();
}
if(isValid && ! isSubmitting)
{
isSubmitting = true;
jQuery('#askQuestionForm .formInner').addClass('submitting');
var myData = JSON.stringify({
"store_id" : storeViewId.toString(),
"prefix" : myPrefix,
"sku" : mySKU,
"firstname" : escapeHtml(myFirstName),
"lastname" : escapeHtml(myLastName),
"email" : escapeHtml(myEmail),
"phone" : myMobilePhoneNo,
"qty" : myQty
});
jQuery.ajax({
url: path,
type: 'post',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
processData: true,
crossDomain: true,
data: myData,
timeout: timeOutCount,
success: function(data, status, req) {
//console.log(data);
jQuery('#askQuestionForm .formInner').removeClass('submitting');
isSubmitting = false;
if(data.result == 1)
{
jQuery('#askQuestionForm .formInner,#askQuestionForm .send').hide();
jQuery('#askQuestionForm .successMsg').remove();
var ticketNo = data.msg.split('no.')[1];
var postfix = dictionary["cultureClub"].waitlist.successMsg.postfix[lang].replace('%num%',ticketNo);
jQuery('#askQuestionForm .formInner').after(jQuery('<div class="successMsg"><div class="title">'+dictionary["cultureClub"].waitlist.successMsg.prefix[lang]+'</div><div class="desc">'+postfix+'</div></div>'));
self.clearform();
}
else
{
alert(data.msg);
}
},
error: function(error) {
alert(error.toString());
/*jQuery('.askQuestion').empty().removeClass('ajax').text('error: ' + error.toString());*/
}
});
}
};
jQuery('#askQuestionForm').appendTo(jQuery('body'));
jQuery('.askQuestion a.singUp').bind('click',function(e){
e.preventDefault();
self.openPopup();
});
jQuery('#askQuestionForm a.btn_popupClose').bind('click',function(e){
e.preventDefault();
self.closePopup();
});
jQuery('#askQuestionForm .send input').bind('click',function(e){
e.preventDefault();
self.submitForm();
});
}
function initClassProduct()
{
jQuery('.minus').bind('click', minusProduct);
jQuery('.plus').bind('click', plusProduct);
jQuery('.amount_field').bind('blur', testField);
if (!productDetailArray || !hasID || productDetailArray[0].result == 0) {
jQuery('.btnTag.singUp.btn_updateCart').hide();
jQuery('.amount_field').val(1);
} else {
jQuery('.btnTag.singUp.btn_addToCart').hide();
jQuery('.amount_field').val(productDetailArray[0].qty);
// console.log(productDetailArray[0].qty);
}
jQuery('.btnTag.singUp').bind('click', function(){
var isUpdate = jQuery(this).hasClass('btn_updateCart') ? true : false;
//console.log(productDetailArray[0].item_id);
membershipPopup.init('Classes');
//classAdd(isUpdate,myItemID,jQuery('.amount_field').val());
});
jQuery('.askQuestion').removeClass('ajax');
}
});
}
function checkMobile() {
var pda_user_agent_list = new Array("2.0 MMP", "240320", "AvantGo", "BlackBerry", "Blazer", "Cellphone", "Danger", "DoCoMo", "Elaine/3.0", "EudoraWeb", "hiptop", "IEMobile", "KYOCERA/WX310K", "LG/U990", "MIDP-2.0", "MMEF20", "MOT-V", "NetFront", "Newt", "Nintendo Wii", "Nitro", "Nokia", "Opera Mini", "Opera Mobi", "Palm", "Playstation Portable", "portalmmm", "Proxinet", "ProxiNet", "SHARP-TQ-GX10", "Small", "SonyEricsson", "Symbian OS", "SymbianOS", "TS21i-10", "UP.Browser", "UP.Link", "Windows CE", "WinWAP", "Android", "iPhone", "iPod", "iPad", "Windows Phone", "HTC"/*, "GTB"*/);
var pda_app_name_list = new Array("Microsoft Pocket Internet Explorer");
var user_agent = navigator.userAgent.toString();
for (var i = 0; i < pda_user_agent_list.length; i++) {
if (user_agent.indexOf(pda_user_agent_list[i]) >= 0) {
return true;
}
}
var appName = navigator.appName.toString();
for (var i = 0; i < pda_app_name_list.length; i++) {
if (user_agent.indexOf(pda_app_name_list[i]) >= 0) {
return true;
}
}
return false;
}
function checkIE8() {
BrowserDetect.init();
if (BrowserDetect.browser == "Explorer" && BrowserDetect.version < 9) {
//console.log('isIE8');
return true;
} else
return false;
}
function checkMobile() {
var pda_user_agent_list = new Array("2.0 MMP", "240320", "AvantGo", "BlackBerry", "Blazer", "Cellphone", "Danger", "DoCoMo", "Elaine/3.0", "EudoraWeb", "hiptop", "IEMobile", "KYOCERA/WX310K", "LG/U990", "MIDP-2.0", "MMEF20", "MOT-V", "NetFront", "Newt", "Nintendo Wii", "Nitro", "Nokia", "Opera Mini", "Opera Mobi", "Palm", "Playstation Portable", "portalmmm", "Proxinet", "ProxiNet", "SHARP-TQ-GX10", "Small", "SonyEricsson", "Symbian OS", "SymbianOS", "TS21i-10", "UP.Browser", "UP.Link", "Windows CE", "WinWAP", "Android", "iPhone", "iPod", "iPad", "Windows Phone", "HTC"/*, "GTB"*/);
var pda_app_name_list = new Array("Microsoft Pocket Internet Explorer");
var user_agent = navigator.userAgent.toString();
for (var i = 0; i < pda_user_agent_list.length; i++) {
if (user_agent.indexOf(pda_user_agent_list[i]) >= 0) {
return true;
}
}
var appName = navigator.appName.toString();
for (var i = 0; i < pda_app_name_list.length; i++) {
if (user_agent.indexOf(pda_app_name_list[i]) >= 0) {
return true;
}
}
return false;
}
var BrowserDetect = {
init : function() {
this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version";
this.OS = this.searchString(this.dataOS) || "an unknown OS";
},
searchString : function(data) {
for (var i = 0; i < data.length; i++) {
var dataString = data[i].string;
var dataProp = data[i].prop;
this.versionSearchString = data[i].versionSearch || data[i].identity;
if (dataString) {
if (dataString.indexOf(data[i].subString) != -1)
return data[i].identity;
} else if (dataProp)
return data[i].identity;
}
},
searchVersion : function(dataString) {
var index = dataString.indexOf(this.versionSearchString);
if (index == -1)
return;
return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
},
dataBrowser : [{
string : navigator.userAgent,
subString : "Chrome",
identity : "Chrome"
}, {
string : navigator.userAgent,
subString : "OmniWeb",
versionSearch : "OmniWeb/",
identity : "OmniWeb"
}, {
string : navigator.vendor,
subString : "Apple",
identity : "Safari",
versionSearch : "Version"
}, {
prop : window.opera,
identity : "Opera",
versionSearch : "Version"
}, {
string : navigator.vendor,
subString : "iCab",
identity : "iCab"
}, {
string : navigator.vendor,
subString : "KDE",
identity : "Konqueror"
}, {
string : navigator.userAgent,
subString : "Firefox",
identity : "Firefox"
}, {
string : navigator.vendor,
subString : "Camino",
identity : "Camino"
}, {// for newer Netscapes (6+)
string : navigator.userAgent,
subString : "Netscape",
identity : "Netscape"
}, {
string : navigator.userAgent,
subString : "MSIE",
identity : "Explorer",
versionSearch : "MSIE"
}, {
string : navigator.userAgent,
subString : "Gecko",
identity : "Mozilla",
versionSearch : "rv"
}, {// for older Netscapes (4-)
string : navigator.userAgent,
subString : "Mozilla",
identity : "Netscape",
versionSearch : "Mozilla"
}],
dataOS : [{
string : navigator.platform,
subString : "Win",
identity : "Windows"
}, {
string : navigator.platform,
subString : "Mac",
identity : "Mac"
}, {
string : navigator.userAgent,
subString : "iPhone",
identity : "iPhone/iPod"
}, {
string : navigator.platform,
subString : "Linux",
identity : "Linux"
}]
};
var belowIE8 = checkIE8();
function initSitemap() {
jQuery(document).ready(function() {
var storePath = domainName + '/dcapi/category/list.php';
var myData = JSON.stringify({
"storeViewId" : storeViewId
});
jQuery('#mainContent').addClass('ajax');
jQuery.ajax({
url : storePath,
type : 'post',
dataType : 'json',
contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
processData : true,
crossDomain : true,
data : myData,
timeout : timeOutCount,
success : function(data, status, req) {
var myUL = jQuery('<ul class="secondLvUL"></ul>').appendTo(jQuery('.firstLvLI').eq(4));
for ( i = 0; i < data[0].category_list.length; i++) {
var myName = data[0].category_list[i][0].name;
var myURLKEY = data[0].category_list[i][0].url_key;
var myLI = jQuery('<li class="secondLvLI"></li>').appendTo(myUL);
jQuery('<a title="All Events" href="/E-Shop/Product-Listing#!/Category/' + myURLKEY + '" class="secondLvLink">' + myName + '</a>').appendTo(myLI);
}
},
error : function(error) {
jQuery('#mainContent').removeClass('ajax');
jQuery('<div class="displayMsg">Cannot get product information, Please try again later.</div>').appendTo("#mainContent").fadeIn();
}
})
})
}
jQuery(document).ready(function(e) {
if (jQuery('.jobOpportunityList').length > 0) {
expandCollapse('.jobList .item a', '.jobDetail');
var myHash = window.location.hash.replace('#','');
if(myHash != "")
{
jQuery('.jobList .item.anchor_'+myHash+' a').addClass('active');
jQuery('.jobList .item.anchor_'+myHash+' a').parent().parent().addClass('active');
jQuery('.jobList .item.anchor_'+myHash+' a').parent().find('.jobDetail').show();
jQuery('body,html').scrollTop(jQuery('.jobList .item.anchor_'+myHash).offset().top);
}
}
});
function getProductBySku(skuString, callback) {
var postData;
var productDetailsArrPath = domainName + '/dcapi/productlist/product_list_by_skus.php'
if (jQuery.cookie('cookies_myCartID')) {
postData = JSON.stringify({
"storeViewId" : storeViewId,
"skus" : skuString,
"cartId" : myCartID
});
} else {
postData = JSON.stringify({
"storeViewId" : storeViewId,
"skus" : skuString
});
}
// console.log(postData);
jQuery.ajax({
url : productDetailsArrPath,
type : 'post',
dataType : 'json',
contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
processData : true,
crossDomain : true,
data : postData,
timeout : timeOutCount,
success : function(data, status, req) {
if ( typeof callback === "function") {
callback(data);
}
},
error : function(error) {
//alert(error);
}
});
}
function getProductByCatergory(catname, callback,errorCallback) {
var postData = JSON.stringify({
"storeViewId" : storeViewId,
"category_key" : catname,
"record_per_page" : 999,
"page_no" : 1
});
var productListPath = domainName + '/dcapi/productlist/product_list_by_category.php';
// console.log(postData);
jQuery.ajax({
url : productListPath,
type : 'post',
dataType : 'json',
contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
processData : true,
crossDomain : true,
data : postData,
timeout : timeOutCount,
success : function(data, status, req) {
if ( typeof callback === "function") {
callback(data);
}
},
error : function(error) {
//alert(error);
}
});
}
function expandCollapse(trigger, content) {
jQuery(document).ready(function() {
jQuery(trigger).each(function(i) {
jQuery(this).on('click', function() {
if (jQuery(this).hasClass('active')) {
jQuery(this).removeClass('active');
jQuery(this).parent().find(content).stop().slideUp(function() {
jQuery(this).parent().parent().removeClass('active');
});
} else {
jQuery(this).addClass('active');
jQuery(this).parent().parent().addClass('active');
jQuery(this).parent().find(content).stop().slideDown();
}
});
});
});
}
var imageGallery = function(container,jsonData){
var self = this;
self.container = jQuery(container);
self.json = jsonData;
self.init = function(){
var i = 0;
var idx = 0;
jQuery.map(mediaAlbumJson.data, function(item){
var isImg = item.type == "image" ? true: false;
var img = jQuery("<img/>").attr("src", isImg? item.image: item.videoThumbnail);
var thumb = jQuery("<a class='thumb' href='javascript:;'></a>");
var frameborder = jQuery("<div class='frame-border'/>");
thumb.data("obj", item);
thumb.data("idx", idx++);
thumb.append(img);
thumb.append(frameborder);
if(!isImg){
var videoLabel = jQuery("<div class='video-label'></div>");
thumb.append(videoLabel);
}
jQuery(container).find(".nav").append(thumb);
})
jQuery(container).find(".thumb").on("click", function(){
var that = jQuery(this);
var obj = that.data("obj");
var idx = that.data("idx");
var isImg = obj.type == "image"? true: false;
var display;
if(isImg){
display = jQuery("<img/>").attr("src", obj.image);
jQuery(container).find(".desc").empty().append(obj.imageDescription);
}else{
display = jQuery('<iframe id="ytplayer" type="text/html" width="100%" height="500" src="https://www.youtube.com/embed/'+obj.videoID+'" frameborder="0"/>');
jQuery(container).find(".desc").empty().append(obj.videoDescription);
}
jQuery(container).find(".display").empty().append(display);
that.siblings().find(".frame-border").removeClass("active");
that.find(".frame-border").addClass("active");
// animate nav bar
var containerWidth = jQuery(container).find(".display").width();
var navbarWidth = jQuery(container).find(".nav").width();
var itemWidth = that.width();
idx += 1;
if(navbarWidth < containerWidth){
}else if(!(idx*itemWidth -itemWidth/2 < containerWidth/2) && !((navbarWidth - idx*itemWidth - itemWidth/2) < containerWidth /2)){
var left = containerWidth/2 - (itemWidth*idx - itemWidth/2);
jQuery(container).find(".nav").animate({left: left}, 500);
}else if(idx*itemWidth -itemWidth/2 < containerWidth/2){
jQuery(container).find(".nav").animate({left: 0}, 500);
}else if((navbarWidth - idx*itemWidth - itemWidth/2) < containerWidth /2){
jQuery(container).find(".nav").animate({left: containerWidth - navbarWidth}, 500);
}
})
// init
jQuery(container).find(".thumb").eq(0).trigger("click");
};
self.init();
};
var slideMenuSpecialPromo = function() {
var menuSlider = jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .menuContainer .menuSlider');
var menuList = jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .menuContainer .menu');
var item = jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .menuContainer .menu .list .item');
var list = jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .menuContainer .menu .list');
var listNumber = jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .menuContainer .menu .list').length;
var itemNumber = 0;
var listWidth = 0;
var menuToggle = jQuery('.mainContainer.withFeaturedPhoto.specialPromo #contentContainer .menuContainer .menuHolder .toggle');
jQuery(list).each(function(i) {
if (jQuery(this).find('.item').length > itemNumber)
itemNumber = jQuery(this).find('.item').length;
});
//alert(itemNumber);
listWidth = 132 * itemNumber + 5;
jQuery(menuList).css({
'width' : listWidth,
'height' : 264 * listNumber
});
jQuery(menuSlider).css({
'height' : 264 * listNumber + 30
/*'top' : -((264* listNumber +30)/2)*/
});
jQuery(menuToggle).click(function(e) {
e.preventDefault();
if (jQuery(this).hasClass('active')) {
jQuery(this).removeClass('active');
menuList.removeClass('active');
jQuery(menuSlider).stop().animate({
'width' : 27
})
} else {
jQuery(this).addClass('active');
menuList.addClass('active');
jQuery(menuSlider).stop().animate({
'width' : listWidth + 27
});
}
});
};
var contentMiniPopup = function(container,trigger){
var self = this;
self.container = container;
self.trigger = trigger;
self.popup = jQuery(self.container).find('.popup');
self.popupContent = jQuery(self.popup).find('.popupContent > div');
self.popupClose = jQuery(self.popup).find('.closeBtn');
self.init = function(){
jQuery(self.trigger).each(function(i){
var additionClass = jQuery(this).attr('class');
jQuery(this).click(function(e){
if(jQuery(self.popup).is(':visible'))
{
jQuery(self.popup).stop().fadeOut(function(e){
jQuery(self.popup).attr('class','popup '+additionClass);
jQuery(self.popupContent).hide().eq(i).show();
jQuery(self.popup).fadeIn();
});
}
else
{
jQuery(self.popupContent).hide().eq(i).show();
jQuery(self.popup).attr('class','popup '+additionClass);
jQuery(self.popup).fadeIn();
}
});
});
jQuery(self.popupClose).click(function(e){
jQuery(self.popup).fadeOut();
});
};
self.init();
}
var openGenericPopup = function(contentElem)
{
jQuery('.genericPopup .popup .mid .closeBtn,.genericPopup .popup .mask').unbind('click');
if(jQuery('.mask').length < 1)
jQuery('body').append('<div class="mask"></div>')
if(jQuery('.genericPopup').length < 1)
jQuery('body').append('<div class="genericPopup"><div class="popup"><div class="top"></div><div class="mid"></div><div class="btm"></div></div></div>');
jQuery('.genericPopup .popup .mid').empty();
jQuery(contentElem).clone().appendTo(jQuery('.genericPopup .popup .mid'));
var popupTop = jQuery(window).scrollTop();
jQuery('.genericPopup').css({'top':popupTop})
jQuery('.genericPopup .popup .mid .closeBtn,.genericPopup .popup .mask').click(function(e){
jQuery('.genericPopup,.mask').fadeOut();
});
jQuery('.genericPopup,.mask').fadeIn();
}
var hideHeaderContainer = function()
{
jQuery('#headerContainer').hide();
}
$(document).ready(function() {
if(isMobileApp())
{
$('#headerContainer').hide();
$('#footerContainer').hide();
//$('.magaTitle.magaLogon').parent().hide();
$('.greenExclamationMark').hide();
//for production
$('.productListContainer.responsiveComplonent').remove();
$('body').addClass('mobileApp');
if(window.location.href.indexOf("citysuper/e-magazine") > -1)
{
$('.magaTitle.magaLogon').parent().hide();
}
else if (window.location.href.indexOf("log-on/e-magazine") > -1)
{
$('.magaTitle.magaCitySuper').parent().hide();
}
}
function isMobileApp()
{
var userAgent = navigator.userAgent.toLowerCase();
var citysuper = /citysuper/.test(userAgent);
var ios = /iphone|ipod|ipad/.test( userAgent );
var safari = /safari/.test( userAgent );
var standalone = window.navigator.standalone;
var androidWebview = /version\/[0-9]\.[0-9]/.test( userAgent );
  
//alert("Console log = ", userAgent);
if( citysuper )
{
return true;
}
else if( ios )
{
if( !safari && !standalone )
{
return true;
}
}
else
return false;
}
});
function hardCodeAddArticleBanner()
{
if (jQuery('.articleBannerItem').length == 0) return;
if (jQuery('.articleBannerItem').length == 3) return;
var str = jQuery('.articleBannerWrapper')[0].innerHTML;
if (jQuery('.articleBannerItem').length == 1) {
str += '<div class="articleBannerItem"><img src="/getmedia/d029d95c-17f9-4557-b6b4-a1afbae2495d/logon_thumbnail_2.aspx"></div><div class="articleBannerItem lastItem"><img src="/getmedia/bad0a7d7-28db-401f-b2a8-a363fa22f68c/bookself_img_a.aspx"></div>';
}
if (jQuery('.articleBannerItem').length == 2) {
str += '<div class="articleBannerItem lastItem"><img src="/getmedia/3c968eb0-ee3c-491f-9167-c79e5ea27b8b/citysuper_thumbnail_3.aspx" alt="Cover Story"></div>';
}
/*str += '<div class="articleBannerItem lastItem"><img src="/getmedia/71c2270e-8436-4f20-8cbc-35acbd25a64c/bookself_img_a.aspx" alt="Cover Story"></div>';*/
/*str += '<div class="articleBannerItem"><img src="/getmedia/71c2270e-8436-4f20-8cbc-35acbd25a64c/bookself_img_a.aspx" alt="Cover Story"></div><div class="articleBannerItem lastItem"><img src="/getmedia/874d42d7-b03f-4dfd-afba-32df78a4d2cc/bookself_img_b.aspx" alt="Cover Story"></div>';*/
str = str.replace(/(?:\r\n|\r|\n)/g, '');
jQuery('.articleBannerWrapper').html(str);
}
function initCheckBox()
{
jQuery('.membershipForm input[type~=checkbox]').unbind('click');
jQuery('.membershipForm input[type~=checkbox]').click(function() {
var self = jQuery(this);
if(self.is(':checked')) {
self.addClass('checked');
}
else {
self.removeClass('checked');
}
});
jQuery('.membershipForm input[type~=radio]').unbind('click');
jQuery('.membershipForm input[type~=radio]').click(function() {
var self = jQuery(this);
var name = self.attr('name');
if(self.is(':checked')) {
jQuery('.membershipForm input[name~='+name+']').removeClass('checked');
self.addClass('checked');
}
});
}
function escapeHtml(text) {
var map = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#039;'
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment