", e("body").append(s).addClass("vbox-open"), e(".vbox-preloader .sk-child, .vbox-preloader .sk-rotating-plane, .vbox-preloader .sk-rect, .vbox-preloader .sk-cube, .vbox-preloader .sk-spinner-pulse").css("background-color", $.spinColor), k = e(".vbox-overlay"), c = e(".vbox-container"), r = e(".vbox-content"), a = e(".vbox-num"), (n = e(".vbox-title")).css($.titlePosition, "-1px"), n.css({ color: $.titleColor, "background-color": $.titleBackground }), e(".vbox-close").css({ color: $.closeColor, "background-color": $.closeBackground }), e(".vbox-num").css($.numerationPosition, "-1px"), e(".vbox-num").css({ color: $.numerationColor, "background-color": $.numerationBackground }), e(".vbox-next span, .vbox-prev span").css({ "border-top-color": $.arrowsColor, "border-right-color": $.arrowsColor }), r.html(""), r.css("opacity", "0"), k.css("opacity", "0"), q(), k.animate({ opacity: 1 }, 250, function () { "iframe" == E.data("vbtype") ? te() : "inline" == E.data("vbtype") ? ne() : "ajax" == E.data("vbtype") ? oe() : "video" == E.data("vbtype") || "vimeo" == E.data("vbtype") || "youtube" == E.data("vbtype") ? ae(o) : (r.html(''), ie()), $.cb_post_open(E, O, w, C) }), e("body").keydown(A), e(".vbox-prev").on("click", function () { I(C) }), e(".vbox-next").on("click", function () { I(w) }), !1 }); var Q = ".vbox-overlay"; function S(e) { r.addClass("animated"), U = z = e.pageY, V = R = e.pageX, Y = !0 } function Z(e) { if (!0 === Y) { R = e.pageX, z = e.pageY, j = R - V, T = z - U; var o = Math.abs(j); o > Math.abs(T) && o <= 100 && (e.preventDefault(), r.css("margin-left", j)) } } function G(e) { if (!0 === Y) { Y = !1; var o = E, t = !1; (X = R - V) < 0 && !0 === _ && (o = w, t = !0), X > 0 && !0 === B && (o = C, t = !0), Math.abs(X) >= W && !0 === t ? I(o) : r.css({ "margin-left": 0, "margin-right": 0 }) } } $.overlayClose || (Q = ".vbox-close"), e(document).on("click", Q, function (o) { (e(o.target).is(".vbox-overlay") || e(o.target).is(".vbox-content") || e(o.target).is(".vbox-close") || e(o.target).is(".vbox-preloader")) && H() }), V = 0, R = 0, X = 0, W = 50, Y = !1; var J = { DOWN: "touchmousedown", UP: "touchmouseup", MOVE: "touchmousemove" }, K = function (o) { var t; switch (o.type) { case "mousedown": t = J.DOWN; break; case "mouseup": case "mouseout": t = J.UP; break; case "mousemove": t = J.MOVE; break; default: return }var a = ee(t, o, o.pageX, o.pageY); e(o.target).trigger(a) }, L = function (o) { var t; switch (o.type) { case "touchstart": t = J.DOWN; break; case "touchend": t = J.UP; break; case "touchmove": t = J.MOVE; break; default: return }var a, n = o.originalEvent.touches[0]; a = t == J.UP ? ee(t, o, null, null) : ee(t, o, n.pageX, n.pageY), e(o.target).trigger(a) }, ee = function (o, t, a, n) { return e.Event(o, { pageX: a, pageY: n, originalEvent: t }) }; function oe() { e.ajax({ url: l, cache: !1 }).done(function (e) { r.html('
' + e + "
"), ie() }).fail(function () { r.html('
Error retrieving contents, please retry
'), se() }) } function te() { r.html(''), se() } function ae(e) { var o, t = function (e) { if (e.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/), RegExp.$3.indexOf("youtu") > -1) var o = "youtube"; else if (RegExp.$3.indexOf("vimeo") > -1) var o = "vimeo"; return { type: o, id: RegExp.$6 } }(l), a = (e ? "?rel=0&autoplay=1" : "?rel=0") + function (e) { var o = "", t = decodeURIComponent(e).split("?"); if (void 0 !== t[1]) { var a, n, i = t[1].split("&"); for (n = 0; n < i.length; n++)a = i[n].split("="), o = o + "&" + a[0] + "=" + a[1] } return encodeURI(o) }(l); "vimeo" == t.type ? o = "https://player.vimeo.com/video/" : "youtube" == t.type && (o = "https://www.youtube.com/embed/"), r.html(''), se() } function ne() { r.html('
' + e(l).html() + "
"), se() } function ie() { (N = r.find("img")).length ? N.each(function () { e(this).one("load", function () { se() }) }) : se() } function se() { n.html(x), r.find(">:first-child").addClass("figlio").css({ width: v, height: u, padding: i, background: t }), e("img.figlio").on("dragstart", function (e) { e.preventDefault() }), ce(), r.animate({ opacity: "1" }, "slow", function () { }) } function ce() { var o = r.outerHeight(), t = e(window).height(); f = o + 60 < t ? (t - o) / 2 : "30px", r.css("margin-top", null == $.contentMarginTop ? f : $.contentMarginTop + "px"), r.css("margin-bottom", null == $.contentMarginBottom ? f : $.contentMarginBottom + "px"), null != $.overFlowY && c.css("overflow-y", $.overFlowY), $.cb_post_resize() } "ontouchstart" in window ? (e(document).on("touchstart", L), e(document).on("touchmove", L), e(document).on("touchend", L)) : (e(document).on("mousedown", K), e(document).on("mouseup", K), e(document).on("mouseout", K), e(document).on("mousemove", K)), e(window).resize(function () { e(".vbox-content").length && setTimeout(ce(), 800) }) }) } }) }(jQuery);
// stop hash link jump to on load
// to top right away
if (window.location.hash) scroll(0, 0);
// void some browsers issue
setTimeout(function () { scroll(0, 0); }, 1);
var App = function () {
var _config = { 'notifDisplayTimeout': 8000, 'uidHash' : '' };
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
// *only* if we have anchor on the url
if (window.location.hash && $('#' + window.location.hash.replace(/[^a-z0-9A-Z\-\_]*/gi, '')).length > 0) {
// smooth scroll to the anchor id
$('html, body').animate({
scrollTop: $('#' + window.location.hash.replace(/[^a-z0-9A-Z\-\_]*/gi, '')).offset().top - 200 + 'px'
}, 1000, 'swing');
}
$('.fname-round').each(function (i, o) {
var color = nameColorPicker($(o).data('fname'));
$(o).css({ 'background-color': color });
$(o).colourBrightness();
})
// initialize regular image modal
if ($('.venobox-image').length > 0)
$('.venobox-image').venobox({
spinColor: 'deeppink',
cb_pre_open: function (obj) {
$('.vbox-preloader').hide();
App.loader.showLoader();
},
cb_post_open: function (obj, gallIndex, thenext, theprev) {
$('.vbox-preloader').hide();
App.loader.hideLoader();
}
});
// initialize image gallery (set data-gall="GalleryName")
$('.venobox-gallery').venobox({
infinigall: true,
spinColor: 'deeppink',
cb_pre_open: function (obj) {
$('.vbox-preloader').hide();
App.loader.showLoader();
},
cb_post_open: function (obj, gallIndex, thenext, theprev) {
$('.vbox-preloader').hide();
App.loader.hideLoader();
}
});
// for test reset button activation
$('[data-answerResetId]').click(function () {
var type = $(this).data('type');
var id = $(this).data('answerresetid');
var tid = $(this).data('tid');
var market = $(this).data('market');
var surveyTable = $(this).data('surveytable');
App.loader.showLoader();
window.location = '/' + market + '/survey/_resetanswer/' + id + '?type=' + type + '&marketuri=' + encodeURIComponent(market) + '&tid=' + tid + '&surveyTable=' + surveyTable;
})
// initialize full screen video (vimeo or youtube only)
$('.venobox-video').venobox({
framewidth: '100%', // default: ''
frameheight: '100%', // default: ''
titleattr: 'data-title', // default: 'title'
numeratio: false, // default: false
infinigall: false, // default: false
spinner: 'cube-grid',
contentMarginTop: 0,
contentMarginBottom: 0,
overFlowY: 'inherit',
spinColor: 'deeppink',
cb_pre_open: function (obj) {
$('.vbox-preloader').hide();
App.loader.showLoader();
},
cb_post_open: function (obj, gallIndex, thenext, theprev) {
$('.vbox-preloader').hide();
App.loader.hideLoader();
}
});
// enable bootstrap tooltip attributes
$('[data-toggle="tooltip"]').tooltip();
// general body/document click handler
$(document).on('click', function (e) {
var clickover = $(e.target);
// close main menu when clicking the body
var _closed = $("#btn-navbar").hasClass("collapsed");
if (_closed !== true && !clickover.hasClass("navbar-toggle")) {
$('.navbar-collapse').collapse('hide');
}
// close popover when click outside
$('[data-toggle="popover"],[data-original-title]').each(function () {
//the 'is' for buttons that trigger popups
//the 'has' for icons within a button that triggers a popup
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
(($(this).popover('hide').data('bs.popover') || {}).inState || {}).click = false // fix for BS 3.3.6
}
});
});
// Prevent 'Maximum call stack size exceeded' error when showing modal inside another modal
$.fn.modal.Constructor.prototype.enforceFocus = function () { };
/*
Multipurpose confirm dialog using bootstrap modal
Add these attributes to configure the dialog:
- data-click-continue: the function that will be called when clicking continue button. Will pass the element source of the click.
- data-before-open: the function that will be called on dialog initialization. If this function return true, it will continue to load the dialog
- data-title: title of the dialog
- data-message: message of the dialog
- data-text-continue: continue button text, default value is Continue.
- data-text-cancel: cancel button text, default value is Cancel
Bootstrap modal required attributes: data-toggle="modal" data-target="#waveConfirmDialog"
Usage example:
*/
$('#waveConfirmDialog').on('show.bs.modal', function (e) {
var $this = $(this);
var btnContinue = $this.find('button[name=btnContinue]');
var btnCancel = $this.find('button[name=btnCancel]');
var link = $(e.relatedTarget);
// run this function before opening the modal from attribute: data-before-open
var fnOpenStr = link.attr('data-before-open');
if (typeof fnOpenStr != 'undefined' && fnOpenStr != '') {
var fnOpen = App.getFunctionFromString(fnOpenStr);
if (typeof fnOpen === 'function') {
// if function returns true, continue, otherwise dont show the modal
if (!fnOpen(link)) {
e.preventDefault(); // don't show the modal
return;
}
}
}
// Set dialog title and message
// Modal title from attribute: data-title
$this.find('.modal-header-title').html(link.attr('data-title'));
// Modal message from attribute: data-message
$this.find('.modal-body-text').html(link.attr('data-message'));
// Continue button text from attribute: data-text-continue
var txtContinue = link.attr('data-text-continue');
if (typeof txtContinue != 'undefined') btnContinue.html(txtContinue);
// Cancel button text from attribute: data-text-cancel
var txtCancel = link.attr('data-text-cancel');
if (typeof txtCancel != 'undefined') btnCancel.html(txtCancel);
// Set continue button callback function from attribute: data-click-continue
btnContinue.off('click'); // remove previous callback if have
// Note: set 'data-click-continue' attribute with the full name of your function, e.g App.Product._deleteMediaUpload
var fnClick = App.getFunctionFromString(link.attr('data-click-continue'));
if (typeof fnClick === 'function') {
// Pass the clicked element to the callback function
btnContinue.on('click', function () { fnClick(link) });
}
});
// remove button callback on modal close
$('#waveConfirmDialog').on('hidden.bs.modal', function (e) {
var $this = $(this);
var btnContinue = $this.find('button[name=btnContinue]');
btnContinue.off('click');
});
/*
Multipurpose info dialog using bootstrap modal
Add these attributes to configure the dialog:
- data-title: title of the dialog
- data-message: message of the dialog
- data-text-close: close button text, default value is Close
Bootstrap modal required attributes: data-toggle="modal" data-target="#waveInfoDialog"
Usage example:
*/
$('#waveInfoDialog').on('show.bs.modal', function (e) {
var $this = $(this);
var btnClose = $this.find('button[name=btnClose]');
var link = $(e.relatedTarget);
// Set dialog title and message
// Modal title from 'data-title' attribute
$this.find('.modal-header-title').html(link.attr('data-title'));
// Modal message from 'data-message' attribute
$this.find('.modal-body-text').html(link.attr('data-message'));
// Continue button text
var txtClose = link.attr('data-text-close');
if (typeof txtClose != 'undefined') btnClose.html(txtClose);
});
// Owais custom droplist
$(document).on('click', '.btn-select', function (e) {
e.preventDefault();
var ul = $(this).find("ul");
if ($(this).hasClass("active")) {
if (ul.find("li").is(e.target)) {
var target = $(e.target);
target.addClass("selected").siblings().removeClass("selected");
var value = target.html();
$(this).find(".btn-select-input").val(value);
$(this).find(".btn-select-value").html(value);
}
ul.hide();
$(this).removeClass("active");
}
else {
$('.btn-select').not(this).each(function () {
$(this).removeClass("active").find("ul").hide();
});
ul.slideDown(300);
$(this).addClass("active");
}
});
$(document).on('click', function (e) {
var target = $(e.target).closest(".btn-select");
if (!target.length) {
$(".btn-select").removeClass("active").find("ul").hide();
}
});
$(".btn-select").each(function (e) {
var value = $(this).find("ul li.selected").html();
if (value != undefined) {
$(this).find(".btn-select-input").val(value);
$(this).find(".btn-select-value").html(value);
}
});
// form input interactive animation
setTimeout(function () {
$('.form-floating-label input, .form-floating-label textarea').focusin(function () {
$(this).parent().addClass('has-value');
});
$('.form-floating-label input, .form-floating-label textarea').blur(function () {
if (!$(this).val().length > 0) {
$(this).parent().removeClass('has-value');
}
});
}, 300)
//scroll to top assignment
$('[data-toggle="scroll-to-top"]').click(function (e) {
e.preventDefault();
App.scrollToTop();
})
};
var $loaderObj;
var loader = {
showLoader: function () {
$loaderObj = $('
');
parent.addClass('round-user-image40 pos-neg-10');
var color = nameColorPicker(userName);
parent.css({ 'background-color': color });
parent.colourBrightness();
};
var avatarOnError2 = function (obj, userName) {
if (typeof userName[0] === 'undefined') return;
var parent = $(obj).parent();
parent.html('
' + userName[0].toUpperCase() + '
');
var color = App.nameColorPicker(userName);
parent.css({ 'background-color': color });
parent.colourBrightness();
};
var nameColorPicker = function (name) {
var n = 'abcdefghijklmnopqrstuvwxyz'.split('');
var r = name.replace(/\s/ig, '').split('')
.map(function (e) { return n.indexOf(e); }).join('');
var colorWheel = ['f6bf26', '7986cb', '9ccc65', '4fc3f7', '90a4ae', '57bb8a', 'f06292', 'b39ddb', 'ba68c8', '4dd0e1', 'FFCDD2', 'EF9A9A', 'E57373', 'E53935', 'FF8A80', 'FF5252', 'E91E63', 'F8BBD0', 'F48FB1', 'F06292', 'EC407A', 'D81B60', 'C2185B', 'AD1457', '880E4F', 'FF80AB', 'FF4081', 'C51162', 'AA00FF', 'D500F9', 'EA80FC', 'CE93D8', 'BA68C8', '8E24AA', 'B39DDB', '9575CD', '7E57C2', 'B388FF', '7C4DFF', '651FFF', '8C9EFF', '7986CB', '2196F3', 'BBDEFB', '90CAF9', '2196F3', '1976D2', '1565C0', '82B1FF', '448AFF', '03A9F4', 'B3E5FC', '81D4FA', '4FC3F7', '03A9F4', '039BE5', '0277BD', '01579B', 'B2EBF2', '80DEEA', '4DD0E1', '26C6DA', '00ACC1', '80D8FF', '40C4FF', '00B0FF', '0091EA', '00E5FF', '00B8D4', 'B2DFDB', '80CBC4', '009688', '64FFDA', '1DE9B6', '00BFA5', '4CAF50', 'A5D6A7', '388E3C', '69F0AE', '00E676', '00C853', '8BC34A', 'AED581', 'CCFF90', '64DD17', 'E6EE9C', 'F4FF81', 'C6FF00', 'AEEA00', 'FFEB3B', 'FFF59D', 'FFD54F', 'FFA726', 'FFC107', 'FDD835', 'FBC02D', 'FF8F00', 'FFEA00', 'FFD740', 'FFD180', 'FFD600', 'CFD8DC', 'FFB6C1', 'FFC0CB', 'FF69B4', 'CD5C5C', 'F08080', 'FA8072', 'FF6347', 'FFA07A', 'FF8C00', 'FFD700', '20B2AA', '66CDAA', '008B8B', '00CED1', '7B68EE', '6495ED', '1E90FF', '8A2BE2', '9400D3', 'BA55D3', 'DA70D6', '663399', 'DDA0DD', 'BC8F8F', 'F7CA18', 'F4D03F', '2980b9', 'f39c12', 'e67e22'];
var colorIndex = (parseInt(r) < 0 ? parseInt(r) * -1 : parseInt(r)) % colorWheel.length;
var color = '#' + colorWheel[colorIndex];
return color;
};
var fixCommentsUserImage = function (parentElement) {
var parent = typeof parentElement == 'undefined' ? '' : parentElement + ' ';
// Fix user profile pic
$(parent + '.user-profile-img').each(function (i, img) {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
avatarOnError2(img, $(img).data('fname'));
}
});
// Set background for users avatar not globally visible
$(parent + '.user-fname-only').each(function () {
var $this = $(this);
var parent = $this.parent();
var fname = $this.data('name');
//var color = App.nameColorPicker(fname);
parent.css({ 'background-color': '#8650d3' });
parent.colourBrightness();
});
};
// password strenth check
var passwordNotice = function (input, selector, color) {
var $input = $(input);
var $notice = $(selector);
$notice.find('span').css('color', '');
$input.keyup(function () {
var text = $.trim($(this).val());
if(!color)
color = {
good: '#0edb73',
bad: 'red'
};
if (text == null) return;
//$notice.find('span.pass-cap').css('color', text.match(/([A-Z])/g) ? color.good : color.bad); // capital letter
$notice.find('span.pass-small').css('color', text.match(/([a-zA-Z])/gi) ? color.good : color.bad); // small case letters
$notice.find('span.pass-special').css('color', text.match(/([!@#$&*])/g) ? color.good : color.bad); // special char
$notice.find('span.pass-num').css('color', text.match(/([\d])/g) ? color.good : color.bad); // a number
$notice.find('span.pass-len').css('color', text.length > 5 ? color.good : color.bad); // at least 8 chars
})
}
var passwordStrength = function (input, notice, weak, good, strong) {
var $input = $(input);
var $form = $input.parents('form:eq(0)');
var $notice = $(notice);
const changeText = function (el, text, color) {
el.text(text).css('color', color);
};
$input.keyup(function () {
$notice.removeClass('p-weak').removeClass('p-good').removeClass('p-strong');
$notice.addClass('hide');
var text = $.trim($(this).val());
if (text.length == 0) {
$notice.empty();
$form.find('.progress-bar_item-1,.progress-bar_item-2,.progress-bar_item-3').removeClass('active');
return;
}
$notice.removeClass('hide');
if (text.length > 0 && text.length < 8) {
//$notice.addClass('p-weak').html(weak);
$form.find('.progress-bar_item-1').addClass('active');
$form.find('.progress-bar_item-2').removeClass('active');
$form.find('.progress-bar_item-3').removeClass('active');
changeText($notice, weak);
return;
}
if (text.match(/([A-Z])/g) == null ||
text.match(/([a-z])/g) == null ||
text.match(/([!@#$&*])/g) == null ||
text.match(/([\d])/g) == null) {
//$notice.addClass('p-weak').html(weak);
$form.find('.progress-bar_item-1').addClass('active');
$form.find('.progress-bar_item-2').removeClass('active');
$form.find('.progress-bar_item-3').removeClass('active');
changeText($notice, weak);
return;
}
var points = 0;
if (text.match(/([A-Z])/g).length > 1)
points++;
if (text.match(/([!@#$&*])/g).length > 1)
points++;
if (text.match(/([\d])/g).length > 1)
points++;
if (text.length > 10)
points++;
if (points <= 2) {
//$notice.addClass('p-good').html(good);
$form.find('.progress-bar_item-2').addClass('active');
$form.find('.progress-bar_item-3').removeClass('active');
changeText($notice, good);
}
else {
//$notice.addClass('p-strong').html(strong);
$form.find('.progress-bar_item').each(function () {
$(this).addClass('active');
});
changeText($notice, strong);
}
})
}
var resetFormError = function (s) {
// get the form inside we are working - change selector to your form as needed
var $form = $(s);
// get validator object
var $validator = $form.validate();
// get errors that were created using jQuery.validate.unobtrusive
var $errors = $form.find(".field-validation-error span");
// trick unobtrusive to think the elements were succesfully validated
// this removes the validation messages
$errors.each(function () { $validator.settings.success($(this)); })
// clear errors from validation
$validator.resetForm();
}
var dataURItoBlob = function (dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var bb = new Blob([ab], { "type": mimeString });
return bb;
}
var getCurKbSize = function (dataUrl) {
return (dataUrl.length * .75) / 1024
}
var downScaleImage = function(dataUrl, newWidth, ext, imageArguments) {
"use strict";
var image, oldWidth, oldHeight, newHeight, canvas, ctx, newDataUrl, imageType;
// Provide default values
imageType = "image/" + (ext || 'jpeg');
imageArguments = imageArguments || 0.7;
// Create a temporary image so that we can compute the height of the downscaled image.
image = new Image();
image.src = dataUrl;
oldWidth = image.width;
oldHeight = image.height;
newHeight = Math.floor((oldHeight) * newWidth / oldWidth);
// Create a temporary canvas to draw the downscaled image on.
canvas = document.createElement("canvas");
canvas.width = newWidth;
canvas.height = newHeight;
// Draw the downscaled image on the canvas and return the new data URL.
ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, newWidth, newHeight);
newDataUrl = canvas.toDataURL(imageType, imageArguments);
return newDataUrl;
}
var resizeImage = function(dataUrl, ext, maxKb) {
var image = new Image();
image.src = dataUrl;
var oldWidth = image.width;
var curSize = getCurKbSize(dataUrl);
var newDataUrl = dataUrl;
var loop = 1;
while (curSize > maxKb) {
newDataUrl = downScaleImage(newDataUrl, oldWidth * 0.8, ext, 1);
curSize = getCurKbSize(newDataUrl);
var tmp = new Image();
tmp.src = newDataUrl;
oldWidth = tmp.width;
}
return newDataUrl;
}
var toScaledImage = function (obj) { // returns binary image data of scaled image
var cropperData = $(obj).cropper('getCroppedCanvas', { aspectRatio: 1 / 1, width: 1024, height: 1024 });
if (!!!cropperData.toDataURL)
return null;
var cropperDataUrl = cropperData.toDataURL();
var maxKbSize = 500;
var isOrigFileSizeOk = true;
if ((cropperData.toDataURL().length * .75) / 1024 > maxKbSize) {
isOrigFileSizeOk = false;
var curKbSIze = (cropperData.toDataURL().length * .75) / 1024;
var maxRes = 100;
var isStillLarge = true;
while (isStillLarge) {
if (maxRes == 0) break;
maxRes -= 5;
var dim = 750 * (maxRes / 100);
var extension = $(obj).data('ext') == 'png' ? 'png' : 'jpeg';
cropperDataUrl = cropperData.toDataURL("image/" + extension, maxRes / 100);
curKbSIze = (cropperDataUrl.length * .75) / 1024;
isStillLarge = curKbSIze > maxKbSize;
}
}
return cropperDataUrl;
}
var formValidateReset = function (s) {
var form = $(s);
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
}
var notifyTemplate =
'
' +
'
' +
'
' +
'
' +
'' +
'
' +
'
' +
'
{1}
' +
'
{2}
' +
'
' +
'
' +
'' +
'
' +
'
' +
'
' +
'
'
;
var notifyBase = function (type, message, title, placementFrom) {
title = typeof title !== 'undefined' ? title : '';
placementFrom = typeof placementFrom !== 'undefined' ? placementFrom : 'top';
var delay = type == 'tester-info' ? 10000 : type == 'tester-debug' ? 0 : 5000; // allow more reading time for info
var icon = type == 'tester-success' ? 'fa fa-check-circle' : type == 'tester-warning' ? 'fa fa-exclamation-circle' :
type == 'tester-danger' ? 'fa fa-exclamation-triangle' : 'fa fa-info';
var mainClass = type == 'tester-success' ? '366' : type == 'tester-warning' ? '5881' :
type == 'tester-danger' ? '6609' : '1117';
$.notify({
icon: icon,
message: message,
title: title
}, {
type: mainClass,
delay: delay,
mouse_over: 'pause',
offset: { x: 0, y: 0 },
placement: { from: placementFrom, align: 'center' },
template: notifyTemplate,
icon_type: 'class'
});
};
var notify = {
Success: function (message, title, placementFrom) {
notifyBase('tester-success', message, title, placementFrom);
},
Info: function (message, title, placementFrom) {
notifyBase('tester-info', message, title, placementFrom);
},
Warning: function (message, title, placementFrom) {
notifyBase('tester-warning', message, title, placementFrom);
},
Danger: function (message, title, placementFrom) {
notifyBase('tester-danger', message, title, placementFrom);
},
Debug: function (message) {
notifyBase('tester-debug', message, 'DEBUG: ');
}
};
var isNullOrUndefined = function (obj) {
return typeof obj == 'undefined' || obj == null;
}
var fbInvite = function (appId, content, url, data) {
window.location = "https://www.facebook.com/dialog/apprequests?app_id=" + appId + "&message=" + content + "!&redirect_uri=" + encodeURIComponent(url) + "&data=" + data;
}
var getFunctionFromString = function (string) {
var scope = window;
var scopeSplit = string.split('.');
for (i = 0; i < scopeSplit.length - 1; i++) {
scope = scope[scopeSplit[i]];
if (scope == undefined) return;
}
return scope[scopeSplit[scopeSplit.length - 1]];
}
var scrollTo = function (selector, speed) {
$('html, body').animate({
scrollTop: $(selector).offset().top
}, speed);
}
// check if url is a valid youtube link and the video exist
var youtubeVideoExists = function (url, callback) {
var v = null;
if (url != undefined || url != '') {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
v = "https://img.youtube.com/vi/{0}/0.jpg".format(match[2]);
}
}
if (v === null) {
callback(false);
return;
}
var image = new Image();
image.onload = function () {
callback(true);
}
image.onerror = function () {
callback(false);
}
image.src = v;
}
var swipedetect = function (el, callback) {
/* Usage
var el = document.getElementById('mybox');
App.swipedetect(el, function (swipedir) {
// swipedir contains either "none", "left", "right", "top", or "down"
if (swipedir == 'left') // do something
if (swipedir == 'right') // do something
if (swipedir == 'top') // do something
if (swipedir == 'down') // do something
});
*/
var touchsurface = el,
swipedir,
startX,
startY,
distX,
distY,
threshold = 120, //required min distance traveled to be considered swipe
restraint = 100, // maximum distance allowed at the same time in perpendicular direction
allowedTime = 250, // maximum time allowed to travel that distance
elapsedTime,
startTime,
handleswipe = callback || function (swipedir) { }
touchsurface.addEventListener('touchstart', function (e) {
var touchobj = e.changedTouches[0]
swipedir = 'none'
dist = 0
startX = touchobj.pageX
startY = touchobj.pageY
startTime = new Date().getTime() // record time when finger first makes contact with surface
e.preventDefault()
}, false)
touchsurface.addEventListener('touchmove', function (e) {
e.preventDefault() // prevent scrolling when inside DIV
}, false)
touchsurface.addEventListener('touchend', function (e) {
var touchobj = e.changedTouches[0]
distX = touchobj.pageX - startX // get horizontal dist traveled by finger while in contact with surface
distY = touchobj.pageY - startY // get vertical dist traveled by finger while in contact with surface
elapsedTime = new Date().getTime() - startTime // get time elapsed
if (elapsedTime <= allowedTime) { // first condition for awipe met
if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint) { // 2nd condition for horizontal swipe met
swipedir = (distX < 0) ? 'left' : 'right' // if dist traveled is negative, it indicates left swipe
}
else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint) { // 2nd condition for vertical swipe met
swipedir = (distY < 0) ? 'up' : 'down' // if dist traveled is negative, it indicates up swipe
}
}
handleswipe(swipedir)
e.preventDefault()
}, false)
}
var titleCase = function (str) {
str = str.trim();
if (str.length == 0) return str;
words = str.toLowerCase().split(' ');
for (var i = 0; i < words.length; i++) {
var letters = words[i].split('');
letters[0] = letters[0].toUpperCase();
words[i] = letters.join('');
}
return words.join(' ');
}
// Format date to: dd/MM/yyyy
var formatDate = function (date) {
var d = new Date(date),
month = ("0" + d.getMonth()).slice(-2),
day = ("0" + d.getDate()).slice(-2),
year = d.getFullYear();
return [day, month, year].join('/');
}
/* Cookie Handling */
//#region Cookie handling
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
//#endregion
/*
function guid() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
}
*/
// the above guid function cause issue on safari 6
function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function inlineSuccessAlert(selector,message, placement) {
var $obj = $(selector);
var id = 'success_' + guid().replace(/\-/gi, '');
var $messageBox = $('', {
class: 'alert alert-success',
style: 'background-color: #fff; padding: 5px 8px; margin-left: auto; margin-right: auto; text-align:center; margin-top: 20px;clear: both',
id: id,
html: message
});
if (placement == App.placement.prepend)
$obj.prepend($messageBox);
if (placement == App.placement.before)
$obj.before($messageBox);
if (placement == App.placement.after)
$obj.after($messageBox);
else
$obj.append($messageBox);
setTimeout(function () { $messageBox.fadeOut(500, function () { $messageBox.remove(); }) }, 10 * 1000);
}
function loadSurveyQuestionTextClone() {
$(document).on('scroll resize', function () {
if (!$('.question-text-parent:not(.stop-float) > h6:visible').isInViewport()) {
var $box = $('', {
class: 'question-text-clone'
});
var $container = $('', { class: 'container' });
var $clone = $('.question-text-parent:visible').clone();
var maxCharToShow = 200;
if ($clone.find('h6').text().length > maxCharToShow) { // don't float header if it's too long, covers the whole mobile screen
$('.question-text-parent:visible').addClass('stop-float');
return;
}
$clone
.removeClass('question-text-parent')
.removeClass('nopadding')
.addClass('padding-t10')
.addClass('padding-b10')
.addClass('text-size-14')
.addClass('floating-text')
.addClass('body-padding-l');
$container.append($clone);
if ($('tr.toptions.tstriped').is(':visible')) {
var $rowData = $('tr.toptions.tstriped:visible').eq(0).clone();
var $table = $('
`;
eParent.append(template);
$compile(eParent.contents())(scope);
}
}
})
});
}
};
})
App.angular.directive('imageonload', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.bind('load', function () {
//call the function that was passed
scope.$apply(attrs.imageonload);
});
}
};
})
App.angular.directive('imageonerror', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.bind('error', function () {
//call the function that was passed
scope.$apply(attrs.imageonload);
});
}
};
})
App.angular.directive('onEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.onEnter);
});
event.preventDefault();
}
});
};
});
App.angular.factory('ScopeStorage', function ($rootScope) {
var mem = {};
return {
store: function (key, value) {
mem[key] = value;
},
get: function (key) {
return mem[key];
}
};
});
App.angular.directive('numbersOnly', function () { // only allow number to be typed in textbox
return {
require: 'ngModel',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
// this next if is necessary for when using ng-required on your input.
// In such cases, when a letter is typed first, this parser will be called
// again, and the 2nd time, the value will be undefined
if (inputValue == undefined) return '';
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
App.angular.directive('convertToNumber', function () { // apply to select whose model are int, use ngRepeat instead of ngOptions
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$parsers.push(function (val) {
return val != null ? parseInt(val, 10) : null;
});
ngModel.$formatters.push(function (val) {
return val != null ? '' + val : null;
});
}
};
});
App.angular.filter('unsafe', function ($sce) { return $sce.trustAsHtml; });
// place here any global angular accessible function
var customServices = angular.module('customServices', [])
.service('unitOfWork', function () {
this.util = function () {
var resetFormError = function (s) { // hides all form validation notice
// get the form inside we are working - change selector to your form as needed
var $form = $(s);
// get validator object
var $validator = $form.validate();
// get errors that were created using jQuery.validate.unobtrusive
var $errors = $form.find(".field-validation-error span");
// trick unobtrusive to think the elements were succesfully validated
// this removes the validation messages
$errors.each(function () { $validator.settings.success($(this)); })
// clear errors from validation
$validator.resetForm();
}
var formValidateReset = function (s) {
var form = $(s);
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
}
return { resetFormError: resetFormError, formValidateReset: formValidateReset }
}()
});
$(function () {
// Conditional include functions.
// RequiredIf method will be included if jQuery validate plugin exist
if (typeof ($.fn.validate) == "function") {
// RequiredIf validation method
jQuery.validator.addMethod('requiredif', function (value, element, params) {
var $element = $(element);
var dependentvalue = $element.attr("data-val-requiredif-dependentvalue");
var control = $('#' + $element.attr("data-val-requiredif-dependentname"));
var controlType = control.attr('type');
var actualvalue = controlType === 'checkbox' ? control.is(':checked').toString() : control.val();
if (dependentvalue.toLowerCase() === actualvalue.toLowerCase()) {
return value.length > 0;
}
return true;
}, '');
}
});
// check if an element is viewable in viewport or not
$.fn.isInViewport = function (offset) {
if (typeof $(this).offset() == 'undefined') return;
offset = offset || 0; // e.g. floating menu offset
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight() - offset;
var viewportTop = $(window).scrollTop() + offset;
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$.fn.isInViewportPercent = function (offset) {
if (typeof $(this).offset() == 'undefined') return 0;
offset = offset || 0; // e.g. floating menu offset
var viewportHeight = $(window).height();
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight() - offset;
var viewportTop = $(window).scrollTop() + offset;
var viewportBottom = viewportTop + viewportHeight;
var intersect = 0;
if (elementBottom > viewportBottom && viewportBottom > elementTop) {
intersect = viewportBottom - elementTop;
}
else if (viewportBottom > elementBottom && viewportTop > elementTop) {
intersect = elementBottom - viewportTop;
}
else if (viewportBottom >= elementBottom && elementTop >= viewportTop) {
intersect = elementBottom - elementTop;
}
if (intersect > viewportHeight) {
intersect = viewportHeight;
}
return Math.round((intersect / viewportHeight) * 100);
};
// truncate stringwith ellipses
String.prototype.trunc = String.prototype.trunc || function (n) {
return (this.length > n) ? this.substr(0, n - 1) + ' ...' : this;
};
String.prototype.isNullOrEmpty = String.prototype.isNullOrEmpty || function (n) {
return typeof this == 'undefined' || this == null || $.trim(this).length == 0;
};
// convert string to hash
String.prototype.hashCode = function () {
var hash = 0, i, chr, len;
if (this.length === 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
// endswith simulator
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
// startswith simulator
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str) {
return this.slice(0, str.length) == str;
};
}
// string.format simulator
if (!String.prototype.format) {
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
// Remove html on string
if (typeof String.prototype.stripHtml !== 'function') {
String.prototype.stripHtml = function () {
return this.replace(/<(?:.|\n)*?>/gm, '');
}
}
if (typeof Number.prototype.isBetween !== 'function') {
Number.prototype.isBetween = function (min, max, isInclusive) {
if (typeof this == 'undefined' || this == null) false;
if (!!!isInclusive) isInclusive = true;
return isInclusive ? (this > min && this < max) || this == min || this == max : this > min && this < max;
}
}
/* display rating in form of stars */
$.fn.makeStars = function () {
$(this).each(function () {
var rating = $(this).data('rating'),
starNumber = $(this).children().length,
fullStars = Math.floor(rating),
halfStarPerc = (rating - fullStars) * 100;
if (rating > 0) {
$(this).children().each(function (index) {
$(this).addClass('fa-star');
$(this).removeClass('fa-star-open');
return ((index + 1) < fullStars);
});
}
if (halfStarPerc !== 0 && fullStars < starNumber) {
var halfStar = $(this).children(":nth-child(" + parseInt(fullStars + 1, 10) + ")");
$('').width(halfStarPerc + '%').appendTo(halfStar);
}
});
};
$.fn.colourBrightness = function () {
var e, t, n, r, i = this.css("background-color");
if (i.match(/^rgb/)) {
i = i.match(/rgb\(([^)]+)\)/)[1];
i = i.split(/ *, */).map(Number);
e = i[0];
t = i[1];
n = i[2]
} else if ("#" == i[0] && 7 == i.length) {
e = parseInt(i.slice(1, 3), 16);
t = parseInt(i.slice(3, 5), 16);
n = parseInt(i.slice(5, 7), 16)
} else if ("#" == i[0] && 4 == i.length) {
e = parseInt(i[1] + i[1], 16);
t = parseInt(i[2] + i[2], 16);
n = parseInt(i[3] + i[3], 16)
}
r = (e * 299 + t * 587 + n * 114) / 1e3;
r < 125 ? this.removeClass("avatar-light").addClass("avatar-dark") : this.removeClass("avatar-dark").addClass("avatar-light")
};
/*! Inline loader overlay - v1.0.0
Usage: $('#target').loadingOverlay(); // to show inline loader on the #target element
$('#target').loadingOverlay('remove'); // to remove inline loader on the #target element
*/
(function ($) {
'use strict';
var methods = {
init: function (options) {
var opts = $.extend({}, $.fn.loadingOverlay.defaults, options);
var target = $(this).addClass(opts.loadingClass);
var overlay = '
' +
'
' +
'' + opts.loadingText + '' +
'
';
// Don't add duplicate loading-overlay
if (!target.data('loading-overlay')) {
target.prepend($(overlay)).data('loading-overlay', true);
}
return target;
},
remove: function (options) {
var opts = $.extend({}, $.fn.loadingOverlay.defaults, options);
var target = $(this).data('loading-overlay', false);
target.find('.' + opts.overlayClass).detach();
if (target.hasClass(opts.loadingClass)) {
target.removeClass(opts.loadingClass);
} else {
target.find('.' + opts.loadingClass).removeClass(opts.loadingClass);
}
return target;
},
// Expose internal methods to allow stubbing in tests
exposeMethods: function () {
return methods;
}
};
$.fn.loadingOverlay = function (method) {
if (methods[method]) {
return methods[method].apply(
this,
Array.prototype.slice.call(arguments, 1)
);
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.loadingOverlay');
}
};
/* Setup plugin defaults */
$.fn.loadingOverlay.defaults = {
loadingClass: 'loading', // Class added to target while loading
overlayClass: 'loading-overlay', // Class added to overlay (style with CSS)
spinnerClass: 'loaderD-inline', // Class added to loading overlay spinner
iconClass: 'loading-icon', // Class added to loading overlay spinner
textClass: 'loading-text', // Class added to loading overlay spinner
loadingText: '' // Text within loading overlay
};
}(jQuery));
if (typeof App == 'undefined') var App = {};
App.Account = function () { return {} }();
App.Account.Index = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$(function () {
// add scripts here
})
});
};
return { init: init };
}()
App.Account.Unsubscribe = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$(function () {
// add scripts here
})
});
};
return { init: init };
}()
App.Account.Activate = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
var resendEmail = function () {
App.loader.showLoader();
$.post(_config.resendUri, function (d) {
if (d.status == 1) {
App.notify.Success(_config.sucessTxt);
}
App.loader.hideLoader();
})
}
$(function () {
$('#btnResend').click(function () { resendEmail(); })
// add scripts here
if (_config.isResend)
resendEmail();
})
});
};
return { init: init };
}()
App.Account.ValidateCode = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$(function () {
// add scripts here
$('#btnSubmitChangePhone').click(function () {
window.location = _config.joinUri
})
})
});
};
return { init: init };
}()
App.Account.Join = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.phone = _config.phone;
$scope.obj = {
email: _config.email,
onEmailChange: function () {
$scope.obj.email = $.trim($scope.obj.email);
console.log($scope.obj.email)
}
};
angular.element(function () {
$.validator.addMethod('requiredutf8', function (value, element) {
var valid = false;
var $element = $(element);
if ($element.attr('id') == 'FirstName') {
var regUtf8 = new XRegExp('^(\\p{L}|[\\-0-9]){1,}(\\p{L}|[\\-0-9]|\\s){0,}$');
valid = regUtf8.test(value);
}
return valid && value != null;
});
var form = $("#frmJoin");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.adapters.addBool("requiredutf8", "requiredutf8");
$.validator.unobtrusive.adapters.addBool("mandatory", "required");
$.validator.unobtrusive.parse(form);
$('#btnFacebook').click(function () {
App.fireDataLayerEventRoutes('account-join-facebook-', _config.controller + '/' + _config.action, _config.route);
window.location = _config.socialUri
})
$('#btnEmail').click(function () {
App.fireDataLayerEventRoutes('account-join-email-', _config.controller + '/' + _config.action, _config.route);
$('#frmJoin').removeClass('hide');
$(this).remove();
$('html, body').animate({
scrollTop: $("#frmJoin").offset().top
}, 1000);
})
$('#frmJoin').submit(function (e) {
e.preventDefault();
if (!$(this).valid()) { return false; }
if (_config.route && _config.route.toLowerCase() == 'c')
App.fireDatalayerEvent('account-submit-iamin-c', _config.controller + '/' + _config.action, document.title);
else if(_config.route)
App.fireDataLayerEventRoutes('account-submit-email-', _config.controller + '/' + _config.action, _config.route);
$('#CountryCallCode').val($('#country-code-0').val());
$('#frmError').addClass('hide');
App.loader.showLoader();
$.post($(this).attr('action'), $(this).serialize(), function (d) {
App.fireDatalayerEvent('click-account-join-byemail', 'account/join', document.title);
if (d.status == 1) {
window.location = d.redirect;
}
else {
if (typeof grecaptcha != 'undefined' && !_config.hasAuthy && !!grecaptcha)
grecaptcha.reset();
if (typeof d.uri != 'undefined' &&!d.uri.isNullOrEmpty()) {
window.location = d.uri;
return;
}
if (d.message && d.message.length > 0) {
var $error = $('', {
text: d.message
})
$error.attr('id', 'Email-error')
$('[data-valmsg-for="Email"]').addClass('field-validation-error').html($error);
$('#Email').addClass('input-validation-error');
}
else {
$('#FirstName,#Email').val(null);
$('#frmJoin').valid();
}
App.loader.hideLoader();
}
})
return false;
});
$('#lnkGoBack').on('click', function () {
window.history.back();
});
if ($(".pass-text-toggle").length > 0) {
$('.pass-text-toggle').click(function () {
var $icon = $(this).find('i');
var isHidden = $icon.hasClass('fa-eye-slash');
if (isHidden) { // unhide password
$icon.removeClass('fa-eye-slash');
$icon.addClass('fa-eye');
$('#Password').attr('type', 'text');
$('#ConfirmPassword').attr('type', 'text');
return;
}
$icon.removeClass('fa-eye');
$icon.addClass('fa-eye-slash');
$('#MPassword').attr('type', 'password');
$('#MConfirmPassword').attr('type', 'password');
});
App.passwordNotice('#Password', '#passNotice');
}
if ($('#FirstName').length > 0 && $('#FirstName').val().length > 0) // show details if name is populated
$('#btnEmail').click();
})
});
};
return { init: init };
}()
App.Account.Register = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, $timeout, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = { submitClicked: false };
$scope.obj.hasPhoto = false;
$scope.obj.suburbList = _config.indoDistrictList;
$scope.obj.address2List = _config.indoSubDistrictList;
$scope.obj.hasFb = _config.hasFb;
$scope.obj.hasIg = _config.hasIg;
$scope.obj.uploadedPic = _config.uploadedPic;
$scope.obj.hasPhoto = false;
$scope.obj.shareMessage = _config.message;
$scope.obj.showTab = function (selector) {
var $tab = $(selector);
$tab.tab('show');
$('html, body').animate({
scrollTop: $tab.offset().top
}, 500);
}
$scope.obj.addPhotoBox = function () {
if ($scope.obj.hasPhoto) return;
$scope.obj.currentAvatar = $('.photo-holder:eq(0)').data('img');
$('#flePic').click();
}
$scope.obj.addPhoto = function () {
$scope.obj.currentAvatar = $('.photo-holder:eq(0)').data('img');
$('#flePic').click();
}
$scope.obj.deletePhoto = function () {
$('.photo-holder:eq(0)').data("img", '');
$('.photo-holder').css('background-image', 'none');
$("#flePic").val('');
$("#hdnFileName").val('');
$scope.obj.uploadedPic = '';
$scope.obj.hasPhoto = false;
}
var clearRotation = function () {
$('.photo-holder:eq(0)').removeClass('rotate-90').removeClass('rotate-180').removeClass('rotate-270'); // remove rotation
$('#hdnRotate').val('');
}
$scope.obj.rotateElement = function (selector, deg) {
var className = '';
var $obj = $(selector);
var $hdn = $('#hdnRotate');
var current = parseInt($hdn.val());
if (!current || current == null || isNaN(current)) current = 0;
current += deg;
if (current == 360 || current == -360) { current = 0; $hdn.val(0); }
switch (current) {
case -270: case 90: className = 'rotate-90'; break;
case -180: case 180: className = 'rotate-180'; break;
case -90: case 270: className = 'rotate-270'; break;
}
$hdn.val(current);
$obj.removeClass('rotate-90').removeClass('rotate-180').removeClass('rotate-270').addClass(className);
}
$scope.obj.goToTab = function (tab) {
$timeout(function () { $('[href="#' + tab + '"]').click(); })
}
$scope.obj.skipToHome = function () {
App.loader.showLoader();
window.location = "/";
}
$scope.obj.goToNextDelivery = function () {
//$scope.obj.setIdState();
$('#divSuccessInfo').addClass('hide');
$('[href="#delivery"]').click();
$timeout(function () { $('#frmInfo').show(); }, 200);
}
$scope.obj.userState = _config.indoState;
$scope.obj.userSuburb = _config.indoDistrict;
$scope.obj.userAddress2 = _config.indoSubDistrict;
$scope.obj.postcodeAreaListing = [];
$scope.obj.marketSelected = _config.market;
$scope.obj.stateList = _config.stateList;
$scope.obj.dynamicPostCode = function () {
if (!!!$scope.obj.userPostCode || $.trim($scope.obj.userPostCode).length < 4) return;
App.loader.showLoader();
$http.post(_config.getDynamicPcListUri, $.param({ code: $scope.obj.userPostCode, market: $scope.obj.marketSelected }))
.then(function (d) {
if (d.status == 200) { //success
$scope.obj.postcodeAreaListing = d.data;
}
App.loader.hideLoader();
}, function () { App.loader.hideLoader(); })
}
$scope.obj.setLocationByPostCode = function (_data) {
App.loader.showLoader();
$scope.obj.userState = _.find($scope.obj.stateList, function (x) { return $.trim(x.Name).toLowerCase() == $.trim(_data.Province).toLowerCase() }).State; // assign state
$scope.obj.setIdState(function () { // load district list
$scope.obj.userSuburb = _data.District; // assign district
$scope.obj.setIdSuburb(function () { // load subdistrict
$scope.obj.userAddress2 = _data.SubDistrict; // assign subdistrict
$scope.obj.userAddress3 = _data.Area; // assign area
$scope.obj.userPostCode = _data.PostCode; // assign postcode
$scope.obj.postcodeAreaListing = [];
App.loader.hideLoader();
})
})
}
$scope.obj.setIdState = function (callback) {
if (!!!$scope.obj.userState || $scope.obj.userState.length == 0) return;
if (!callback) App.loader.showLoader();
$http.post(_config.getSuburbListUri, $.param({ state: $scope.obj.userState }))
.then(function (d) {
if (d.status == 200 && d.data.status == 1) { //success
$scope.obj.suburbList = d.data.list;
if (callback) callback();
}
if (!callback) App.loader.hideLoader();
}, function () { App.loader.hideLoader(); })
}
$scope.obj.setIdSuburb = function (callback) {
if (!!!$scope.obj.userSuburb || $scope.obj.userSuburb.length == 0) return;
if (!callback) App.loader.showLoader();
$http.post(_config.getAddress2ListUri, $.param({ suburb: $scope.obj.userSuburb }))
.then(function (d) {
if (d.status == 200 && d.data.status == 1) { //success
$scope.obj.address2List = d.data.list;
if (callback) callback();
}
if (!callback) App.loader.hideLoader();
}, function () { App.loader.hideLoader(); })
}
$scope.obj.setSocial = function (u) {
App.loader.showLoader();
window.location = u;
}
//#region share section
$scope.obj.getShareStatus = function (s) {
if (s.Status == null) s.Status = 0;
return _.find(_config.shareStatus, function (x) { return x.key == s.Status });
}
$scope.obj.shareFb = function () {
var uri = _config.shareToFbUri + '&message=' + encodeURIComponent($scope.obj.shareMessage);
App.loader.showLoader();
App.fbFeedDialog(_config.linkToShare, function () {
$http.post(uri)
.then(function (res) {
if (res.status == 200) {
if (res.data.status == 1) {
App.notify.Success(_config.successTxt);
$scope.obj.shareMessage = null;
return;
}
else
App.notify.Warning(res.data.message);
App.loader.hideLoader();
}
})
})
}
$scope.obj.removeFriend = function (s) {
var uri = _config.unsubUri + '&id=' + s.Guid;
App.loader.showLoader();
$http.post(uri)
.then(function (res) {
if (res.status == 200) {
if (res.data.status == 1) {
App.notify.Success(_config.successTxt);
$scope.obj.sharedToFriends = _.reject($scope.obj.sharedToFriends, function (x) { return x.Id == s.Id });
}
else
App.notify.Danger(res.data.message);
App.loader.hideLoader();
}
})
}
$scope.obj.resendEmail = function (s) {
var email = prompt('Please enter email');
if (email == null || email.length == 0)
return;
if (!isStringEmail(email))
return;
App.loader.showLoader();
var uri = _config.resendEmailUri + "?id=" + s.Id + '&e=' + encodeURIComponent(email);
$http.post(uri)
.then(function (res) {
if (res.status == 200) {
if (res.data.status == 1)
App.notify.Success(_config.successTxt)
else
App.notify.Danger(res.data.message);
App.loader.hideLoader();
}
})
}
$scope.obj.showPreview = function () {
// cleanup
$('#contentDiv').remove();
var iframe = document.getElementById('re_contentIframe');
iframe.src = _config.frameUri + "/" + _config.boxId + "?body=" + encodeURIComponent($('#EmailBody').val());
App.loader.showLoader();
iframe.onload = function () {
App.loader.hideLoader();
// adjust iframe height
var frame = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument;
var height = Math.max(frame.document.documentElement.clientHeight, frame.document.documentElement.scrollHeight, frame.document.documentElement.offsetHeight);
document.getElementById('re_contentIframe').style.height = /*height + */'500px';
// show modal
$('#modalEmailBody').modal();
}
}
function hideEmailErr() {
$('#err_recipientsList').addClass('hide');
}
function isStringEmail(email) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(email);
}
//#endregion
var resendEmail = function () {
App.loader.showLoader();
$.post(_config.resendEmailUri, function (d) {
if (d.status == 1) {
App.notify.Success(_config.uploadSuccessTxt);
}
App.loader.hideLoader();
})
}
angular.element(function () {
// add asterisk on required label fields
$('[data-val-required]').parents('.form-group').find('label[for]:eq(0)').addClass('required');
$('[href="#collapse-tab_new1"] .count').text($('#regTab li[role="presentation"]').length);
$('[href="#collapse-tab_new1"] .count').removeClass('hide');
// set all email resend buttons
$('.btn-resend-email-validation').click(function () {
resendEmail();
})
$('#lnkShareEmail').on('click', function (e) {
e.preventDefault();
$('#lnkShareEmail i,#lnkShareFb i').removeClass('active');
$('#divShareFb').addClass('hidden');
$('#divShareEmail').removeClass('hidden');
$('#lnkShareEmail i').addClass('active');
$('.circle_v2.circle-purple-hover').removeClass('active')
$(this).addClass('active');
App.scrollTo('#divShareEmail', 1000);
});
$('#lnkShareFb').on('click', function (e) {
e.preventDefault();
$('#lnkShareEmail i,#lnkShareFb i').removeClass('active');
$('#divShareEmail').addClass('hidden');
$('#divShareFb').removeClass('hidden');
$('#lnkShareFb i').addClass('active');
$('.circle_v2.circle-purple-hover').removeClass('active')
$(this).addClass('active');
App.scrollTo('#divShareFb', 1000);
});
$('#txtFbMessage').on("focus keyup", function (e) {
var keycode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
if (keycode === 9 || !keycode) {
// select
var $this = $(this);
$this.select();
// For Chrome's bug
$this.on("mouseup", function () {
// Unbindl mouseup
$this.off("mouseup");
return false;
});
}
});
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
//$('html, body').animate({
// scrollTop: $("#" + (e.target.hash.replace('#',''))).offset().top
//}, 1000);
$('#regTab li').removeClass('active');
$('.xs-tab-item a span').removeClass('tab-selected');
$('li[role="presentation"] [href="' + e.target.hash + '"]').parent().addClass('active');
$('.xs-tab-item a[href="' + e.target.hash + '"] span').addClass('tab-selected');
$('[href="#collapse-tab_new1"] .text').text($('.xs-tab-item a[href="' + e.target.hash + '"] span').text());
// hide xs tab list
$('#collapse-tab_new1').addClass('collapsing').removeClass('collapse in').attr('aria-expanded', 'false');
// scroll to tab nav on select
App.scrollTo('#regTab', 300);
})
// add scripts here
$.validator.addMethod('passwordpattern', function (value, element) {
var valid = false;
var $element = $(element);
if ($element.attr('id') == 'MemberInfo_Password') {
var regPass = App.passwordRegex();
valid = regPass.test(value);
}
return valid && value != null;
});
$.validator.addMethod('requiredutf8', function (value, element) {
var valid = false;
var $element = $(element);
if ($element.attr('id') == 'MemberInfo_FirstName' || $element.attr('id') == 'MemberInfo_LastName') {
var regUtf8 = new XRegExp('^(\\p{L}|[\\-0-9]){1,}(\\p{L}|[\\-0-9]|\\s){0,}$');
valid = regUtf8.test(value);
}
return valid && value != null;
});
$.validator.unobtrusive.adapters.add("mandatory", function (options) {
options.rules["required"] = true;
if (options.message) {
options.messages["required"] = options.message;
}
});
var form = $("#frmInfo");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.adapters.addBool("requiredutf8", "requiredutf8");
$.validator.unobtrusive.adapters.addBool("mandatory", "required");
$.validator.unobtrusive.adapters.addBool("passwordpattern", "passwordpattern");
$.validator.unobtrusive.adapters.add("checkbox", function (options) {
if (options.element.tagName.toUpperCase() === "INPUT" && options.element.type.toUpperCase() === "CHECKBOX") {
options.rules["required"] = true;
if ($.trim(options.message).length == 0) {
options.messages["required"] = $(options.element).attr('id') == "MemberInfo_Agree" ? _config.agreementText : _config.plsSpecifyText;//options.message;
}
}
});
$.validator.unobtrusive.parse(form);
App.formValidateReset('#frmDelivery');
App.formValidateReset('#frmShare');
//#region Share section
$('#frmShare').submit(function (e) {
e.preventDefault();
if (!$(this).valid()) return false;
var emailList = $("#txtEmails").tagsinput('items');
if (_.filter(emailList, function (x) { return x.toLowerCase() == _config.myEmail.toLowerCase() }).length > 0) {
App.notify.Warning(_config.notOwnEmailNoticeTxt)
return false;
}
if (_.filter(emailList, function (x) { return !isStringEmail(x) }).length > 0) {
App.notify.Warning(_config.onlyValidEmailNoticeTxt)
return false;
}
App.loader.showLoader();
$http.post($(this).attr('action'), $(this).serialize())
.then(
function (r) {
if (r.status == 200 && r.data.status == 1) {
$http.post(_config.getSharedFriendsUri)
.then(function (res) {
if (res.status == 200) {
$scope.obj.sharedToFriends = res.data;
$scope.obj.submitClicked = true;
$('#txtEmails').val('');
App.loader.hideLoader();
}
})
}
else
App.loader.hideLoader();
}
)
})
$('#frmFbShare').submit(function (e) {
e.preventDefault();
})
$('#txtEmails')
.on('beforeItemAdd', function (event) {
$('.bootstrap-tagsinput input:eq(0)').css('width', '100%');
}).on('itemAdded', function (event) {
if (!isStringEmail(event.item))
return;
hideEmailErr();
}).on('itemRemoved', function (event) {
if (!isStringEmail(event.item))
return;
});
$('#txtEmails').tagsinput({
tagClass: function (item) {
return (isStringEmail(item) ? 'label-info' : 'label-danger');
},
trimValue: true,
confirmKeys: [13, 188, 44, 32]
});
//#endregion
$('#MemberInfo_State').change(function () {
var val = $(this).val();
$('#drpState').val(val);
})
$("#chkShowPass").change(function () {
var isChecked = $("#chkShowPass").prop('checked');
var selector = '#MemberInfo_Password,#MemberInfo_ConfirmPassword';
if (isChecked)
$(selector).attr('type', 'text');
else
$(selector).attr('type', 'password');
})
$('#frmInfo').submit(function () {
if (!$(this).valid()) return;
App.loader.showLoader();
App.fireDataLayerEventRoutes('account-submit-particulars-', _config.controller + '/' + _config.action, 'A');
var formData = new FormData(document.getElementById('frmInfo'));
$scope.obj.isUploading = true;
$.ajax({
url: $(this).attr('action'),
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function (d) {
App.fireDatalayerEvent('submit-account-register-registryinfo', 'account/register', document.title);
$timeout(function () {
$scope.obj.isUploading = false;
$('.upload-progress-box .upload-progress').css('width', '')
if (d.status == 1) {
window.location = _config.registerUri;
}
else {
App.notify.Danger(d.message);
App.loader.hideLoader();
}
})
},
error: function () {
App.loader.hideLoader();
}
});
return false;
})
$('#frmDelivery').submit(function (e) {
if (!$(this).valid() || $(this).find('button:visible').length == 0) return false;
App.fireDataLayerEventRoutes('account-submit-delivery-', _config.controller + '/' + _config.action, 'A');
App.loader.showLoader();
$.post($(this).attr('action'), $(this).serialize(), function (d) {
App.fireDatalayerEvent('submit-account-register-deliveryinfo', 'account/register', document.title);
if (d.status == 1) window.location = _config.registerUri;
else {
App.notify.Danger(d.message);
App.loader.hideLoader();
}
})
return false;
})
$('#frmAvatar').submit(function (e) {
e.preventDefault();
App.loader.showLoader();
var formData = new FormData(document.getElementById('frmAvatar'));
if ($('#flePic').val().length > 0)
formData.append('file', App.dataURItoBlob($('.photo-holder:eq(0)').data('img')));
formData.append('name', $('#hdnFileName').val());
formData.append('rotation', $('#hdnRotate').val());
$scope.obj.isUploading = true;
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log(percentComplete);
$('.upload-progress-box').show();
$('.upload-progress-box .upload-progress').css('width', percentComplete + '%');
if (percentComplete === 100) {
$('.upload-progress-box').hide();
$('.upload-progress-box .upload-progress').css('width', '0px');
}
}
}, false);
return xhr;
},
url: $(this).attr('action'),
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function (d) {
$scope.obj.isUploading = false;
$('.upload-progress-box .upload-progress').css('width', '')
if (d.status == 1) {
if ($('#flePic').val().length > 0)
$('#main_menu .username + img.round-user-image100').attr('src', $('.photo-holder:eq(0)').data('img'));
else
$('#main_menu .username + img.round-user-image100').removeAttr('src');
$("#flePic").val('');
$("#hdnFileName").val('');
$scope.obj.uploadedPic = null;
$scope.obj.hasPhoto = false;
$('#btnAddPhoto').hide();
App.inlineSuccessAlert('#frmAvatar .circle_v2:eq(0)', _config.uploadSuccessTxt, App.placement.after);
$scope.$apply();
clearRotation();
}
else {
App.notify.Danger(d.message)
}
App.loader.hideLoader();
},
error: function () {
App.loader.hideLoader();
}
});
})
$("#flePic").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
var frag = this.files[0].name.split('.');
var ext = frag[frag.length - 1];
App.loader.showLoader();
reader.onload = function (e) {
var scaled = App.resizeImage(e.target.result, ext == 'jpg' ? 'jpeg' : ext, 200);
var image = scaled == 'data:,' ? e.target.result : scaled;
App.loader.hideLoader();
$scope.obj.hasPhoto = true;
$scope.$apply();
angular.element(function () {
clearRotation();
$('.photo-holder:eq(0)').data('img', image);
$('.photo-holder:eq(0)').css('background-image', 'url(' + (image) + ')');
})
}
reader.readAsDataURL(this.files[0]);
$("#hdnFileName").val(this.files[0].name);
}
});
// password toggle
$('.pass-text-toggle').click(function () {
var $icon = $(this).find('i');
var isHidden = $icon.hasClass('fa-eye-slash');
if (isHidden) { // unhide password
$icon.removeClass('fa-eye-slash');
$icon.addClass('fa-eye');
$('#MemberInfo_Password').attr('type', 'text');
$('#MemberInfo_ConfirmPassword').attr('type', 'text');
return;
}
$icon.removeClass('fa-eye');
$icon.addClass('fa-eye-slash');
$('#MemberInfo_Password').attr('type', 'password');
$('#MemberInfo_ConfirmPassword').attr('type', 'password');
})
App.passwordNotice('#MemberInfo_Password', '#passNotice');
// show error if exists
if ($('#lnkWarning').length > 0) $('#lnkWarning').click();
// tab selection on load
if (_config.isLoggedIn) {
if (_config.isFromFbShareFeed) {
$('[href="#socials"]').attr("data-toggle", "tab");
$scope.obj.goToTab('last');
$('#lnkShareFb').click();
App.inlineSuccessAlert('#divTextMessage', _config.successFbFeed, App.placement.after);
return;
}
if (!_config.userState || $.trim(_config.userState).length == 0) {
// insert complete pixel
if ($.trim(_config.src).length > 0) {
var pxReg = App.readCookie(_config.pxRegister + _config.src);
if (pxReg == null || $.trim(pxReg).length == 0) {
var px = $('#complete_' + _config.src).val();
$('body').append(px);
App.createCookie(_config.pxRegister + _config.src, App.guid(), 1);
}
}
$scope.obj.goToTab('delivery');
return;
}
if (!_config.isProfileRequired || (!!window._surveyObjects.answers && window._surveyObjects.answers.length > 0))
$('[href="#socials"]').attr("data-toggle", "tab");
if (_config.fromSocialConnect && (_config.hasFb || _config.hasIg))
$scope.obj.goToTab('socials');
if (_config.isProfileRequired) {
if (!!window._surveyObjects.answers) {
$('[href="#about"]').attr("data-toggle", "tab");
$scope.obj.goToTab('about');
}
else {
$('[href="#register"]').attr("data-toggle", "tab");
$scope.obj.goToTab('register');
}
}
else if ($('[href="#register"]').length > 0) {
$('[href="#register"]').attr("data-toggle", "tab");
$scope.obj.goToTab('register');
}
}
});
});
};
var submitPhoto = function () {
$('#frmAvatar').submit();
};
return { init: init, submitPhoto: submitPhoto };
}();
App.Account.RegisterB = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, $timeout, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {
submitClicked: false,
delvieryObj: {
hasGlobalLookup: _config.deliveryObj.hasGlobalLookup,
phone: _config.deliveryObj.phone,
userPin: _config.deliveryObj.userPin,
addressMain: _config.deliveryObj.userAddress,
userAddress4: _config.deliveryObj.userAddress4,
userAddress3: _config.deliveryObj.area
},
progressPerc: null
};
$scope.obj.hasPhoto = false;
$scope.obj.suburbList = _config.indoDistrictList;
$scope.obj.address2List = _config.indoSubDistrictList;
$scope.obj.hasFb = _config.hasFb;
$scope.obj.hasIg = _config.hasIg;
$scope.obj.uploadedPic = _config.uploadedPic;
$scope.obj.hasPhoto = false;
$scope.obj.shareMessage = _config.message;
$scope.obj.slideToInfo = function () {
App.fireDataLayerEventRoutes('account-submit-iamin-', _config.controller + '/' + _config.action, 'b');
$('#introSlide').addClass('hide');
$('#infoSlide').removeClass('hide').slideDown();
$scope.obj.progressPerc = 0.0;
angular.element(function () {
App.scrollTo('#infoSlide', 300);
})
};
$scope.obj.nextFinalSLide = function () {
$('#socialSlide').addClass('hide');
$('#finalSlide').removeClass('hide').slideDown();
$scope.obj.progressPerc = 100;
angular.element(function () {
App.scrollTo('#finalSlide', 300);
$('.survey_Qgraph_div').addClass('bar-full');
})
};
$scope.obj.nextDeliverySLide = function () {
var $currentSlide = $('.delivery-slide:visible');
var isLastSlide = $currentSlide.next('.delivery-slide').length === 0;
var $form = $('#frmDeliverySlide');
App.resetFormError('#frmDeliverySlide');
var isCurrentSlideValid = $currentSlide.find('input[name], select[name]').valid();
if (isCurrentSlideValid && isLastSlide) { //submit info and save to DB
if (!$form.valid()) return;
$scope.obj.progressPerc += 10.0;
App.loader.showLoader();
$.post($form.attr('action'), $form.serialize(), function (d) {
App.fireDatalayerEvent('submit-account-register-deliveryinfo', 'account/register', document.title);
App.fireDatalayerEvent('account-submit-address-b', 'account/register', document.title);
if (d.status === 1) {
$('#deliverySlide').addClass('hide');
if (_config.isProfileRequired)
$('#aboutSlide').removeClass('hide').slideDown();
else
$('#socialSlide').removeClass('hide').slideDown();
$scope.$apply(function () {
$scope.obj.progressPerc = 60.0;
App.scrollTo('#aboutSlide:visible,#socialSlide:visible', 300);
})
}
else
console.log('Error');
App.loader.hideLoader();
});
}
else if (isCurrentSlideValid) { // go next
$scope.obj.progressPerc += 10.0;
if ($('.delivery-slide').is(':visible')) {
App.fireDatalayerEvent('account-submit-post-b', _config.controller + '/' + _config.action, document.title);
$scope.obj.delvieryObj.dynamicPostCode(function () {
$currentSlide.addClass('hide');
$currentSlide.next('.delivery-slide').removeClass('hide').slideDown(200);
});
}
else {
$currentSlide.addClass('hide');
$currentSlide.next('.delivery-slide').removeClass('hide').slideDown(200);
}
App.scrollTo('.delivery-slide', 300);
}
};
$scope.obj.nextLideInfoCounter = 0;
$scope.obj.nextInfoSLide = function () {
var $currentSlide = $('.info-slide:visible');
var isLastSlide = $currentSlide.next('.info-slide.hide').length === 0;
var $form = $('#frmInfoSlide');
App.resetFormError('#frmInfoSlide');
var isCurrentSlideValid = $currentSlide.find('input[name], select[name]').valid();
if (isCurrentSlideValid && isLastSlide) { //submit info and save to DB
if (!$form.valid()) return;
App.fireDatalayerEvent('account-submit-agree-b', _config.controller + '/' + _config.action, document.title);
$scope.obj.progressPerc += 5.0;
App.loader.showLoader();
var formData = new FormData(document.getElementById('frmInfoSlide'));
$scope.obj.isUploading = true;
$.ajax({
url: $form.attr('action'),
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function (d) {
App.fireDatalayerEvent('submit-account-register-registryinfo', 'account/register', document.title);
$timeout(function () {
$scope.obj.isUploading = false;
if (d.status === 1) {
$('#infoSlide').addClass('hide');
$('#deliverySlide').removeClass('hide').slideDown();
App.scrollTo('#deliverySlide', 300);
App.loader.hideLoader();
}
else {
App.notify.Danger(d.message);
App.loader.hideLoader();
}
});
},
error: function () {
App.loader.hideLoader();
}
});
}
else if (isCurrentSlideValid) { // go next
var key = $scope.obj.nextLideInfoCounter == 1 ? 'account-submit-gender-b' :
$scope.obj.nextLideInfoCounter == 2 ? 'account-submit-bday-b' :
'account-submit-name-b';
$scope.obj.nextLideInfoCounter ++;
App.fireDatalayerEvent(key, _config.controller + '/' + _config.action, document.title);
$currentSlide.addClass('hide');
$currentSlide.next('.info-slide').removeClass('hide').slideDown(200);
$scope.obj.progressPerc += $scope.obj.progressPerc > 0 ? 5.0 : 15.0;
angular.element(function () {
App.scrollTo('.info-slide:visible', 300);
})
}
};
$scope.obj.showTab = function (selector) {
var $tab = $(selector);
$tab.tab('show');
$('html, body').animate({
scrollTop: $tab.offset().top
}, 500);
}
$scope.obj.addPhotoBox = function () {
if ($scope.obj.hasPhoto) return;
$scope.obj.currentAvatar = $('.photo-holder:eq(0)').data('img');
$('#flePic').click();
}
$scope.obj.addPhoto = function () {
$scope.obj.currentAvatar = $('.photo-holder:eq(0)').data('img');
$('#flePic').click();
}
$scope.obj.deletePhoto = function () {
$('.photo-holder:eq(0)').data("img", '');
$('.photo-holder').css('background-image', 'none');
$("#flePic").val('');
$("#hdnFileName").val('');
$scope.obj.uploadedPic = '';
$scope.obj.hasPhoto = false;
}
var clearRotation = function () {
$('.photo-holder:eq(0)').removeClass('rotate-90').removeClass('rotate-180').removeClass('rotate-270'); // remove rotation
$('#hdnRotate').val('');
}
$scope.obj.rotateElement = function (selector, deg) {
var className = '';
var $obj = $(selector);
var $hdn = $('#hdnRotate');
var current = parseInt($hdn.val());
if (!current || current == null || isNaN(current)) current = 0;
current += deg;
if (current == 360 || current == -360) { current = 0; $hdn.val(0); }
switch (current) {
case -270: case 90: className = 'rotate-90'; break;
case -180: case 180: className = 'rotate-180'; break;
case -90: case 270: className = 'rotate-270'; break;
}
$hdn.val(current);
$obj.removeClass('rotate-90').removeClass('rotate-180').removeClass('rotate-270').addClass(className);
}
$scope.obj.skipToHome = function () {
App.loader.showLoader();
window.location = "/";
}
$scope.obj.goToNextDelivery = function () {
//$scope.obj.setIdState();
$('#divSuccessInfo').addClass('hide');
$('[href="#delivery"]').click();
$timeout(function () { $('#frmInfo').show(); }, 200);
};
$scope.obj.setSocial = function (u) {
App.loader.showLoader();
window.location = u;
};
//#region share section
$scope.obj.getShareStatus = function (s) {
if (s.Status == null) s.Status = 0;
return _.find(_config.shareStatus, function (x) { return x.key == s.Status });
};
$scope.obj.shareFb = function () {
var uri = _config.shareToFbUri + '&message=' + encodeURIComponent($scope.obj.shareMessage);
App.loader.showLoader();
App.fbFeedDialog(_config.linkToShare, function () {
$http.post(uri)
.then(function (res) {
if (res.status == 200) {
if (res.data.status == 1) {
App.notify.Success(_config.successTxt);
$scope.obj.shareMessage = null;
return;
}
else
App.notify.Warning(res.data.message);
App.loader.hideLoader();
}
})
})
}
$scope.obj.removeFriend = function (s) {
var uri = _config.unsubUri + '&id=' + s.Guid;
App.loader.showLoader();
$http.post(uri)
.then(function (res) {
if (res.status == 200) {
if (res.data.status == 1) {
App.notify.Success(_config.successTxt);
$scope.obj.sharedToFriends = _.reject($scope.obj.sharedToFriends, function (x) { return x.Id == s.Id });
}
else
App.notify.Danger(res.data.message);
App.loader.hideLoader();
}
})
}
$scope.obj.resendEmail = function (s) {
var email = prompt('Please enter email');
if (email == null || email.length == 0)
return;
if (!isStringEmail(email))
return;
App.loader.showLoader();
var uri = _config.resendEmailUri + "?id=" + s.Id + '&e=' + encodeURIComponent(email);
$http.post(uri)
.then(function (res) {
if (res.status == 200) {
if (res.data.status == 1)
App.notify.Success(_config.successTxt)
else
App.notify.Danger(res.data.message);
App.loader.hideLoader();
}
})
}
$scope.obj.showPreview = function () {
// cleanup
$('#contentDiv').remove();
var iframe = document.getElementById('re_contentIframe');
iframe.src = _config.frameUri + "/" + _config.boxId + "?body=" + encodeURIComponent($('#EmailBody').val());
App.loader.showLoader();
iframe.onload = function () {
App.loader.hideLoader();
// adjust iframe height
var frame = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument;
var height = Math.max(frame.document.documentElement.clientHeight, frame.document.documentElement.scrollHeight, frame.document.documentElement.offsetHeight);
document.getElementById('re_contentIframe').style.height = /*height + */'500px';
// show modal
$('#modalEmailBody').modal();
}
}
function hideEmailErr() {
$('#err_recipientsList').addClass('hide');
}
function isStringEmail(email) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(email);
}
//#endregion
var resendEmail = function () {
App.loader.showLoader();
$.post(_config.resendEmailUri, function (d) {
if (d.status == 1) {
App.notify.Success(_config.uploadSuccessTxt);
}
App.loader.hideLoader();
});
};
//#region Post code lookup func
$scope.obj.delvieryObj.dynamicFields = _config.deliveryObj.dynamicFields;
$scope.obj.delvieryObj.marketSelected = _config.deliveryObj.market;
$scope.obj.delvieryObj.nameSpace = _config.deliveryObj.nameSpace;
$scope.obj.delvieryObj.showCountryOption = _config.deliveryObj.showCountryOption;
$scope.obj.delvieryObj.hasPostcodeLookup = _config.deliveryObj.hasPostcodeLookup;
$scope.obj.delvieryObj.userState = _config.deliveryObj.state;
$scope.obj.delvieryObj.stateList = _config.deliveryObj.stateList;
$scope.obj.delvieryObj.userSuburb = _config.deliveryObj.indoDistrict;
$scope.obj.delvieryObj.userAddress2 = _config.deliveryObj.indoSubDistrict;
$scope.obj.delvieryObj.hasDynamicSuburb = function () { return _.filter(_config.deliveryObj.dynamicSuburbCountries, function (x) { return x == $scope.obj.delvieryObj.marketSelected }).length > 0; };
$scope.obj.delvieryObj.hasLookupData = function () { return !$.isEmptyObject($scope.obj.delvieryObj.lookupData); };
$scope.obj.delvieryObj.hasReturnedLookup = false;
$scope.obj.delvieryObj.postcodeAreaListing = [];
$scope.obj.delvieryObj.suburbFiltered = function () {
if (!$scope.obj.delvieryObj.dynamicFields.hasNoPost || $scope.obj.delvieryObj.userState == null)
return $scope.obj.delvieryObj.suburbList;
return _.filter($scope.obj.delvieryObj.suburbList, function (s) { return $scope.obj.delvieryObj.userState == s.state });
};
$scope.obj.delvieryObj.canShowInput = function () {
return (!$scope.obj.delvieryObj.hasGlobalLookup || ($scope.obj.delvieryObj.hasGlobalLookup && $scope.obj.delvieryObj.hasReturnedLookup));
};
$scope.obj.delvieryObj.dynamicPostCode = function (callback) {
//if (!$scope.obj.delvieryObj.hasGlobalLookup || !!!$scope.obj.delvieryObj.userPostCode || $.trim($scope.obj.delvieryObj.userPostCode).length < 2) return;
App.loader.showLoader();
$http.post(_config.deliveryObj.getDynamicPcListUri, $.param({ code: $scope.obj.delvieryObj.userPostCode, country: $scope.obj.delvieryObj.marketSelected }))
.then(function (d) {
if (d.status === 200) { //success
$scope.obj.delvieryObj.hasReturnedLookup = true;
$('#btnRegisterDelivery').removeClass('hide');
var data = d.data;
if (data.status === 0) {
$scope.obj.delvieryObj.lookupData = {};
$scope.obj.delvieryObj.stateList = data.states;
$scope.obj.delvieryObj.suburbList = [];
$scope.obj.delvieryObj.address3List = [];
$scope.obj.delvieryObj.address4List = [];
clearLookup();
App.loader.hideLoader();
angular.element(function () {
unitOfWork.util.resetFormError("#frmDeliverySlide");
unitOfWork.util.formValidateReset("#frmDeliverySlide");
if (callback) callback();
});
return;
}
$scope.obj.delvieryObj.lookupData = data;
$scope.obj.delvieryObj.setLookupData(data);
angular.element(function () {
if (callback) callback();
})
}
App.loader.hideLoader();
}, function () { App.loader.hideLoader(); });
};
function clearLookup() {
$scope.obj.delvieryObj.userSuburb = null;
$scope.obj.delvieryObj.userState = null;
$scope.obj.delvieryObj.userAddress3 = null;
$scope.obj.delvieryObj.userAddress4 = null;
$scope.obj.delvieryObj.userStateName = null;
}
var returnLocation = function (x) {
return { state: x.State, text: (x.Eng || '') + ($.trim((x.Local || '')).length > 0 && $.trim((x.Eng || '')).length > 0 ? '-' : '') + (x.Local || ''), val: ($.trim(x.Eng || '').length > 0 ? x.Eng : x.Local) };
};
var firstOrDefault = function (x, k) {
if (!!!x || x == null || x.length == 0) return null;
return x[0][k];
};
$scope.obj.delvieryObj.setLookupData = function (data) {
clearLookup();
$scope.obj.delvieryObj.stateList = data.States;
$scope.obj.delvieryObj.suburbList = _.map(data.Suburbs, returnLocation); //_.pluck(data.Suburbs, 'Eng');
$scope.obj.delvieryObj.address3List = _.map(data.Address3s, returnLocation); //_.pluck(data.Address3s, 'Eng');
$scope.obj.delvieryObj.address4List = _.map(data.Address4s, returnLocation); //_.pluck(data.Address4s, 'Eng');
if ($scope.obj.delvieryObj.stateList.length === 1) {
$scope.obj.delvieryObj.userState = $scope.obj.delvieryObj.stateList[0].State;
$scope.obj.delvieryObj.userStateName = $scope.obj.delvieryObj.stateList[0].Name;
}
if ($scope.obj.delvieryObj.suburbList.length <= 1)
$scope.obj.delvieryObj.userSuburb = firstOrDefault($scope.obj.delvieryObj.suburbList, 'text');
if ($scope.obj.delvieryObj.address3List.length <= 1)
$scope.obj.delvieryObj.userAddress3 = firstOrDefault($scope.obj.delvieryObj.address3List, 'text');
if ($scope.obj.delvieryObj.address4List.length <= 1)
$scope.obj.delvieryObj.userAddress4 = firstOrDefault($scope.obj.delvieryObj.address4List, 'text');
angular.element(function () {
unitOfWork.util.resetFormError("#frmDeliverySlide");
unitOfWork.util.formValidateReset("#frmDeliverySlide");
});
};
//#endregion
angular.element(function () {
//#region Post Lookup
$scope.obj.delvieryObj.userPostCode = _config.deliveryObj.userPostCode;
$scope.obj.delvieryObj.userSuburb = _config.deliveryObj.userSuburb; // assign district
$scope.obj.delvieryObj.userAddress2 = _config.deliveryObj.subDistrict; // assign subdistrict
$scope.obj.delvieryObj.userAddress3 = _config.deliveryObj.area; // assign area
if ($scope.obj.delvieryObj.dynamicFields.hasNoPost) // immediately load details for no postcode with global address
$scope.obj.delvieryObj.dynamicPostCode();
//#endregion
// add asterisk on required label fields
$('[data-val-required]').parents('.form-group').find('label[for]:eq(0)').addClass('required');
$('[href="#collapse-tab_new1"] .count').text($('#regTab li[role="presentation"]').length);
$('[href="#collapse-tab_new1"] .count').removeClass('hide');
// set all email resend buttons
$('.btn-resend-email-validation').click(function () {
resendEmail();
});
$('#cmn-toggle-fb, #cmn-toggle-ig').click(function (e) {
e.preventDefault();
App.fireDatalayerEvent('account-submit-socials-b', _config.controller + '/' + _config.action, document.title);
var lnk = $(this).attr('href');
window.location = lnk;
})
$('#lnkShareEmail').on('click', function (e) {
e.preventDefault();
$('#lnkShareEmail i,#lnkShareFb i').removeClass('active');
$('#divShareFb').addClass('hidden');
$('#divShareEmail').removeClass('hidden');
$('#lnkShareEmail i').addClass('active');
$('.circle_v2.circle-purple-hover').removeClass('active')
$(this).addClass('active');
App.scrollTo('#divShareEmail', 1000);
});
$('#lnkShareFb').on('click', function (e) {
e.preventDefault();
$('#lnkShareEmail i,#lnkShareFb i').removeClass('active');
$('#divShareEmail').addClass('hidden');
$('#divShareFb').removeClass('hidden');
$('#lnkShareFb i').addClass('active');
$('.circle_v2.circle-purple-hover').removeClass('active')
$(this).addClass('active');
App.scrollTo('#divShareFb', 1000);
});
$('#txtFbMessage').on("focus keyup", function (e) {
var keycode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
if (keycode === 9 || !keycode) {
// select
var $this = $(this);
$this.select();
// For Chrome's bug
$this.on("mouseup", function () {
// Unbindl mouseup
$this.off("mouseup");
return false;
});
}
});
// add scripts here
$.validator.addMethod('passwordpattern', function (value, element) {
var valid = false;
var $element = $(element);
if ($element.attr('id') == 'MemberInfo_Password') {
var regPass = App.passwordRegex();
valid = regPass.test(value);
}
return valid && value != null;
});
$.validator.addMethod('requiredutf8', function (value, element) {
var valid = false;
var $element = $(element);
if ($element.attr('id') == 'MemberInfo_FirstName' || $element.attr('id') == 'MemberInfo_LastName') {
var regUtf8 = new XRegExp('^(\\p{L}|[\\-0-9]){1,}(\\p{L}|[\\-0-9]|\\s){0,}$');
valid = regUtf8.test(value);
}
return valid && value != null;
});
$.validator.unobtrusive.adapters.add("mandatory", function (options) {
options.rules["required"] = true;
if (options.message) {
options.messages["required"] = options.message;
}
});
$.validator.unobtrusive.adapters.addBool("requiredutf8", "requiredutf8");
$.validator.unobtrusive.adapters.addBool("mandatory", "required");
$.validator.unobtrusive.adapters.add("checkbox", function (options) {
if (options.element.tagName.toUpperCase() === "INPUT" && options.element.type.toUpperCase() === "CHECKBOX") {
options.rules["required"] = true;
if ($.trim(options.message).length == 0) {
options.messages["required"] = $(options.element).attr('id') == "MemberInfo_Agree" ? _config.agreementText : _config.plsSpecifyText;//options.message;
}
}
});
App.formValidateReset('#frmInfoSlide');
App.formValidateReset('#frmDeliverySlide');
App.formValidateReset('#frmShare');
//#region Share section
$('#frmShare').submit(function (e) {
e.preventDefault();
if (!$(this).valid()) return false;
var emailList = $("#txtEmails").tagsinput('items');
if (_.filter(emailList, function (x) { return x.toLowerCase() == _config.myEmail.toLowerCase() }).length > 0) {
App.notify.Warning(_config.notOwnEmailNoticeTxt)
return false;
}
if (_.filter(emailList, function (x) { return !isStringEmail(x) }).length > 0) {
App.notify.Warning(_config.onlyValidEmailNoticeTxt)
return false;
}
App.loader.showLoader();
$http.post($(this).attr('action'), $(this).serialize())
.then(
function (r) {
if (r.status == 200 && r.data.status == 1) {
$http.post(_config.getSharedFriendsUri)
.then(function (res) {
if (res.status == 200) {
$scope.obj.sharedToFriends = res.data;
$scope.obj.submitClicked = true;
$('#txtEmails').val('');
App.loader.hideLoader();
}
})
}
else
App.loader.hideLoader();
}
)
})
$('#frmFbShare').submit(function (e) {
e.preventDefault();
})
$('#txtEmails')
.on('beforeItemAdd', function (event) {
$('.bootstrap-tagsinput input:eq(0)').css('width', '100%');
}).on('itemAdded', function (event) {
if (!isStringEmail(event.item))
return;
hideEmailErr();
}).on('itemRemoved', function (event) {
if (!isStringEmail(event.item))
return;
});
$('#txtEmails').tagsinput({
tagClass: function (item) {
return (isStringEmail(item) ? 'label-info' : 'label-danger');
},
trimValue: true,
confirmKeys: [13, 188, 44, 32]
});
//#endregion
$('#MemberInfo_State').change(function () {
var val = $(this).val();
$('#drpState').val(val);
})
$('#frmAvatar').submit(function (e) {
e.preventDefault();
App.loader.showLoader();
var formData = new FormData(document.getElementById('frmAvatar'));
if ($('#flePic').val().length > 0)
formData.append('file', App.dataURItoBlob($('.photo-holder:eq(0)').data('img')));
formData.append('name', $('#hdnFileName').val());
formData.append('rotation', $('#hdnRotate').val());
$scope.obj.isUploading = true;
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log(percentComplete);
$('.upload-progress-box').show();
$('.upload-progress-box .upload-progress').css('width', percentComplete + '%');
if (percentComplete === 100) {
$('.upload-progress-box').hide();
$('.upload-progress-box .upload-progress').css('width', '0px');
}
}
}, false);
return xhr;
},
url: $(this).attr('action'),
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function (d) {
$scope.obj.isUploading = false;
$('.upload-progress-box .upload-progress').css('width', '')
if (d.status == 1) {
if ($('#flePic').val().length > 0)
$('#main_menu .username + img.round-user-image100').attr('src', $('.photo-holder:eq(0)').data('img'));
else
$('#main_menu .username + img.round-user-image100').removeAttr('src');
$("#flePic").val('');
$("#hdnFileName").val('');
$scope.obj.uploadedPic = null;
$scope.obj.hasPhoto = false;
$('#btnAddPhoto').hide();
App.inlineSuccessAlert('#frmAvatar .circle_v2:eq(0)', _config.uploadSuccessTxt, App.placement.after);
$scope.$apply();
clearRotation();
}
else {
App.notify.Danger(d.message)
}
App.loader.hideLoader();
},
error: function () {
App.loader.hideLoader();
}
});
})
$("#flePic").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
var frag = this.files[0].name.split('.');
var ext = frag[frag.length - 1];
App.loader.showLoader();
reader.onload = function (e) {
var scaled = App.resizeImage(e.target.result, ext == 'jpg' ? 'jpeg' : ext, 200);
var image = scaled == 'data:,' ? e.target.result : scaled;
App.loader.hideLoader();
$scope.obj.hasPhoto = true;
$scope.$apply();
angular.element(function () {
clearRotation();
$('.photo-holder:eq(0)').data('img', image);
$('.photo-holder:eq(0)').css('background-image', 'url(' + (image) + ')');
//immediately open modal to upload
$('[data-click-continue="App.Account.Register.submitPhoto"]').click();
})
}
reader.readAsDataURL(this.files[0]);
$("#hdnFileName").val(this.files[0].name);
}
});
// password toggle
$('.pass-text-toggle').click(function () {
var $icon = $(this).find('i');
var isHidden = $icon.hasClass('fa-eye-slash');
if (isHidden) { // unhide password
$icon.removeClass('fa-eye-slash');
$icon.addClass('fa-eye');
$('#MemberInfo_Password').attr('type', 'text');
$('#MemberInfo_ConfirmPassword').attr('type', 'text');
return;
}
$icon.removeClass('fa-eye');
$icon.addClass('fa-eye-slash');
$('#MemberInfo_Password').attr('type', 'password');
$('#MemberInfo_ConfirmPassword').attr('type', 'password');
})
App.passwordNotice('#MemberInfo_Password', '#passNotice');
// show error if exists
if ($('#lnkWarning').length > 0) $('#lnkWarning').click();
// tab selection on load
if (_config.isLoggedIn) {
if (!_config.userState || $.trim(_config.userState).length == 0) {
// insert complete pixel
if ($.trim(_config.src).length > 0) {
var pxReg = App.readCookie(_config.pxRegister + _config.src);
if (pxReg == null || $.trim(pxReg).length == 0) {
var px = $('#complete_' + _config.src).val();
$('body').append(px);
App.createCookie(_config.pxRegister + _config.src, App.guid(), 1);
}
}
return;
}
}
// clear style from survey
if ($('.text-center-xs-right-md').length > 0) {
$('#aboutSlide p.body-font.txt-left').addClass('text-center').removeClass('txt-left');
$('#aboutSlide .heading-font-h6').addClass('margin-b30');
$('.text-center-xs-right-md').addClass('text-center').removeClass('text-center-xs-right');
$('.question-container').removeClass('layout-wrapper');
$('#aboutSlide>div.cp-elements-wrapper>div').removeClass('margin-t40');
}
if (_config.fromSocialConnect) {
$('#introSlide').addClass('hide');
$('#socialSlide').removeClass('hide');
$scope.$apply(function () { $scope.obj.progressPerc = 90.0; })
}
})
});
};
var submitPhoto = function () {
$('#frmAvatar').submit();
};
return { init: init, submitPhoto: submitPhoto };
}();
App.Account.RegisterC = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, $timeout, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {
submitClicked: false,
delvieryObj: {
hasGlobalLookup: _config.deliveryObj.hasGlobalLookup,
phone: _config.deliveryObj.phone,
userPin: _config.deliveryObj.userPin,
addressMain: _config.deliveryObj.userAddress,
userAddress4: _config.deliveryObj.userAddress4,
userAddress3: _config.deliveryObj.area
},
progressPerc: null
};
$scope.obj.hasPhoto = false;
$scope.obj.suburbList = _config.indoDistrictList;
$scope.obj.address2List = _config.indoSubDistrictList;
$scope.obj.hasFb = _config.hasFb;
$scope.obj.hasIg = _config.hasIg;
$scope.obj.uploadedPic = _config.uploadedPic;
$scope.obj.hasPhoto = false;
$scope.obj.shareMessage = _config.message;
$scope.obj.nextFinalSLide = function () {
$('#socialSlide').addClass('hide');
$('#finalSlide').removeClass('hide').slideDown();
$scope.obj.progressPerc = 100;
angular.element(function () {
App.scrollTo('#finalSlide', 300);
$('.survey_Qgraph_div').addClass('bar-full');
})
};
$scope.obj.nextDeliverySLide = function () {
var $currentSlide = $('.delivery-slide:visible');
var isLastSlide = $currentSlide.next('.delivery-slide').length === 0;
var $form = $('#frmDeliverySlide');
App.resetFormError('#frmDeliverySlide');
var isCurrentSlideValid = $currentSlide.find('input[name], select[name]').valid();
if (isCurrentSlideValid && isLastSlide) { //submit info and save to DB
if (!$form.valid()) return;
App.fireDatalayerEvent('account-submit-address-c', _config.controller + '/' + _config.action, document.title);
$scope.obj.progressPerc += 10.0;
App.loader.showLoader();
$.post($form.attr('action'), $form.serialize(), function (d) {
App.fireDatalayerEvent('submit-account-register-deliveryinfo', 'account/register', document.title);
if (d.status === 1) {
$('#deliverySlide').addClass('hide');
if (_config.isProfileRequired)
$('#aboutSlide').removeClass('hide').slideDown();
else
$('#socialSlide').removeClass('hide').slideDown();
$scope.$apply(function () {
$scope.obj.progressPerc = 60.0;
App.scrollTo('#aboutSlide:visible,#socialSlide:visible', 300);
})
}
else
console.log('Error');
App.loader.hideLoader();
});
}
else if (isCurrentSlideValid) { // go next
$scope.obj.progressPerc += 10.0;
if ($('.delivery-slide').is(':visible')) {
App.fireDatalayerEvent('account-submit-post-c', _config.controller + '/' + _config.action, document.title);
$scope.obj.delvieryObj.dynamicPostCode(function () {
$currentSlide.addClass('hide');
$currentSlide.next('.delivery-slide').removeClass('hide').slideDown(200);
});
}
else {
$currentSlide.addClass('hide');
$currentSlide.next('.delivery-slide').removeClass('hide').slideDown(200);
}
App.scrollTo('.delivery-slide', 300);
}
};
$scope.obj.nextInfoSLideCounter = 0;
$scope.obj.nextInfoSLide = function () {
var $currentSlide = $('.info-slide:visible');
var isLastSlide = $currentSlide.next('.info-slide.hide').length === 0;
var $form = $('#frmInfoSlide');
App.resetFormError('#frmInfoSlide');
var isCurrentSlideValid = $currentSlide.find('input[name], select[name]').valid();
if (isCurrentSlideValid && isLastSlide) { //submit info and save to DB
if (!$form.valid()) return;
App.fireDatalayerEvent('account-submit-agree-c', 'account/register', document.title);
$scope.obj.progressPerc += 5.0;
App.loader.showLoader();
var formData = new FormData(document.getElementById('frmInfoSlide'));
$scope.obj.isUploading = true;
$.ajax({
url: $form.attr('action'),
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function (d) {
App.fireDatalayerEvent('submit-account-register-registryinfo', 'account/register', document.title);
$timeout(function () {
$scope.obj.isUploading = false;
if (d.status === 1) {
$('#MVCProductID').val(d.id);
$('#infoSlide').addClass('hide');
$('#deliverySlide').removeClass('hide').slideDown();
App.scrollTo('#deliverySlide', 300);
App.loader.hideLoader();
}
else {
if (d.message.toLowerCase().indexOf('already exists') > -1) {
var errTpl = _config.emailAccountErr;
App.notify.Danger(errTpl);
$('.lnk-use-other-email').click(function (e) {
e.preventDefault();
$('#frmInfoSlide .info-slide:visible').addClass('hide');
$('#frmInfoSlide .info-slide:eq(1)').removeClass('hide');
$('[data-notify]').remove();
$('#MemberInfo_Email').focus().select();
})
}
else
App.notify.Danger(d.message);
App.loader.hideLoader();
}
});
},
error: function () {
App.loader.hideLoader();
}
});
}
else if (isCurrentSlideValid) { // go next
var dataLayerKey = $scope.obj.nextInfoSLideCounter == 1 ? 'account-submit-secureacc-c' :
$scope.obj.nextInfoSLideCounter == 2 ? 'account-submit-gender-c' :
$scope.obj.nextInfoSLideCounter == 3 ? 'account-submit-bday-c' :
$scope.obj.nextInfoSLideCounter == 4 ? 'account-submit-agree-c)' :
'account-submit-name-c';
$scope.obj.nextInfoSLideCounter++;
App.fireDatalayerEvent(dataLayerKey, _config.controller + '/' + _config.action, document.title);
$currentSlide.addClass('hide');
$currentSlide.next('.info-slide').removeClass('hide').slideDown(200);
$scope.obj.progressPerc += $scope.obj.progressPerc > 0 ? 5.0 : 15.0;
angular.element(function () {
App.scrollTo('.info-slide:visible', 300);
})
}
};
$scope.obj.showTab = function (selector) {
var $tab = $(selector);
$tab.tab('show');
$('html, body').animate({
scrollTop: $tab.offset().top
}, 500);
}
$scope.obj.addPhotoBox = function () {
if ($scope.obj.hasPhoto) return;
$scope.obj.currentAvatar = $('.photo-holder:eq(0)').data('img');
$('#flePic').click();
}
$scope.obj.addPhoto = function () {
$scope.obj.currentAvatar = $('.photo-holder:eq(0)').data('img');
$('#flePic').click();
}
$scope.obj.deletePhoto = function () {
$('.photo-holder:eq(0)').data("img", '');
$('.photo-holder').css('background-image', 'none');
$("#flePic").val('');
$("#hdnFileName").val('');
$scope.obj.uploadedPic = '';
$scope.obj.hasPhoto = false;
}
var clearRotation = function () {
$('.photo-holder:eq(0)').removeClass('rotate-90').removeClass('rotate-180').removeClass('rotate-270'); // remove rotation
$('#hdnRotate').val('');
}
$scope.obj.rotateElement = function (selector, deg) {
var className = '';
var $obj = $(selector);
var $hdn = $('#hdnRotate');
var current = parseInt($hdn.val());
if (!current || current == null || isNaN(current)) current = 0;
current += deg;
if (current == 360 || current == -360) { current = 0; $hdn.val(0); }
switch (current) {
case -270: case 90: className = 'rotate-90'; break;
case -180: case 180: className = 'rotate-180'; break;
case -90: case 270: className = 'rotate-270'; break;
}
$hdn.val(current);
$obj.removeClass('rotate-90').removeClass('rotate-180').removeClass('rotate-270').addClass(className);
}
$scope.obj.skipToHome = function () {
App.loader.showLoader();
window.location = "/";
}
$scope.obj.goToNextDelivery = function () {
//$scope.obj.setIdState();
$('#divSuccessInfo').addClass('hide');
$('[href="#delivery"]').click();
$timeout(function () { $('#frmInfo').show(); }, 200);
};
$scope.obj.setSocial = function (u) {
App.loader.showLoader();
window.location = u;
};
//#region share section
$scope.obj.getShareStatus = function (s) {
if (s.Status == null) s.Status = 0;
return _.find(_config.shareStatus, function (x) { return x.key == s.Status });
};
$scope.obj.shareFb = function () {
var uri = _config.shareToFbUri + '&message=' + encodeURIComponent($scope.obj.shareMessage);
App.loader.showLoader();
App.fbFeedDialog(_config.linkToShare, function () {
$http.post(uri)
.then(function (res) {
if (res.status == 200) {
if (res.data.status == 1) {
App.notify.Success(_config.successTxt);
$scope.obj.shareMessage = null;
return;
}
else
App.notify.Warning(res.data.message);
App.loader.hideLoader();
}
})
})
}
$scope.obj.removeFriend = function (s) {
var uri = _config.unsubUri + '&id=' + s.Guid;
App.loader.showLoader();
$http.post(uri)
.then(function (res) {
if (res.status == 200) {
if (res.data.status == 1) {
App.notify.Success(_config.successTxt);
$scope.obj.sharedToFriends = _.reject($scope.obj.sharedToFriends, function (x) { return x.Id == s.Id });
}
else
App.notify.Danger(res.data.message);
App.loader.hideLoader();
}
})
}
$scope.obj.resendEmail = function (s) {
var email = prompt('Please enter email');
if (email == null || email.length == 0)
return;
if (!isStringEmail(email))
return;
App.loader.showLoader();
var uri = _config.resendEmailUri + "?id=" + s.Id + '&e=' + encodeURIComponent(email);
$http.post(uri)
.then(function (res) {
if (res.status == 200) {
if (res.data.status == 1)
App.notify.Success(_config.successTxt)
else
App.notify.Danger(res.data.message);
App.loader.hideLoader();
}
})
}
$scope.obj.showPreview = function () {
// cleanup
$('#contentDiv').remove();
var iframe = document.getElementById('re_contentIframe');
iframe.src = _config.frameUri + "/" + _config.boxId + "?body=" + encodeURIComponent($('#EmailBody').val());
App.loader.showLoader();
iframe.onload = function () {
App.loader.hideLoader();
// adjust iframe height
var frame = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument;
var height = Math.max(frame.document.documentElement.clientHeight, frame.document.documentElement.scrollHeight, frame.document.documentElement.offsetHeight);
document.getElementById('re_contentIframe').style.height = /*height + */'500px';
// show modal
$('#modalEmailBody').modal();
}
}
function hideEmailErr() {
$('#err_recipientsList').addClass('hide');
}
function isStringEmail(email) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(email);
}
//#endregion
var resendEmail = function () {
App.loader.showLoader();
$.post(_config.resendEmailUri, function (d) {
if (d.status == 1) {
App.notify.Success(_config.uploadSuccessTxt);
}
App.loader.hideLoader();
});
};
//#region Post code lookup func
$scope.obj.delvieryObj.dynamicFields = _config.deliveryObj.dynamicFields;
$scope.obj.delvieryObj.marketSelected = _config.deliveryObj.market;
$scope.obj.delvieryObj.nameSpace = _config.deliveryObj.nameSpace;
$scope.obj.delvieryObj.showCountryOption = _config.deliveryObj.showCountryOption;
$scope.obj.delvieryObj.hasPostcodeLookup = _config.deliveryObj.hasPostcodeLookup;
$scope.obj.delvieryObj.userState = _config.deliveryObj.state;
$scope.obj.delvieryObj.stateList = _config.deliveryObj.stateList;
$scope.obj.delvieryObj.userSuburb = _config.deliveryObj.indoDistrict;
$scope.obj.delvieryObj.userAddress2 = _config.deliveryObj.indoSubDistrict;
$scope.obj.delvieryObj.hasDynamicSuburb = function () { return _.filter(_config.deliveryObj.dynamicSuburbCountries, function (x) { return x == $scope.obj.delvieryObj.marketSelected }).length > 0; };
$scope.obj.delvieryObj.hasLookupData = function () { return !$.isEmptyObject($scope.obj.delvieryObj.lookupData); };
$scope.obj.delvieryObj.hasReturnedLookup = false;
$scope.obj.delvieryObj.postcodeAreaListing = [];
$scope.obj.delvieryObj.suburbFiltered = function () {
if (!$scope.obj.delvieryObj.dynamicFields.hasNoPost || $scope.obj.delvieryObj.userState == null)
return $scope.obj.delvieryObj.suburbList;
return _.filter($scope.obj.delvieryObj.suburbList, function (s) { return $scope.obj.delvieryObj.userState == s.state });
};
$scope.obj.delvieryObj.canShowInput = function () {
return (!$scope.obj.delvieryObj.hasGlobalLookup || ($scope.obj.delvieryObj.hasGlobalLookup && $scope.obj.delvieryObj.hasReturnedLookup));
};
$scope.obj.delvieryObj.dynamicPostCode = function (callback) {
//if (!$scope.obj.delvieryObj.hasGlobalLookup || !!!$scope.obj.delvieryObj.userPostCode || $.trim($scope.obj.delvieryObj.userPostCode).length < 2) return;
App.loader.showLoader();
$http.post(_config.deliveryObj.getDynamicPcListUri, $.param({ code: $scope.obj.delvieryObj.userPostCode, country: $scope.obj.delvieryObj.marketSelected }))
.then(function (d) {
if (d.status === 200) { //success
$scope.obj.delvieryObj.hasReturnedLookup = true;
$('#btnRegisterDelivery').removeClass('hide');
var data = d.data;
if (data.status === 0) {
$scope.obj.delvieryObj.lookupData = {};
$scope.obj.delvieryObj.stateList = data.states;
$scope.obj.delvieryObj.suburbList = [];
$scope.obj.delvieryObj.address3List = [];
$scope.obj.delvieryObj.address4List = [];
clearLookup();
App.loader.hideLoader();
angular.element(function () {
unitOfWork.util.resetFormError("#frmDeliverySlide");
unitOfWork.util.formValidateReset("#frmDeliverySlide");
if (callback) callback();
});
return;
}
$scope.obj.delvieryObj.lookupData = data;
$scope.obj.delvieryObj.setLookupData(data);
angular.element(function () {
if (callback) callback();
})
}
App.loader.hideLoader();
}, function () { App.loader.hideLoader(); });
};
function clearLookup() {
$scope.obj.delvieryObj.userSuburb = null;
$scope.obj.delvieryObj.userState = null;
$scope.obj.delvieryObj.userAddress3 = null;
$scope.obj.delvieryObj.userAddress4 = null;
$scope.obj.delvieryObj.userStateName = null;
}
var returnLocation = function (x) {
return { state: x.State, text: (x.Eng || '') + ($.trim((x.Local || '')).length > 0 && $.trim((x.Eng || '')).length > 0 ? '-' : '') + (x.Local || ''), val: ($.trim(x.Eng || '').length > 0 ? x.Eng : x.Local) };
};
var firstOrDefault = function (x, k) {
if (!!!x || x == null || x.length == 0) return null;
return x[0][k];
};
$scope.obj.delvieryObj.setLookupData = function (data) {
clearLookup();
$scope.obj.delvieryObj.stateList = data.States;
$scope.obj.delvieryObj.suburbList = _.map(data.Suburbs, returnLocation); //_.pluck(data.Suburbs, 'Eng');
$scope.obj.delvieryObj.address3List = _.map(data.Address3s, returnLocation); //_.pluck(data.Address3s, 'Eng');
$scope.obj.delvieryObj.address4List = _.map(data.Address4s, returnLocation); //_.pluck(data.Address4s, 'Eng');
if ($scope.obj.delvieryObj.stateList.length === 1) {
$scope.obj.delvieryObj.userState = $scope.obj.delvieryObj.stateList[0].State;
$scope.obj.delvieryObj.userStateName = $scope.obj.delvieryObj.stateList[0].Name;
}
if ($scope.obj.delvieryObj.suburbList.length <= 1)
$scope.obj.delvieryObj.userSuburb = firstOrDefault($scope.obj.delvieryObj.suburbList, 'text');
if ($scope.obj.delvieryObj.address3List.length <= 1)
$scope.obj.delvieryObj.userAddress3 = firstOrDefault($scope.obj.delvieryObj.address3List, 'text');
if ($scope.obj.delvieryObj.address4List.length <= 1)
$scope.obj.delvieryObj.userAddress4 = firstOrDefault($scope.obj.delvieryObj.address4List, 'text');
angular.element(function () {
unitOfWork.util.resetFormError("#frmDeliverySlide");
unitOfWork.util.formValidateReset("#frmDeliverySlide");
});
};
//#endregion
angular.element(function () {
//#region Post Lookup
$scope.obj.delvieryObj.userPostCode = _config.deliveryObj.userPostCode;
$scope.obj.delvieryObj.userSuburb = _config.deliveryObj.userSuburb; // assign district
$scope.obj.delvieryObj.userAddress2 = _config.deliveryObj.subDistrict; // assign subdistrict
$scope.obj.delvieryObj.userAddress3 = _config.deliveryObj.area; // assign area
if ($scope.obj.delvieryObj.dynamicFields.hasNoPost) // immediately load details for no postcode with global address
$scope.obj.delvieryObj.dynamicPostCode();
//#endregion
// add asterisk on required label fields
$('[data-val-required]').parents('.form-group').find('label[for]:eq(0)').addClass('required');
$('[href="#collapse-tab_new1"] .count').text($('#regTab li[role="presentation"]').length);
$('[href="#collapse-tab_new1"] .count').removeClass('hide');
// set all email resend buttons
$('.btn-resend-email-validation').click(function () {
resendEmail();
});
$('#cmn-toggle-fb, #cmn-toggle-ig').click(function (e) {
e.preventDefault();
App.fireDatalayerEvent('account-submit-socials-c', _config.controller + '/' + _config.action, document.title);
var lnk = $(this).attr('href');
window.location = lnk;
});
$('#lnkShareEmail').on('click', function (e) {
e.preventDefault();
$('#lnkShareEmail i,#lnkShareFb i').removeClass('active');
$('#divShareFb').addClass('hidden');
$('#divShareEmail').removeClass('hidden');
$('#lnkShareEmail i').addClass('active');
$('.circle_v2.circle-purple-hover').removeClass('active')
$(this).addClass('active');
App.scrollTo('#divShareEmail', 1000);
});
$('#lnkShareFb').on('click', function (e) {
e.preventDefault();
$('#lnkShareEmail i,#lnkShareFb i').removeClass('active');
$('#divShareEmail').addClass('hidden');
$('#divShareFb').removeClass('hidden');
$('#lnkShareFb i').addClass('active');
$('.circle_v2.circle-purple-hover').removeClass('active')
$(this).addClass('active');
App.scrollTo('#divShareFb', 1000);
});
$('#txtFbMessage').on("focus keyup", function (e) {
var keycode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
if (keycode === 9 || !keycode) {
// select
var $this = $(this);
$this.select();
// For Chrome's bug
$this.on("mouseup", function () {
// Unbindl mouseup
$this.off("mouseup");
return false;
});
}
});
//#region Validator Reset
$.validator.addMethod('passwordpattern', function (value, element) {
var valid = false;
var $element = $(element);
if ($element.attr('id') == 'MemberInfo_Password') {
var regPass = App.passwordRegex();
valid = regPass.test(value);
}
return valid && value != null;
});
$.validator.addMethod('requiredutf8', function (value, element) {
var valid = false;
var $element = $(element);
if ($element.attr('id') == 'MemberInfo_FirstName' || $element.attr('id') == 'MemberInfo_LastName') {
var regUtf8 = new XRegExp('^(\\p{L}|[\\-0-9]){1,}(\\p{L}|[\\-0-9]|\\s){0,}$');
valid = regUtf8.test(value);
}
return valid && value != null;
});
$.validator.unobtrusive.adapters.add("mandatory", function (options) {
options.rules["required"] = true;
if (options.message) {
options.messages["required"] = options.message;
}
});
$.validator.unobtrusive.adapters.addBool("requiredutf8", "requiredutf8");
$.validator.unobtrusive.adapters.addBool("mandatory", "required");
$.validator.unobtrusive.adapters.add("checkbox", function (options) {
if (options.element.tagName.toUpperCase() === "INPUT" && options.element.type.toUpperCase() === "CHECKBOX") {
options.rules["required"] = true;
if ($.trim(options.message).length == 0) {
options.messages["required"] = $(options.element).attr('id') == "MemberInfo_Agree" ? _config.agreementText : _config.plsSpecifyText;//options.message;
}
}
});
App.formValidateReset('#frmInfoSlide');
App.formValidateReset('#frmDeliverySlide');
App.formValidateReset('#frmShare');
//#endregion
$('#MemberInfo_State').change(function () {
var val = $(this).val();
$('#drpState').val(val);
})
$('#frmAvatar').submit(function (e) {
e.preventDefault();
App.loader.showLoader();
var formData = new FormData(document.getElementById('frmAvatar'));
if ($('#flePic').val().length > 0)
formData.append('file', App.dataURItoBlob($('.photo-holder:eq(0)').data('img')));
formData.append('name', $('#hdnFileName').val());
formData.append('rotation', $('#hdnRotate').val());
$scope.obj.isUploading = true;
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log(percentComplete);
$('.upload-progress-box').show();
$('.upload-progress-box .upload-progress').css('width', percentComplete + '%');
if (percentComplete === 100) {
$('.upload-progress-box').hide();
$('.upload-progress-box .upload-progress').css('width', '0px');
}
}
}, false);
return xhr;
},
url: $(this).attr('action'),
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function (d) {
$scope.obj.isUploading = false;
$('.upload-progress-box .upload-progress').css('width', '')
if (d.status == 1) {
if ($('#flePic').val().length > 0)
$('#main_menu .username + img.round-user-image100').attr('src', $('.photo-holder:eq(0)').data('img'));
else
$('#main_menu .username + img.round-user-image100').removeAttr('src');
$("#flePic").val('');
$("#hdnFileName").val('');
$scope.obj.uploadedPic = null;
$scope.obj.hasPhoto = false;
$('#btnAddPhoto').hide();
App.inlineSuccessAlert('#frmAvatar .circle_v2:eq(0)', _config.uploadSuccessTxt, App.placement.after);
$scope.$apply();
clearRotation();
}
else {
App.notify.Danger(d.message)
}
App.loader.hideLoader();
},
error: function () {
App.loader.hideLoader();
}
});
})
$("#flePic").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
var frag = this.files[0].name.split('.');
var ext = frag[frag.length - 1];
App.loader.showLoader();
reader.onload = function (e) {
var scaled = App.resizeImage(e.target.result, ext == 'jpg' ? 'jpeg' : ext, 200);
var image = scaled == 'data:,' ? e.target.result : scaled;
App.loader.hideLoader();
$scope.obj.hasPhoto = true;
$scope.$apply();
angular.element(function () {
clearRotation();
$('.photo-holder:eq(0)').data('img', image);
$('.photo-holder:eq(0)').css('background-image', 'url(' + (image) + ')');
//immediately open modal to upload
$('[data-click-continue="App.Account.Register.submitPhoto"]').click();
})
}
reader.readAsDataURL(this.files[0]);
$("#hdnFileName").val(this.files[0].name);
}
});
// password toggle
$('.pass-text-toggle').click(function () {
var $icon = $(this).find('i');
var isHidden = $icon.hasClass('fa-eye-slash');
if (isHidden) { // unhide password
$icon.removeClass('fa-eye-slash');
$icon.addClass('fa-eye');
$('#MemberInfo_Password').attr('type', 'text');
$('#MemberInfo_ConfirmPassword').attr('type', 'text');
return;
}
$icon.removeClass('fa-eye');
$icon.addClass('fa-eye-slash');
$('#MemberInfo_Password').attr('type', 'password');
$('#MemberInfo_ConfirmPassword').attr('type', 'password');
})
App.passwordNotice('#MemberInfo_Password', '#passNotice');
// show error if exists
if ($('#lnkWarning').length > 0) $('#lnkWarning').click();
// tab selection on load
if (_config.isLoggedIn) {
if (!_config.userState || $.trim(_config.userState).length == 0) {
// insert complete pixel
if ($.trim(_config.src).length > 0) {
var pxReg = App.readCookie(_config.pxRegister + _config.src);
if (pxReg == null || $.trim(pxReg).length == 0) {
var px = $('#complete_' + _config.src).val();
$('body').append(px);
App.createCookie(_config.pxRegister + _config.src, App.guid(), 1);
}
}
return;
}
}
// clear style from survey
if ($('.text-center-xs-right-md').length > 0) {
$('#aboutSlide p.body-font.txt-left').addClass('text-center').removeClass('txt-left');
$('#aboutSlide .heading-font-h6').addClass('margin-b30');
$('.text-center-xs-right-md').addClass('text-center').removeClass('text-center-xs-right');
$('.question-container').removeClass('layout-wrapper');
$('#aboutSlide>div.cp-elements-wrapper>div').removeClass('margin-t40');
}
if (_config.fromSocialConnect) {
$('#introSlide').addClass('hide');
$('#socialSlide').removeClass('hide');
$scope.$apply(function () { $scope.obj.progressPerc = 90.0; })
}
})
});
};
var submitPhoto = function () {
$('#frmAvatar').submit();
};
return { init: init, submitPhoto: submitPhoto };
}();
App.Account.Login = function () {
var _config = {};
var init = function (config) {
if (config && typeof config === 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$scope.email = _config.email;
angular.element(function () {
$('.pass-text-toggle').click(function () {
var $icon = $(this).find('i');
var isHidden = $icon.hasClass('fa-eye-slash');
if (isHidden) { // unhide password
$icon.removeClass('fa-eye-slash');
$icon.addClass('fa-eye');
$('#Password').attr('type', 'text');
return;
}
$icon.removeClass('fa-eye');
$icon.addClass('fa-eye-slash');
$('#Password').attr('type', 'password');
});
$("#frmLogin :input").each(function () {
if ($(this).attr("name")) {
if ($(this).val().length > 0) {
$(this).parent().addClass('has-value');
} else {
$(this).parent().removeClass('has-value');
}
}
});
$('#lnkGoBack').on('click', function () {
window.history.back();
});
$('#IsPersist').on('click', function () {
$(this).val($(this).is(':checked'));
});
$('#btnEmail').click(function () {
$('.login-inputs').hide().removeClass('hide');
$('.login-inputs').slideDown();
$(this).parent().remove();
$([document.documentElement, document.body]).animate({
scrollTop: $("#welcomeHome").offset().top
}, 1000);
});
if (!_config.email.isNullOrEmpty()) {
$('.login-inputs').hide().removeClass('hide');
$('.login-inputs').slideDown();
$('#btnEmail').parent().remove();
}
});
});
(function (l) { var i, s = { touchend: function () { } }; for (i in s) l.addEventListener(i, s); })(document); // sticky hover fix in iOS
};
return { init: init };
}();
App.Account.DeleteAccount = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, $timeout, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
angular.element(function () {
$('#frmDelete').submit(function (e) {
e.preventDefault();
var $form = $(this);
if (!$form.valid()) {
return;
}
App.loader.showLoader();
$.post($form.attr('action'), $form.serialize(), function (d) {
if (d.status == 1) {
window.location = './../';
}
else
App.loader.hideLoader();
})
})
});
})
};
return { init: init };
}()
App.Account.ForgotPassword = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$(function () {
$('#lnkGoBack').on('click', function () {
window.history.back();
});
setTimeout(function () {
$('#Email').val('')
}, 300);
});
});
};
return { init: init };
}()
App.Account.ResetPassword = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
angular.element(function () {
var form = $("#frmReset");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.adapters.addBool("mandatory", "required");
$.validator.unobtrusive.adapters.addBool("passwordpattern", "passwordpattern");
$.validator.addMethod('passwordpattern', function (value, element) {
var valid = false;
var $element = $(element);
if ($element.attr('id') == 'Password') {
var regPass = App.passwordRegex();
valid = regPass.test(value);
}
return valid && value != null;
});
$.validator.unobtrusive.parse(form);
App.passwordNotice('#Password', '#passNotice', {
good: '#0edb73',
bad: 'white'
});
$('.pass-text-toggle').click(function () {
var $icon = $(this).find('i');
var isHidden = $icon.hasClass('fa-eye-slash');
if (isHidden) { // unhide password
$icon.removeClass('fa-eye-slash');
$icon.addClass('fa-eye');
$('#Password,#ConfirmPassword').attr('type', 'text');
return;
}
$icon.removeClass('fa-eye');
$icon.addClass('fa-eye-slash');
$('#Password,#ConfirmPassword').attr('type', 'password');
})
});
})
};
return { init: init };
}()
if (typeof App == 'undefined') var App = {};
App.Competitions = function () { return {} }();
App.Competitions.Index = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
});
App.angular.controller('competitionsController', function ($scope) {
// private fields
var competitions = this;
var _competitions = _config.competitions;
$(function () {
});
// public properties
competitions.competitions = function (newCompetitions) {
return arguments.length > 0 ? (competitions._competitions = newCompetitions) : _competitions;
};
});
};
return { init: init };
}();
if (typeof App == 'undefined') var App = {};
App.Dashboard = function () { return {} }();
App.Dashboard.Index = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, $compile, dateFilter, unitOfWork, ScopeStorage) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$scope.obj.hasFb = _config.hasFb;
$scope.obj.hasIg = _config.hasIg;
$scope.obj.hasTw = _config.hasTw;
$scope.obj.jsonCompletedSurveyList = _config.jsonCompletedSurveyList;
$scope.obj.commentList = _config.commentList;
$scope.obj.questionList = _config.questionList;
$scope.obj.totalComments = _config.totalComments;
$scope.obj.commentOffset = 1;
$scope.obj.uploadedPic = _config.uploadedPic;
$scope.obj.hasPhoto = false;
$scope.obj.cleanUpDate = function (d) { return d.indexOf('/Date(') > -1 ? new Date(parseFloat(d.replace('/Date(', '').replace(')/', ''))) : new Date(d); }
$scope.obj.hasMoreCompletedSurveys = function () {
return $scope.obj.jsonCompletedSurveyList.length < _config.totalCompletedSurvey;
}
$scope.obj.loadMoreCompletedSurvey = function () {
App.loader.showLoader();
var items = 10;
var page = Math.ceil($scope.obj.jsonCompletedSurveyList.length / items) + 1;
$http.post(_config.completedSurveysUri, $.param({ page, items }))
.then(function (d) {
if (d.status == 200) { //success
for (var s in d.data) {
$scope.obj.jsonCompletedSurveyList.push(d.data[s]);
}
}
App.loader.hideLoader();
}, function () { App.loader.hideLoader(); })
}
$scope.obj.showMobileTab = function () {
var isHidden = $('#myTab').is(':hidden');
var $caret = $('p.tab-selected-box .tab-caret .fa');
$caret.removeClass('fa-angle-up').removeClass('fa-angle-down');
var caret = isHidden ? 'fa-angle-up' : 'fa-angle-down';
$caret.addClass(caret);
if (isHidden)
$('#myTab').slideDown()
else
$('#myTab').slideUp('fast');
}
$scope.obj.addPhoto = function () {
$scope.obj.currentAvatar = $('.photo-holder:eq(0)').data('img');
$('#flePic').click();
};
$scope.obj.deletePhoto = function () {
$('.photo-holder:eq(0)').data("img", $scope.obj.currentAvatar);
$('.photo-holder:eq(0)').css('background-image', 'url(' + $scope.obj.currentAvatar + ')');
$("#flePic").val('');
$("#hdnFileName").val('');
$scope.obj.hasPhoto = false;
clearRotation();
};
$scope.obj.rotateElement = function (selector, deg) {
var className = '';
var $obj = $(selector);
var $hdn = $('#hdnRotate');
var current = parseInt($hdn.val());
if (!current || current == null || isNaN(current)) current = 0;
current += deg;
if (current == 360 || current == -360) { current = 0; $hdn.val(0); }
switch (current) {
case -270: case 90: className = 'rotate-90'; break;
case -180: case 180: className = 'rotate-180'; break;
case -90: case 270: className = 'rotate-270'; break;
}
$hdn.val(current);
$obj.removeClass('rotate-90').removeClass('rotate-180').removeClass('rotate-270').addClass(className);
};
$scope.obj.showTab = function (selector) {
var $tab = $(selector);
if ($tab.length > 0)
$tab.tab('show');
};
$scope.obj.showProfile = function () {
$scope.obj.showTab('.nav-tabs a[href="#profile"]');
};
$scope.obj.showAchievement = function () {
$scope.obj.showTab('.nav-tabs a[href="#mybadges"]');
};
$scope.obj.inserRawHtml = function (s) {
return $sce.trustAsHtml(s);
};
$scope.obj.showMoreComments = function () {
App.loader.showLoader();
$http.post(_config.moreCommentUri, $.param({ o: $scope.obj.commentOffset, i: 3 }))
.then(function (d) {
if (d.status == 200) { //success
for (var i in d.data) {
$scope.obj.commentList.push(d.data[i]);
}
$scope.obj.commentOffset++;
}
App.loader.hideLoader();
}, function () { App.loader.hideLoader(); })
};
$scope.obj.setSocial = function (u, p) {
var hasSocialLinked = p == 'instagram' ? $scope.obj.hasIg :
p == 'twitter' ? $scope.obj.hasTw :
$scope.obj.hasFb;
if (!hasSocialLinked) { // detach social account from HTC
if (!confirm('Are you sure you want to detach #provider# from your HTC account?'.replace('#provider#', p))) {
$scope.obj[p == 'instagram' ? 'hasIg' : p == 'twitter' ? 'hasTw' : 'hasFb'] = true;
return;
}
App.loader.showLoader();
$http.post(_config.releaseSocialUri, $.param({ provider: p }))
.then(function (d) {
if (d.status == 200 && d.data.status == 1) { //success
App.notify.Success(_config.sucessTxt);
}
App.loader.hideLoader();
}, function () { App.loader.hideLoader(); })
}
else { // link social account
App.loader.showLoader();
window.location = u;
}
};
$scope.obj.iframSource = function (x) {
return $sce.trustAsResourceUrl(x);
};
//#region User Uploads
var rebuildModalVideo = function () {
// re-bind modal pop-up
$('.upload-video-popup').magnificPopup({
fixedContentPos: false, // prevent scroll top on img click
mainClass: 'mfp-with-zoom mfp-img-mobile',
zoom: {
enabled: true
},
closeMarkup: ''
});
};
$scope.obj.uploadItem = 4;
$scope.obj.uploadPage = 1;
$scope.obj.userUploadList = _config.userUploadList;
$scope.obj.totalUserUploads = _config.totalUserUploads;
$scope.obj.showMoreUserUploads = function () {
App.loader.showLoader();
$http.post(_config.userUploadsUri, $.param({ items: $scope.obj.uploadItem, page: $scope.obj.uploadPage, filter: $scope.obj.uploadFilter }))
.then(function (d) {
if (d.status == 200) { //success
for (var i in d.data.data) {
var uu = d.data.data[i];
$scope.obj.userUploadList.push(uu);
}
$scope.obj.uploadPage++;
$scope.obj.totalUserUploads = d.data.count;
angular.element(function () {
rebuildModalVideo();
});
}
App.loader.hideLoader();
}, function () { App.loader.hideLoader(); })
};
$scope.obj.setOffline = function (e, u) {
var $obj = $(e.target);
App.loader.showLoader();
$http.post(_config.setOfflineUri, $.param({ id: u.Id }))
.then(function (d) {
if (d.status == 200) { //success
$obj.parents('.dropdown:eq(0)').remove();
App.notify.Success(_config.sucessTxt);
}
App.loader.hideLoader();
}, function () { App.loader.hideLoader(); })
};
$scope.obj.filterUploadList = function () {
if (!$scope.obj.uploadFilter || $scope.obj.uploadFilter == 0)
return $scope.obj.userUploadList;
var result = $scope.obj.userUploadList;
return _.filter(result, function (x) {
if ($scope.obj.uploadFilter == 2)
return _.filter(["vbupload", "vbrecord", "vbio", "you", "youopen", "vim", "video"], function (y) { return x.FileType.toLowerCase() == y }).length > 0;
else
return x.FileType.toLowerCase() == 'img';
});
};
$scope.obj.uploadListFilter = function (t) {
$scope.obj.uploadFilter = t;
};
//#endregion
//#region Badge/Achievements
$scope.obj.productListTemplate = (function () { return $('#tmplPlist').clone().html(); })();
$scope.obj._selectedItem = {};
$scope.obj.badgeGroupSelect = 0;
$scope.obj.showAchievedOnly = false;
$scope.obj.badgeList = _config.badgeList;
$scope.obj.achievements = _config.achievements;
$scope.obj.newBadges = _config.newBadges;
$scope.obj.categories = _config.categories;
$scope.obj._products = [];
$scope.obj.productCategory = [
{ type: 'Reviews_Beauty', cid: [10] },
{ type: 'Reviews_Food', cid: [1, 2, 3, 5, 16] },
{ type: 'Reviews_House', cid: [4, 6, 7, 8, 9, 12] },
{ type: 'Reviews_Kids', cid: [15] },
{ type: 'Reviews_Pet', cid: [14] }
];
$scope.obj.divToggle2 = function (pin, cin, item, x, parent, prefix) {
$('.more-info-holder').remove();
if ($scope.obj._selectedItem.item && $scope.obj._selectedItem.item.BadgeCode == item.BadgeCode) {
$scope.obj._selectedItem = {};
return;
}
var mappedList = [];
$('#' + parent + ' .item-acquired').each(function (index, value) {
mappedList.push({ id: $(this).attr('id'), top: $(this).position().top });
});
var currentId = prefix + '_' + pin + '_' + cin;
var currentObject = $('#' + currentId);
var nextObject = null;
var currentIndex = _.findIndex(mappedList, function (x) { return x.id == currentId; });
if (currentIndex == mappedList.length - 1)
nextObject = currentObject;
else {
var hasFound = false, cout = 0, currentTop = mappedList[currentIndex].top;
while (!hasFound) {
cout++;
var nextTop = mappedList[currentIndex + cout].top;
if (nextTop > currentTop) {
cout--;
hasFound = true;
}
else if ((currentIndex + cout) == mappedList.length - 1)
hasFound = true;
}
nextObject = $('#' + mappedList[currentIndex + cout].id);
}
$scope.obj._selectedItem.item = item;
$scope.obj._selectedItem.x = x;
var template = angular.element('#tmplMoreInfo').clone().html();
var result = $compile(template)($scope);
var divToInsert = $('');
divToInsert.html(result);
nextObject.after(divToInsert);
divToInsert.slideDown({
done: function () {
$('.btn-what:eq(0)').click();
}
});
};
$scope.obj.isNotAchieved = function (b) {
if ($scope.obj.achievements.length == 0 || typeof b == 'undefined')
return true;
return typeof b.ReceivedDate === 'undefined' || b.ReceivedDate === null;
};
$scope.obj.getAlreadyAcquiredBadges = function (blist) {
var b = _.chain(blist)
.filter(function (x) {
return !$scope.obj.isNotAchieved(x);
}).sortBy(function (x) {
return x.Ord;
}).value();
if (b.length == 0)
return null;
return b;
};
$scope.obj.getLatestAchievement = function (blist) {
var b = $scope.obj.getAlreadyAcquiredBadges(blist);
if (b == null)
return null;
return b[0];
};
$scope.obj.getNextLevelBadge = function (blist) {
var b = _.chain(blist)
.filter(function (x) {
return $scope.obj.isNotAchieved(x);
}).first().value();
if (b == null) return null;
return [b]; // put in array to use ng-repeat
};
$scope.obj.myBadgeListAll = function (list) {
var result = _.flatten(list);
if ($scope.obj.showAchievedOnly) {
result = _.reject(result, function (x) {
return $scope.obj.isNotAchieved(x);
});
}
return result;
};
$scope.obj.futureList = function (list) {
var result = _.chain(list)
.filter(function (x) {
var item = $scope.obj.getLatestAchievement(x);
return $scope.obj.isNullOrUndefined(item);
})
//.filter(function (x) {
// var items = _.filter(x, function (y) {
// return y.BadgeGroup == $scope.obj.badgeGroupSelect
// });
// return items.length > 0;
//})
.value();
return result;
};
$scope.obj.myBadgeListGrouped = function (list) {
var result = _.chain(list)
.reject(function (x) {
//var items = _.filter(x, function (y) {
// return y.BadgeGroup == $scope.obj.badgeGroupSelect
//});
var items = x;
var item = $scope.obj.getLatestAchievement(items);
return $scope.obj.isNullOrUndefined(item);
})
.value();
return result;
};
$scope.obj.myBadgeList = function (list, limit) {
if (!limit) limit = null;
var result = _.chain(list)
.reject(function (x) {
var item = $scope.obj.getLatestAchievement(x);
return $scope.obj.isNullOrUndefined(item);
})
.value();
if (limit != null && limit > 0)
result = _.first(result, limit);
return result;
};
$scope.obj.isNew = function (b) {
if ($scope.obj.isNotAchieved(b) || typeof b == 'undefined')
return false;
var act = _.find($scope.obj.achievements, function (x) {
return x.BadgeId == b.Id;
});
if (act == null)
return false;
var id = _.find($scope.obj.newBadges, function (x) {
return x == act.Id;
});
return id != null;
};
$scope.obj.isNullOrUndefined = function (x) {
return typeof x == 'undefined' || x == null;
};
$scope.obj.getBadgeImage = function (item) {
if (item == null) return "";
var arr = item.BadgeCode.split('_');
var mkt = arr[0];
arr.shift();
return '/Content/Img/badges/' + mkt + '/' + arr.join('_') + '.png';
};
$scope.obj.getBadgeProgress = function (item) {
return ((item.UserHas / item.PointsAchievedAt) * 100).toFixed(1);
};
$scope.obj.getCategoryByBadgeType = function (type) {
return _.find($scope.obj.productCategory, function (x) { return x.type == type; });
};
$scope.obj.countBadgeGroup = function () {
var blist = $scope.obj.myBadgeList($scope.obj.badgeList);
var arr = [];
blist.forEach(function (x) {
arr = _.union(arr, $scope.obj.getAlreadyAcquiredBadges(x));
});
//var result = _.filter(arr, function (x) {
// return x.BadgeGroup == $scope.obj.badgeGroupSelect;
//});
return arr.length;
};
$scope.obj.countFutureBadgeGroup = function () {
var blist = $scope.obj.futureList($scope.obj.badgeList);
var arr = [];
blist.forEach(function (x) {
arr.push(x[0]);
});
//var result = _.filter(arr, function (x) {
// return x.BadgeGroup == $scope.obj.badgeGroupSelect;
//});
return arr.length;
};
$scope.obj.showInfo = function (item) {
var $div = $('#div' + item.BadgeCode);
$div.slideToggle();
if ($div.data('isloaded')) return;
var category = $scope.obj.getCategoryByBadgeType(item.BadgeType);
var cidString = category.cid.toString();
var cidIndex = cidString.hashCode();
$scope.obj._products[cidIndex] = {
badgeName: item.BadgeName,
badgeAlias: item.BadgeAlias,
badgeDescription: item.Description,
badgeImage: $scope.obj.getBadgeImage(item),
products: [],
page: 1
};
if (_.filter($scope.obj.productCategory, function (x) { return x.type == item.BadgeType; }).length > 0) {
$scope.obj.loadDashboardProducts(item);
}
};
$scope.obj.loadDashboardProducts = function (item) {
var category = $scope.obj.getCategoryByBadgeType(item.BadgeType);
var cidString = category.cid.toString();
var cidIndex = cidString.hashCode();
$scope.obj._products[cidIndex].categoryImage = _.find($scope.obj.categories, function (x) {
return x.Id == category.cid[0];
}).Logo;
// _GetDashboardProducts does the randomization of data '@Url.Action("_GetDashboardProducts", "Dashboard", new { rows = 4 })&q=' + cidString + "&page=" + $scope._products[cidIndex].page
$http.post(_config.getProductUri, $.param({ q: cidString, page: $scope.obj._products[cidIndex].page, rows: 4 }))
.then(function (data) {
if (data.status == 200 && data.data.length > 0) {
$scope.obj._products[cidIndex].products = data.data.concat($scope.obj._products[cidIndex].products);
$scope.obj._products[cidIndex].products = _.uniq($scope.obj._products[cidIndex].products, function (item, key, a) {
return item.id;
});
}
var template = $scope.obj.productListTemplate.replace('obj._products.products', 'obj._products[' + cidIndex + '].products');
var result = $compile(template)($scope);
var $divInner = $('#inner' + item.BadgeCode);
var $div = $('#div' + item.BadgeCode);
$divInner.html(result);
$divInner.parent().show();
$div.data('isloaded', true);
});
}
//#endregion
$scope.obj.stripHtml = function (html) {
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
};
var clearRotation = function () {
$('.photo-holder:eq(0)').removeClass('rotate-90').removeClass('rotate-180').removeClass('rotate-270'); // remove rotation
$('#hdnRotate').val('');
};
var onWindowResize = function () {
var isMobile = $(window).width() <= 768;
var $caret = $('p.tab-selected-box .tab-caret .fa');
$caret.removeClass('fa-angle-up').removeClass('fa-angle-down');
if (!isMobile) { $('#myTab').show(); $caret.addClass('fa-angle-up') }
else { $('#myTab').hide(); $caret.addClass('fa-angle-down') }
}
$(window).resize(function () {
onWindowResize();
})
function toggleFloatTab() {
var $float = $('.float-panel-dashboard');
!$('#myTab').isInViewport() ? $float.show() : $float.hide();
resetFloatTabs();
}
function resetFloatTabs() {
var $fTabs = $('.float-panel-dashboard .float-nav-table');
$fTabs.removeClass('activebox');
$fTabs.each((i, o) => {
var obj = $(o);
if ($(`#${obj.data('tab')}`).is(':visible'))
obj.addClass('activebox');
});
}
function assignFLoatTabs() {
var $fTabs = $('.float-panel-dashboard .float-nav-table');
$fTabs.each((i, o) => {
var obj = $(o);
obj.click(function () {
$scope.obj.showTab(`ul.nav a[href="#${obj.data('tab')}"]`);
$('html, body').animate({
scrollTop: 300
}, 500);
})
});
}
function testUserPic() {
// catch failed loaded image and show name text instead for userpic
if (!$scope.obj.uploadedPic) return;
var img = new Image();
img.onerror = function () {
console.log('error called')
$scope.$apply(function () {
$scope.obj.uploadedPic = '';
$scope.obj.hasPhoto = false;
});
}
img.src = $scope.obj.uploadedPic;
}
angular.element(function () {
onWindowResize();
$(window).on('scroll resize', function () {
toggleFloatTab();
})
toggleFloatTab();
assignFLoatTabs();
testUserPic();
if (_config.hasFbCallbackWarning) {
$('#lnkFbWarning').click();
}
$('.collapse-link-invite').click('on', function (e) { e.preventDefault(); })
$('.progress-pink .progress-bar-pink').css("width",
function () {
return $(this).attr("aria-valuenow") + "%";
}
);
// add scripts here
$.validator.addMethod('passwordpattern', function (value, element) {
if (value == null || $.trim(value).length == 0) return true;
var valid = false;
var $element = $(element);
if ($element.attr('id') == 'SecurityModel_Password') {
var regPass = App.passwordRegex();
valid = regPass.test(value);
}
return valid;
});
$.validator.unobtrusive.adapters.add("mandatory", function (options) {
options.rules["required"] = true;
if (options.message) {
options.messages["required"] = options.message;
}
});
$.validator.unobtrusive.adapters.addBool("passwordpattern", "passwordpattern");
unitOfWork.util.formValidateReset("#frmSecurity");
//unitOfWork.util.formValidateReset("#frmUserInfo");
// add scripts here
$("#chkShowPass").change(function () {
var isChecked = $("#chkShowPass").prop('checked');
var selector = '#SecurityModel_Password,#SecurityModel_ConfirmPassword';
if (isChecked)
$(selector).attr('type', 'text');
else
$(selector).attr('type', 'password');
});
$('#frmUserInfo').submit(function (e) {
e.preventDefault(); //return false;
if (!$(this).valid()) return false;
App.loader.showLoader();
$.post($(this).attr('action'), $(this).serialize(), function (d) {
if (d.status == 1) {
App.inlineSuccessAlert('#frmUserInfo', _config.sucessTxt, App.placement.append);
if (d.reset == 1)
window.location.reload();
if (d.reloadtUri && d.reloadtUri.length > 0)
window.location = d.reloadtUri;
App.loader.hideLoader();
}
else {
App.notify.Danger(d.message);
App.loader.hideLoader();
}
});
});
$('#frmSecurity').submit(function (e) {
e.preventDefault();
if (!$(this).valid()) return false;
App.loader.showLoader();
$.post($(this).attr('action'), $(this).serialize(), function (d) {
if (d.status == 1) {
App.inlineSuccessAlert('#frmSecurity', _config.sucessTxt, App.placement.append);
$('#SecurityModel_Password,#SecurityModel_ConfirmPassword').val('');
App.loader.hideLoader();
}
else {
App.notify.Danger(d.message);
App.loader.hideLoader();
}
});
});
// add callbacks for tab click events (before shown)
//$('a[data-toggle="tab"]').on('show.bs.tab', function (e) { })
$(document).on('show.bs.tab', '.nav-tabs-responsive [data-toggle="tab"]', function (e) { console.log(e); });
//fakewaffle.responsiveTabs(['xs', 'sm']);
$('#frmAvatar').submit(function (e) {
e.preventDefault();
App.loader.showLoader();
var formData = new FormData(document.getElementById('frmAvatar'));
if ($('#flePic').val().length > 0)
formData.append('file', App.dataURItoBlob($('.photo-holder:eq(0)').data('img')));
formData.append('name', $('#hdnFileName').val());
formData.append('rotation', $('#hdnRotate').val());
$scope.obj.isUploading = true;
//$scope.$apply();
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log(percentComplete);
$('.upload-progress-box').show();
$('.upload-progress-box .upload-progress').css('width', percentComplete + '%');
if (percentComplete === 100) {
$('.upload-progress-box').hide();
$('.upload-progress-box .upload-progress').css('width', '0px');
}
}
}, false);
return xhr;
},
url: $(this).attr('action'),
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function (d) {
$scope.obj.isUploading = false;
$('.upload-progress-box .upload-progress').css('width', '')
if (d.status == 1) {
var imagePath = d.path.replace('/thumb_', '/'); // get big image
clearRotation();
if ($('#flePic').val().length > 0)
$('#main_menu .username + img.round-user-image100').attr('src', imagePath);
else
$('#main_menu .username + img.round-user-image100').removeAttr('src');
$("#flePic").val('');
$("#hdnFileName").val('');
$('.photo-holder:eq(0)').data('img', imagePath);
$('.photo-holder:eq(0)').css('background-image', 'url(' + imagePath + ')')
$scope.obj.uploadedPic = $('.photo-holder:eq(0)').data('img');
$scope.obj.hasPhoto = false;
$scope.$apply();
App.inlineSuccessAlert('#frmAvatar', _config.uploadSuccessTxt, App.placement.after);
}
else {
App.notify.Danger(d.message)
}
App.loader.hideLoader();
},
error: function () {
App.loader.hideLoader();
}
});
});
$("#flePic").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
var frag = this.files[0].name.split('.');
var ext = frag[frag.length - 1];
App.loader.showLoader();
reader.onload = function (e) {
var scaled = App.resizeImage(e.target.result, ext == 'jpg' ? 'jpeg' : ext, 200);
var image = scaled == 'data:,' ? e.target.result : scaled;
App.loader.hideLoader();
$scope.obj.hasPhoto = true;
$scope.$apply();
angular.element(function () {
$('.photo-holder:eq(0)').data('img', image);
$('.photo-holder:eq(0)').css('background-image', 'url(' + (image) + ')');
})
}
reader.readAsDataURL(this.files[0]);
$("#hdnFileName").val(this.files[0].name);
}
});
// re-bind modal pop-up
rebuildModalVideo();
App.passwordNotice('#SecurityModel_Password', '#passNotice');
// password toggle
$('.pass-text-toggle').click(function () {
var $icon = $(this).find('i');
var isHidden = $icon.hasClass('fa-eye-slash');
if (isHidden) { // unhide password
$icon.removeClass('fa-eye-slash');
$icon.addClass('fa-eye');
$('#SecurityModel_Password').attr('type', 'text');
$('#SecurityModel_ConfirmPassword').attr('type', 'text');
return;
}
$icon.removeClass('fa-eye');
$icon.addClass('fa-eye-slash');
$('#SecurityModel_Password').attr('type', 'password');
$('#SecurityModel_ConfirmPassword').attr('type', 'password');
});
// scroll to tab on mobile
$('#myTab a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//e.target // newly activated tab
//e.relatedTarget // previous active tab
var href = $(this).attr('href');
toggleLeftPanel(href);
// assign text to mobile only tab header
$('.tab-selected:first').text($(this).find('.text').text());
var windowWidth = $(window).width();
if (windowWidth <= 768) { // only for mobile/small screen
// select activity if setting is chosen and sub tab is clear
if ($('#myTab2 li[role="presentation"].active').length === 0) $('#aboutme-tab').click();;
// hide tabs for mobile
$('#myTab').slideUp();
$('p.tab-selected-box .tab-caret .fa').removeClass('fa-angle-up').addClass('fa-angle-down');
$('html, body').animate({
scrollTop: $(href).offset().top - 200
}, 100);
}
toggleForcedWidth(href);
});
function toggleForcedWidth(hash) {
if (hash !== '#mysettings' && ($('.your-product-test-cshtml').length === 0 && $('.box-test-listing').length === 0)) {
$('.right-panel, .top-tab').addClass("forced-full-width");
}
else
$('.right-panel, .top-tab').removeClass("forced-full-width");
}
function toggleLeftPanel(href) {
$('.dashboard-tabs [data-left-toggle]').hide();
if (href === '#mysettings')
$('.dashboard-tabs [data-left-toggle="togglable-tabs"]').show();
else
$('.dashboard-tabs [data-left-toggle="togglable-tasks"]').show();
}
// hot link bootstrap tabs from URL
var hash = window.location.hash ? window.location.hash.replace(/[^a-z0-9A-Z\-\_]*/gi, '') : null;
var hashProfileTabList = $('#myTab2 a[role="tab"]').map(function (x, i) { return $(i).attr('href').substr(1); }).toArray();
toggleForcedWidth(`#${hash}`);
hash && $scope.obj.showTab('ul.nav a[href="#' + hash + '"]');
hash && hashProfileTabList.filter(x => { return x === hash }).length > 0 && $scope.obj.showTab('ul.nav a[href="#mysettings"]');
toggleLeftPanel(`#${hash}`);
});
});
};
var submitPhoto = function () {
$('#frmAvatar').submit();
};
var deleteComment = function (el) {
var id = el.data('cid');
if (id === 0) return;
App.loader.showLoader();
$.post(_config.deleteCommentUri + '/' + id, function (d) {
if (d.status === 1) { //success
var $scope = angular.element($('body')).scope(); // get angular scope
$scope.$apply(function () {
$scope.obj.commentList = _.reject($scope.obj.commentList, function (x) {
return x.Id === id;
});
});
}
})
.fail(function () {
App.notify.Warning(_config.T_ErrorProcessingRequest);
})
.always(function () {
App.loader.hideLoader();
});
};
var deleteUserUpload = function (el) {
var id = el.data('cid');
if (id === 0) return;
App.loader.showLoader();
$.post(_config.deleteUserUploadUri + '/' + id, function (d) {
if (d.status === 1) { //success
var $scope = angular.element($('body')).scope(); // get angular scope
$scope.$apply(function () {
$scope.obj.userUploadList = _.reject($scope.obj.userUploadList, function (x) {
return x.Id === id;
});
// update total count
$scope.obj.totalUserUploads -= 1;
});
}
})
.fail(function () {
App.notify.Warning(_config.T_ErrorProcessingRequest);
})
.always(function () {
App.loader.hideLoader();
});
};
var deleteUserQuestion = function (el) {
var id = el.data('cid');
if (id === 0) return;
App.loader.showLoader();
$.post(_config.deleteUserQuestionUri + '/' + id, function (d) {
if (d.status === 1) { //success
var $scope = angular.element($('body')).scope(); // get angular scope
$scope.$apply(function () {
$scope.obj.questionList = _.reject($scope.obj.questionList, function (x) {
return x.Id === id;
});
});
}
})
.fail(function () {
App.notify.Warning(_config.T_ErrorProcessingRequest);
})
.always(function () {
App.loader.hideLoader();
});
};
return { init: init, submitPhoto: submitPhoto, deleteComment: deleteComment, deleteUserUpload: deleteUserUpload, deleteUserQuestion: deleteUserQuestion };
}();
if (typeof App === 'undefined') var App = {};
App.Gamification = function () {
return {};
}();
App.Gamification.Index = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) === 'object') {
$.extend(true, _config, config);
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$(function () {
// add scripts here
})
});
}
};
return { init: init };
}();
if (typeof App === 'undefined') var App = {};
App.Home = function () { return {} }();
App.Home.Index = function () {
var _config = {};
var init = function (config) {
if (config && typeof config === 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$(function () {
// add scripts here
var sliderItems = $('.home-main-slider .bxslider li').length;
var homeMainSlider = $('.home-main-slider .bxslider').bxSlider({
auto: sliderItems > 1 ? true : false,
speed: 1000,
pause: 10000,
touchEnabled: false,
onSlideBefore: function () { $('.home-main-slider .bx-default-pager').hide(); },
onSlideAfter: function () { $('.home-main-slider .bx-default-pager').show(); },
onSliderLoad: function () {
$('.home-main-slider .bx-prev').hide();
$('.home-main-slider .bx-next').hide();
var defaultPager = $('.home-main-slider .bx-default-pager');
if (this.getSlideCount() > 1) {
defaultPager.show();
}
else {
defaultPager.hide();
}
$('.home-main-slider .slider-link').removeClass('hidden');
}
});
// stop auto play on slider when clicking the pager
$('.home-main-slider .bx-pager-link').on('click', function () {
homeMainSlider.stopAuto(false);
});
homeMainSlider.swipe({ swipeRight: function (event, direction, distance, duration, fingerCount) { homeMainSlider.goToPrevSlide(); }, swipeLeft: function (event, direction, distance, duration, fingerCount) { homeMainSlider.goToNextSlide(); }, threshold: 100 });
$('.Herocounter').css('visibility', 'visible');
$('.Herocounter').counterUp({
delay: 10,
time: 2000,
formatter: function (n) {
return n.replace(/,/g, _config.thousandSepator);
}
});
$(".boxCellPic-container .boxCellPic-overlay").each(function (i, o) {
if ($(o).find('a.href-link2').length == 0) {
$(o).css('cursor', 'initial');
$(o).find('.href-link2').css('cursor', 'initial');
}
})
$(".boxCellPic-container .boxCellPic-overlay").click(function () {
if ($(this).find("a").length == 0)
return false;
window.location = $(this).find("a").attr("href");
return false;
});
});
});
};
return { init: init };
}();
App.Home.ChooseCountry = function () {
var _config = {};
var init = function (config) {
if (config && typeof config === 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {
selectCountry: function (uri, name) {
$scope.obj.selectedCountry = name;
window.location.replace(uri);
$scope.obj.isShow = false;
}
};
angular.element(function () {
$('body').click(function (evt) {
if (evt.target.id === "countrySelectList")
return;
//For descendants of menu_content being clicked, remove this check if you do not want to put constraint on descendants.
if ($(evt.target).closest('#countrySelectList').length)
return;
$scope.obj.isShow = false;
$scope.$apply();
});
});
});
};
return { init: init };
}();
App.Home.Privacy = function () {
var _config = {};
var init = function (config) {
if (config && typeof config === 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$(function () {
// add scripts here
});
});
};
return { init: init };
}();
App.Home.Disclosure = function () {
var _config = {};
var init = function (config) {
if (config && typeof config === 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$(function () {
// add scripts here
});
});
};
return { init: init };
}();
App.Home.DMCA = function () {
var _config = {};
var init = function (config) {
if (config && typeof config === 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$(function () {
// add scripts here
});
});
};
return { init: init };
}();
App.Home.Terms = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$(function () {
// add scripts here
});
});
};
return { init: init };
}();
App.Home.Page = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$(function () {
// add scripts here
});
});
};
return { init: init };
}();
if (typeof App == 'undefined') var App = {};
App.MemberArea = function () { return {} }();
App.MemberArea.MemberDetail = function () {
var _config = {};
var commentPage = 1;
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$scope.obj.commentPagesize = _config.commentsPerPage;
$scope.obj.Comments = [];
$scope.trustHtml = function (html) {
return $sce.trustAsHtml(html);
}
$scope.formatDate = function (dateStr) {
var date = new Date(parseInt(dateStr.substr(6)));
return App.formatDate(date);
}
$scope.getComments = function (url, $target, callback) {
if (typeof ($target) != 'undefined' && $target.length > 0) {
$target.loadingOverlay();
}
else {
App.loader.showLoader();
}
$http.get(url)
.then(function (response) {
// success
$scope.obj.Comments.push.apply($scope.obj.Comments, response.data.UserComments);
if (response.data.UserComments.length < $scope.obj.commentPagesize) {
$scope.obj.showMoreComments = false;
}
else {
$scope.obj.showMoreComments = true;
}
setTimeout(function () {
// post processing
//App.fixCommentsUserImage();
}, 100);
if (typeof (callback) != 'undefined') callback();
}, function (response) {
// error
}).finally(function () {
if (typeof ($target) != 'undefined' && $target.length > 0) {
$target.loadingOverlay('remove');
}
else {
App.loader.hideLoader();
}
});
}
$scope.getMoreComments = function () {
commentPage += 1;
var url = _config.commentsUrl + '?page=' + commentPage;
$scope.getComments(url);
}
$(function () {
var $commentsSection = $('#commentsSection');
if ($commentsSection.length > 0) {
$scope.getComments(_config.commentsUrl + '?page=1', $commentsSection);
}
})
});
};
return { init: init };
}()
if (typeof App == 'undefined') var App = {};
App.Notifications = function () { return {} }();
App.Notifications._NotificationHeader = function () {
var _config = {};
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
var notifCount = $('#user-menu-popover-content').find('li[data-notified="0"]').length;
if (notifCount > 0) {
$('.user-menu-link').find('span.badge').text(notifCount);
}
else {
$('.user-menu-link').find('span.badge').hide();
}
$('.notif-image').on('error', function () {
$(this).replaceWith('
');
})
};
return { init: init };
}();
App.Notifications.Index = function () {
var _config = { };
var init = function (config) {
if (config && typeof (config) == 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
$(function () {
// add event handler here
})
});
};
return { init: init };
}()
if (typeof App === 'undefined') var App = {};
App.Product = function () { return {} }();
App.Product.Index = function () {
var _config = {};
var init = function (config) {
if (config && typeof config === 'object') {
$.extend(true, _config, config);
}
};
return { init: init };
}();
App.Product.ProductSuggestion = function () {
var _config = {};
var init = function (config) {
if (config && typeof config === 'object') {
$.extend(true, _config, config);
}
App.angular.controller('MainController', function ($scope, $http, $sce, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.obj = {};
angular.element(document).ready(function () {
// add scripts here
});
});
App.angular.controller('productSuggestionController', ['$scope', '$location', '$anchorScroll', '$window', function ($scope, $location, $anchorScroll, $window) {
var productSupport = this;
productSupport.productName = '';
productSupport.brandName = '';
productSupport.suggestion = '';
productSupport.displayFailedMessage = false;
productSupport.messageTimer = null;
productSupport.hasProductNameError = false;
productSupport.hasProductBrandError = false;
productSupport.hasProductSuggestionError = false;
angular.element(document).ready(function () {
});
productSupport.submitSuggestion = function () {
// validate
var hasError = false;
if (productSupport.productName.trim() === '') {
productSupport.hasProductNameError = true;
hasError = true;
}
if (productSupport.brandName.trim() === '') {
productSupport.hasProductBrandError = true;
hasError = true;
}
if (productSupport.suggestion.trim() === '') {
productSupport.hasProductSuggestionError = true;
hasError = true;
}
if (hasError) return;
// put up the loader
App.loader.showLoader();
var data = {
productName: productSupport.productName,
brandName: productSupport.brandName,
suggestion: productSupport.suggestion
};
$.post(_config.submitFeedbackUri, data)
.done(function (result) {
if (result.result === false) {
productSupport.displayFailedMessage = true;
$location.hash('failed-message');
productSupport.startMessageTimer();
$scope.$apply();
$anchorScroll();
// hide the loader
App.loader.hideLoader();
}
else {
productSupport.productName = '';
productSupport.brandName = '';
productSupport.suggestion = '';
$scope.$apply();
$window.location.href = result.result.toString();
}
})
.fail(function () {
productSupport.displayFailedMessage = true;
$location.hash('failed-message');
productSupport.startMessageTimer();
$scope.$apply();
$anchorScroll();
// hide the loader
App.loader.hideLoader();
})
};
productSupport.startMessageTimer = function () {
// Set a timer to hide the message panel
productSupport.messageTimer = setTimeout(function () {
productSupport.messageTimer = null;
productSupport.displayFailedMessage = false;
$scope.$apply();
}, 5000);
};
}]);
};
return { init: init };
}();
App.Product.Details = function () {
var _config = { 'commentsPageSize': 15, 'commentsUrl': '', 'reviewResponseUrl': '', 'loginUrl': '', 'deleteCommentUrl': '', 'T_ErrorProcessingRequest': '' };
var init = function (config) {
if (config && typeof config === 'object') {
$.extend(true, _config, config);
}
App.angular.config(function ($locationProvider) {
// use the HTML5 History API
$locationProvider.html5Mode({
enabled: true,
rewriteLinks: false // make link on same base clickable or work normally
});
});
App.angular.controller('MainController', function ($compile, $location, $scope, $http, $sce, $anchorScroll, dateFilter, unitOfWork) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$http.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$scope.obj = {};
$scope.obj.isDebug = $location.absUrl().indexOf('debug=1') > -1 ? true : false;
$scope.obj.uId = _config.uId;
$scope.obj.canReview = _config.canReview > 0;
$scope.obj.isMobile = _config.isMobile;
$scope.commentsSearch = '';
$scope.commentsRdoRating = '';
$scope.commentType = '';
$scope.commentsStarFilter = [];
$scope.commentsTotalRows = 0; // initialized in /product/_comments
$scope.commentsTempData = [];
$scope.pagination = {
current: _config.currentPage
};
$scope.commentsOrderBy = _config.defaultOrderBy; // display radio model
$scope.currentOrderBy = _config.defaultOrderBy; //
$scope.commentsOrderByLocal = _config.defaultOrderBy; // actual order value pass as parameter
$scope.T_Reply = _config.T_Reply;
$scope.T_Cancel = _config.T_Cancel;
$scope.T_Submit = _config.T_Submit;
$scope.T_WriteYourReponsePlaceholder = _config.T_WriteYourReponsePlaceholder;
$scope.T_DeleteComment = _config.T_DeleteComment;
$scope.T_ConfirmDeleteComment = _config.T_ConfirmDeleteComment;
$scope.T_Delete = _config.T_Delete;
// initialize interface from url params
var searchObject = $location.search();
// initialize pagesize
$scope.commentsPageSize = _config.commentsPerPage; // default
if (typeof searchObject.pagesize !== 'undefined') {
$scope.commentsPageSize = searchObject.pagesize;
}
// initialize comtype
if (typeof searchObject.comtype !== 'undefined') {
$scope.commentType = searchObject.comtype;
}
// initialize sort by
if (typeof searchObject.orderby !== 'undefined') {
$scope.commentsOrderBy = searchObject.orderby;
$scope.commentsOrderByLocal = searchObject.orderby;
var comTypeAr = $scope.commentType.split(',');
if (comTypeAr.indexOf('1') > -1) { // homeTested
$scope.commentsOrderBy = 'haveTried';
}
else if (comTypeAr.indexOf('2') > -1) { // homeTested
$scope.commentsOrderBy = 'homeTested';
}
$scope.currentOrderBy = $scope.commentsOrderBy;
}
else {
// check auto reorder 'TESTED' to 'NEWEST' due to no data
var autoOrder = $('#reviewOrder').data('defaultorderby');
if (_config.defaultOrderBy !== autoOrder) {
$scope.commentsOrderBy = autoOrder;
$scope.currentOrderBy = autoOrder;
}
}
// initialize star rating filter based on startrating URL param
if (typeof searchObject.starfilter !== 'undefined') {
$scope.commentsStarFilter.push(searchObject.starfilter.split(','));
$scope.commentsRdoRating = '' + searchObject.starfilter; // check the rating radio
}
$scope.getCommentsRatingsFilter = function () {
$scope.commentsStarFilter = []; // reset star filter
var rating = $('[name=radioRating]:checked').val();
if (rating !== '') $scope.commentsStarFilter.push(rating);
};
$scope.getCommentTypeFilter = function (sortBy) {
$scope.commentsOrderByLocal = sortBy;
$scope.commentType = '';
if (sortBy === 'homeTested') {
$scope.commentsOrderByLocal = 'id desc';
$scope.commentType = '2';
}
else if (sortBy === 'haveTried') {
$scope.commentsOrderByLocal = 'id desc';
$scope.commentType = '1';
}
};
$scope.getUrlParam = function () {
var starFilters = $scope.commentsStarFilter.join(',');
var filterParam = '?page=' + $scope.pagination.current + '&pagesize=' + $scope.commentsPageSize;
filterParam += $scope.commentsOrderByLocal !== '' && typeof $scope.commentsOrderByLocal !== 'undefined' ? '&orderby=' + $scope.commentsOrderByLocal : '';
filterParam += $scope.commentType !== '' ? '&comtype=' + $scope.commentType : '';
filterParam += starFilters !== '' ? '&starfilter=' + starFilters : '';
filterParam += $scope.commentsSearch !== '' ? '&search=' + $scope.commentsSearch : '';
return filterParam;
};
$scope.getPageParam = function () {
var starFilters = $scope.commentsStarFilter.join(',');
var strFilter = '';
var filterParam = [];
if ($scope.commentsOrderByLocal !== '' && typeof $scope.commentsOrderByLocal !== 'undefined') filterParam.push('orderby=' + $scope.commentsOrderByLocal);
if ($scope.commentType !== '') filterParam.push('comtype=' + $scope.commentType);
if (starFilters !== '') filterParam.push('starfilter=' + starFilters);
if ($scope.commentsSearch !== '') filterParam.push('search=' + $scope.commentsSearch);
if (filterParam.length > 0) {
strFilter = '&' + filterParam.join('&');
}
if (_config.defaultPerPage !== $scope.commentsPageSize) {
return '?review-page=' + $scope.pagination.current + ',' + $scope.commentsPageSize + strFilter;
}
else {
return '?review-page=' + $scope.pagination.current + strFilter;
}
};
$scope.fixUserImage = function () {
$('.user-profile-img').each(function (i, div) {
var img = $(div)[0],
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
$('').attr('src', bi).on('load', function () {
$(this).remove(); // prevent memory leaks
}).on('error', function () {
var $this = $(div);
var fname = $this.data('fname');
$this.parent().html('
' + fname[0].toUpperCase() + '
');
});
});
};
$scope.getCurrDate = function () {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) { dd = '0' + dd; }
if (mm < 10) { mm = '0' + mm; }
var currDate = dd + '/' + mm + '/' + yyyy;
return currDate;
};
$scope.getChildComments = function (parentIds, callback) {
$http.post(_config.childCommentsUrl, $.param({ parentIds: parentIds }))
.then(function (response) {
// success
$scope.obj.ChildComments = response.data.ChildComments;
$scope.obj.ChildCommentsReplies = response.data.ChildCommentsReplies;
// set tooltips
$(".tooltips").tooltip({ trigger: "hover" });
// fix avatar image
//$scope.fixUserImage();
if (typeof (callback) !== 'undefined') callback();
}, function (response) {
// error
}).finally(function () {
App.loader.hideLoader();
});
};
$scope.obj.hideMoreComments = false;
$scope.getComments = function (url, callback, appendonly) {
App.loader.showLoader();
$http.get(url)
.then(function (response) {
// success
if (typeof appendonly !== 'undefined' && appendonly === true) {
$('#divReviewSection').append(response.data);
// rebind angularjs scope on appended comments
$compile($('.div-more-comments').last().contents())($scope);
}
else {
$('#divReviewSection').parent().replaceWith(response.data);
// rebind angularjs scope on divReviewSection
$compile($('#divReviewSection').parent().contents())($scope);
}
// colorize stars based on product ratings
$('.js-star-rating').makeStars();
// set tooltips
$(".tooltips").tooltip({ trigger: "hover" });
// floating label event
$('.form-floating-label input, .form-floating-label textarea').focusin(function () {
$(this).parent().addClass('has-value');
});
$('.form-floating-label input, .form-floating-label textarea').blur(function () {
if (!$(this).val().length > 0) {
$(this).parent().removeClass('has-value');
}
});
setTimeout(function () {
// fix avatar image
$scope.fixUserImage();
$.each($('.forthumbnail'), function () {
genVideoThumbnail($(this));
});
}, 300);
if (typeof callback !== 'undefined') callback();
}, function (response) {
// error
}).finally(function () {
App.loader.hideLoader();
});
};
$scope.FindUserMessageStamp = function (comment) {
return _.find($scope.obj.MessagesStamps, function (item) { return item.ItemId === comment.Id; });
};
$scope.obj.UsersUploads = [];
$scope.obj.userUploadPage = 1;
$scope.obj.showMoreUploads = true;
$scope.getUsersUploads = function (page, pageSize, orderBy, $targetContainer, successCallback, errorCallback) {
if (typeof $targetContainer !== 'undefined') {
//$targetContainer.loadingOverlay();
}
var url = _config.testersGalleryUrl + '?page=' + page + '&pageSize=' + pageSize + '&sortBy=' + orderBy;
url += $scope.obj.isDebug ? '&debug=1' : '';
$http.get(url)
.then(function (response) {
$scope.obj.Queries = response.data.Queries;
if (response.data.UsersUploads.length < $scope.obj.userUploadPagesize) {
$scope.obj.showMoreUploads = false;
}
else {
$scope.obj.showMoreUploads = true;
}
// call callback if provided
if (typeof successCallback !== 'undefined') successCallback(response.data);
}, function (response) {
// error
if (typeof errorCallback !== 'undefined') errorCallback(response);
console.log(response.statusText);
}).finally(function () {
//
if (typeof ($targetContainer) !== 'undefined') {
$targetContainer.loadingOverlay('remove');
}
});
};
$scope.getUsersReview = function (uId, callback) {
var url = _config.getUserReviewUrl + '&uId=' + uId;
$http.get(url)
.then(function (response) {
// call callback if provided
if (typeof callback !== 'undefined') callback(response.data);
}, function (response) {
// error
console.log(response.statusText);
}).finally(function () {
//
});
};
$scope.fullGalleryData = [];
$scope.obj.ngUserUploadPage = 0;
$scope.obj.showMoreUploadsFG = false;
$scope.obj.showTextLoading = true;
$scope.obj.galleryFullPerPage = _config.galleryFullPerPage;
$scope.getMoreUsersUploadsNg = function ($event) {
if ($scope.obj.showMoreUploadsFG || $scope.obj.ngUserUploadPage === 0) {
$scope.obj.ngUserUploadPage += 1;
var btn;
if (typeof $event !== 'undefined') {
// add loading to btn and disable
btn = $($event.currentTarget);
btn.prepend(' ');
btn.addClass('disabled');
}
$scope.getUsersUploads($scope.obj.ngUserUploadPage, $scope.obj.galleryFullPerPage, 'quality desc,dateCreated desc', undefined,
function (data) { // on success
$scope.obj.showTextLoading = false;
// Merges response comments to fullGalleryData
Array.prototype.push.apply($scope.fullGalleryData, data.UsersUploads);
if (data.UsersUploads.length < $scope.obj.galleryFullPerPage) {
$scope.obj.showMoreUploadsFG = false;
}
else {
$scope.obj.showMoreUploadsFG = true;
}
// Add items to modal thumbnails if not exist
var $carousel = $('#userGalleryModal .modalgallery-carousel');
for (var i = 0; i < data.UsersUploads.length; i++) {
var up = data.UsersUploads[i];
var item = $('.modalgallery-carousel').find('a[data-uploadid="' + up.Id + '"]');
if (item.length > 0) continue;
var slHtmlthumb = '
';
// find upload in carousel, add if not found
var item = $carousel.find('a[data-uploadid="' + up.Id + '"]');
if (item.length === 0) {
var slHtmlthumb = '